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);
}
};
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*);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With