Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: Can't set layout in QMainWindow

Tags:

c++

qt

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);
    }
};
like image 744
feedc0de Avatar asked Jul 11 '13 15:07

feedc0de


People also ask

How to set layout of QMainWindow?

QMainWindow has a setLayout(QLayout*) member function. Or alternate way is to use QWidget with parent 0 as a main window, and pass the pointer as a parameter to the creation of layout (or use setLayout(...)) or add the widget, as central widget for QMainWindow, with setCentralWidget(QWidget*);

What is the difference between QMainWindow and QWidget?

A QDialog is based on QWidget , but designed to be shown as a window. It will always appear in a window, and has functions to make it work well with common buttons on dialogs (accept, reject, etc.). QMainWindow is designed around common needs for a main window to have.

What is Centralwidget in Qt?

The centralwidget refers to a relative position but it is not exactly a central position: #include <QtWidgets> int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow w; QLabel *central_widget = new QLabel("Central Widget"); central_widget->setAlignment(Qt::AlignCenter); w.


1 Answers

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.

like image 180
Cory Klein Avatar answered Sep 21 '22 09:09

Cory Klein