0

https://stackoverflow.com/a/13661255/462608

QMainWindow comes with its own layout, you can't set that directly. You probably should be setting your layout on the central widget, or possibly not using a QMainWindow at all if you don't want its layout/features.

I have my own set of buttons and other things which I want to arrange in a grid.
Am I supposed to add my widgets to QMainWindow's default layout?

What should I use instead of QMainWindow if I don't want to use QMainWindow's layout? Where should QMainWindow be preferred?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

2

from the docs:

QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. The layout has a center area that can be occupied by any kind of widget. You can see an image of the layout below.

QMainWindow layout

What should I use instead of QMainWindow if I don't want to use QMainWindow's layout? Where should QMainWindow be preferred?

So, if you are interested in having QToolBars, QDockWidgets, QMenuBars, or QStatusBars, You should use QMainWindow. Otherwise, You can just use a plain QWidget.

Am I supposed to add my widgets to QMainWindow's default layout?

No, You don't have access to QMainWindow's layout. You should have a QWidget that contains all your widgets (your buttons for example) in a layout, then use that widget as QMainWindow's central widget, e.g.:

#include <QtWidgets>

int main(int argc, char* argv[]){
    QApplication a(argc, argv);
    
    QMainWindow mainWindow;
    QWidget centralWidget; //this is the widget where you put your buttons
    QGridLayout centralLayout(&centralWidget); //sets layout for the widget
    //add buttons
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            centralLayout
                    .addWidget(new QPushButton(
                                   QStringLiteral("(%0, %1)")
                                   .arg(i).arg(j)),
                               i, j);
    
    //use your widget inside the main window
    mainWindow.setCentralWidget(&centralWidget);
    //main window can have a toolbar too
    QToolBar* myToolBar = mainWindow.addToolBar("myToolBar");
    myToolBar->addAction("myToolBar action");
    //show mainwindow
    mainWindow.show();
    
    return a.exec();
}
Community
  • 1
  • 1
Mike
  • 8,055
  • 1
  • 30
  • 44