Qt小部件在布局中重叠

时间:2016-03-25 20:10:01

标签: c++ qt user-interface

我在主窗口的构造函数中有以下代码,它扩展了QMainWindow类:

QHBoxLayout* mainLayout = new QHBoxLayout(this);

QPushButton* button0 = new QPushButton(this);
button0->setText("Button 0");
mainLayout->addWidget(button0);

QPushButton* button1 = new QPushButton(this);
button1->setText("Button 1");
button1->setMinimumWidth(500);
mainLayout->addWidget(button1);

QPushButton* button2 = new QPushButton(this);
button2->setText("Button 2");
mainLayout->addWidget(button2);

setMinimumSize(700,480);
this->setLayout(mainLayout);

然而,当我试图运行它时,按钮似乎在左上角重叠。我应该在这里改变什么?

1 个答案:

答案 0 :(得分:1)

检查控制台输出。通常主窗口默认都有布局,然后你只需要在中央窗口小部件而不是窗口本身上设置它:

this->centralWidget()->setLayout(mainLayout);

如果中央窗口小部件不存在(例如您删除了自动生成的.ui文件),则只需手动创建:

QWidget* centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
QHBoxLayout* mainLayout = new QHBoxLayout(centralWidget);

QPushButton* button0 = new QPushButton(this);
button0->setText("Button 0");
mainLayout->addWidget(button0);

QPushButton* button1 = new QPushButton(this);
button1->setText("Button 1");
button1->setMinimumWidth(500);
mainLayout->addWidget(button1);

QPushButton* button2 = new QPushButton(this);
button2->setText("Button 2");
mainLayout->addWidget(button2);

setMinimumSize(700,480);