qt MainWindow设置layout失效

错误的做法:直接把layout设置到MainWindow上

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    QPushButton *btn1 = new QPushButton("aa", this);
    QPushButton *btn2 = new QPushButton("bb", this);
    QPushButton *btn3 = new QPushButton("cc", this);

    mainLayout->addWidget(btn1);
    mainLayout->addWidget(btn2);
    mainLayout->addWidget(btn3);

    setLayout(mainLayout);
}

报警告:QWidget::setLayout: Attempting to set QLayout "" on MainWindow "MainWindow", which already has a layout

下面看到layout实际上没生效

qt MainWindow设置layout失效_第1张图片

正确的做法:把layout设置到centralWidget上

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QWidget *centerWidget = new QWidget(this);
    setCentralWidget(centerWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    QPushButton *btn1 = new QPushButton("aa", this);
    QPushButton *btn2 = new QPushButton("bb", this);
    QPushButton *btn3 = new QPushButton("cc", this);

    mainLayout->addWidget(btn1);
    mainLayout->addWidget(btn2);
    mainLayout->addWidget(btn3);

    centralWidget()->setLayout(mainLayout);
}

qt MainWindow设置layout失效_第2张图片

你可能感兴趣的:(qt,开发语言)