pythonpyqtpyqt5qmainwindowqmenubar

How can I avoid having PyQT5 Central Widget covering up MenuBar?


The central widget in my QMainWindow keeps covering up the QMenuBar I want. How do I avoid this?

If I comment out the pushbutton, I can see the menu bar using the code below.

from PyQt5 import QtWidgets
class Test:
    def __init__(self):
        self.app = QtWidgets.QApplication([])
        self.win = QtWidgets.QMainWindow()
        self.win.resize(100,100)
        menu_bar = QtWidgets.QMenuBar(self.win)
        file_menu = menu_bar.addMenu('&File')
        pb = QtWidgets.QPushButton('push me!')
        # self.win.setCentralWidget(pb)
        self.win.show()
        self.app.exec()

if __name__  == '__main__':
    Test()

Shouldn't the QMainWindow manage to separate them according to this?

enter image description here


Solution

  • You must set the QMenuBar in the QMainWindow using setMenuBar():

    from PyQt5 import QtWidgets
    
    class Test:
        def __init__(self):
            self.app = QtWidgets.QApplication([])
            self.win = QtWidgets.QMainWindow()
            self.win.resize(100,100)
            menu_bar = QtWidgets.QMenuBar(self.win)
            self.win.setMenuBar(menu_bar)
            file_menu = menu_bar.addMenu('&File')
            pb = QtWidgets.QPushButton('push me!')
            self.win.setCentralWidget(pb)
            self.win.show()
            self.app.exec()
    
    if __name__  == '__main__':
        Test()