20

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);
    }
};
feedc0de
  • 3,646
  • 8
  • 30
  • 55
  • This code doesn't compile. You can't allocate an object of abstract type `QLayout`. See the line near the end that says `new QLayout`. – Cory Klein Jul 11 '13 at 15:58

1 Answers1

40

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.

Community
  • 1
  • 1
Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • 1
    ok thanks! why is there a setLayout void when it does nothing? – feedc0de Jul 11 '13 at 16:13
  • There is no `setLayout(void*)`. See http://qt-project.org/doc/qt-4.8/qwidget.html#setLayout. And `setLayout()` doesn't "do nothing", it sets the layout on the widget. However, if you look at the application output when running that function you should see an error saying that a layout has already been set. See the earlier documentation on `setLayout()` for an explanation of this error. – Cory Klein Jul 11 '13 at 16:28
  • Did someone edit OPs original submission? I can't figure out which two lines to replace, and I can't figure out what the resulting code looks like. Could someone please make an additional section in the answer with the resulting answer? Sincerely. – Mads Skjern Feb 13 '22 at 08:56