Linuts
Linuts

Reputation: 61

Displaying a QGridLayout from within a QMainWindow

I tried to set a QGridLayout from within a QMainWindow. As far as I can tell this code looks valid, but its not working. Can this be done?

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);
}

All I see if I run this is three buttons on top of each other...

Upvotes: -1

Views: 619

Answers (1)

Holt
Holt

Reputation: 37606

You need to use the Central Widget because the QMainWindow is the whole window (containing status bar, menu bar, etc.):

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

Upvotes: 2

Related Questions