I have coded a QWidget MyWidget and I wanted to add two MyWidget with QVBoxLayout in the MainWindow class (the same MainWindow which is provided default when we open Qt Creator). So, what I did was, in the constructor of MainWindow, I took two pointers of MyWidget, make in point to an instances of the same class, then added the widgets to a QVBoxLayout and called setLayout, but when I ran the code, the ui contained nothing!
Demonstration code (didn't work):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLayout>
#include "mywidget.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVBoxLayout *layout;
layout=new QVBoxLayout();
MyWidget *a=new MyWidget(),*b=new MyWidget();
layout.addWidget(a);
layout.addwidget(b);
setLayout(layout);
}
But MainWindow showed nothing. Now, according to this answer, I have to add layout to a widget and then set the new widget as a central widget of the MainWindow. I did that and that worked.
New demonstration code (Worked):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLayout>
#include "mywidget.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVBoxLayout *layout;
layout=new QVBoxLayout();
MyWidget *a=new MyWidget(),*b=new MyWidget();
layout.addWidget(a);
layout.addwidget(b);
QWidget *window=new QWidget();
window.setLayout(layout);
setCentralWidget(window);
}
My question is why?