Search code examples
qtqwidgetqmainwindow

Qt: why adding layout to MainWindow (by code) didn't work but adding as CentralWidget worked?


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?


Solution

  • The reason is clearly described by QMainWindow documentation:

    QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. The layout has a center area that can be occupied by any kind of widget.

    and

    Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.