How to add a widget to QMainWindow layout?

c++, layout, qmainwindow, qt

Solution

You are creating a temporary parent widget on the stack, and using a reference to it for the `QPushButton` - this is a fine way to get a segfault.

The parent widget argument defaults to `nullptr`, which is acceptable for you as the layout takes ownership of it.

//QWidget wdg;
mine[i][j] = new QPushButton( " " );

The error message you are getting is answered by this question. In short it means that you should not modify the `QMainWindow` layout; you need to a create a widget, add that as the central widget, and then modify the central widget's layout.

Problem

I'm using the code below to add a QPushButton to a ui: ``` QPushButton *mine[PlayForm->horizontal][PlayForm->vertical]; for(int i=0; i<PlayForm->horizontal; i++) { for(int j=0; j<PlayForm->vertical; j++) { QWidget wdg; mine[i][j] = new QPushButton(" ", &wdg); mine[i][j]->setGeometry(size*i, size*j, size, size); mine[i][j]->show(); PlayForm->layout()->addWidget(mine[i][j]); } } ``` But I get this message: QMainWindowLayout::addItem: Please use the public QMainWindow API instead What should I do?

Original source

Related problems