feedc0de
feedc0de

Reputation: 3796

Qt: Can't set layout in QMainWindow

I am trying to set my layout (using setLayout()) in my mainwindow. It does not show anything on launch:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0)
    {
        QVBoxLayout *vBoxLayout = new QVBoxLayout;
        {
            QPushButton *pushButton = new QPushButton(tr("A button"));
            vBoxLayout->addWidget(pushButton);
        }
        setLayout(vBoxLayout);
    }
};

Upvotes: 21

Views: 23779

Answers (1)

Cory Klein
Cory Klein

Reputation: 55620

You need to change the last two lines of code to be the following:

QWidget *widget = new QWidget();
widget->setLayout(VBoxLayout);
setCentralWidget(widget);
//VBoxLayout->addWidget(new QLayout);
//setLayout(VBoxLayout);

The QMainWindow is a special case. You set the contents of this widget by putting the layout in a new QWidget and then setting that as the central widget.
See this answer also.

Upvotes: 41

Related Questions