Qt: why adding a layout to MainWindow (by code) did not work, but adding how CentralWidget works?

I encoded a QWidget MyWidget, and I wanted to add two MyWidgets QVBoxLayoutto the class MainWindow(the same MainWindowone that is provided by default when Qt Creator opens). So, what I did, in the constructor MainWindowI took two pointers MyWidget, introduced instances of the same class into the example, then added widgets to QVBoxLayoutand named setLayout, but when I ran the code, ui did not contain anything!

Sample code (does not 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 the layout to the widget, and then install the new widget as the center widget MainWindow. I did it and it 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);
}

: ?

+4
1

QMainWindow:

QMainWindow , QToolBars, QDockWidgets, QMenuBar QStatusBar. , .

. . , .

+5

Source: https://habr.com/ru/post/1547336/


All Articles