在QMainWindow中显示QGridLayout

时间:2014-05-27 07:35:18

标签: c++ object user-interface layout qt4

我尝试在QMainWindow中设置QGridLayout。据我所知,这段代码看起来有效,但它不起作用。可以这样做吗?

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) 
{
   QGridLayout *layout = new QGridLayout;
   this->setLayout(layout);

   QPushButton *box1 = new QPushButton(this);
   QPushButton *box2 = new QPushButton(this);
   QPushButton *box3 = new QPushButton(this);

   layout->addWidget(box1, 0, 0);
   layout->addWidget(box2, 1, 0);
   layout->addWidget(box3, 2, 0);
}

我所看到的就是我跑这是三个按钮在彼此的顶部......

1 个答案:

答案 0 :(得分:2)

您需要使用Central Widget,因为QMainWindow是整个窗口(包含状态栏,菜单栏等):

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    this->setCentralWidget (new QWidget (this)) ;
    this->centralWidget()->setLayout(new QGridLayout());
}