Overdrivr
Overdrivr

Reputation: 6576

How to make a layout the main widget of a QMainWindow

Say I have two buttons, in a horizontal layout, that I need to add to a QMainWindow (basically, an app with a menu bar and two buttons in the main area).

I tried implementing it this way

class Example(QMainWindow):
    def __init__(self):
        super().__init__()

        # Menus
        exitAct = QAction(QIcon('exit.png'), '&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(qApp.quit)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)

        # central widget
        firstButton = QPushButton("first")
        secondButton = QPushButton("second")

        hbox = QHBoxLayout()
        hbox.addWidget(firstButton)
        hbox.addWidget(secondButton)

        # Not working because TypeError: setCentralWidget(self, QWidget): argument 1 has unexpected type 'QHBoxLayout'
        # self.setCentralWidget(hbox)

        # Not working because centralWidget is not set, therefore is null
        # self.centralWidget().setLayout(hbox)

        # Not working because this is a QMainWindow, and the top-level widget already has a layout containing the menu bar for instance
        self.setLayout(hbox)

        self.setGeometry(300, 300, 300, 190)
        self.setWindowTitle('Points')
        self.show()

I have defined my two buttons, created an horizontal layout and added the buttons to the layout. Now I need to tell my window to use this layout.

However, I cannot manage to add the layout to the QMainWindow, because QMainWindow already has a top level layout (for the menu bar among other things).

As a result, my buttons are not displayed. How can I achieve this ?

Upvotes: 2

Views: 1664

Answers (1)

Mel
Mel

Reputation: 6065

You can create a QWidget, apply the layout to it, and set it as the central widget:

centralWidget = QWidget()
centralWidget.setLayout(hbox)
self.setCentralWidget(centralWidget)

Upvotes: 3

Related Questions