PyQt: Create a menu bar

Menu bars are commonly used in GUI applications.A collection of program commands is located in the menu bar.

MacOS treats menubars differently than Windows or Linux systems. You can see in the example below, adding a line of code menubar.setNativeMenuBar(False) gives you the same results as your Windows experience on macOS.

Related course: Create Desktop Apps with Python PyQt5

Create a menu bar.

The program below adds a menu bar to ta PyQt5 window.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp
from PyQt5.QtGui import QIcon

class MyApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        self.statusBar()

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        filemenu = menubar.addMenu('&File')
        filemenu.addAction(exitAction)

        self.setWindowTitle('Menubar')
        self.setGeometry(300, 300, 300, 200)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

I created a menu bar with one menu. This menu has the ability to exit the application when clicked. This feature can also be executed with shortcuts (Ctrl+Q).

pyqt menu menubar

Related course: Create Desktop Apps with Python PyQt5

Description

exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')

These three lines of code create one action with an exit .png and an 'Exit' label, and define a shortcut for that action. Also, when you hovered over the menu, you set a status tip that would appear in the status bar using the setStatusTip() method.

exitAction.triggered.connect(qApp.quit)

When this behavior is selected, the generated signal is connected to the QApplication widget's quit() method and exits the application.

menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)

The menuBar() method generates a menu bar. Then create a 'File' menu and add an 'exitAction' action to it. '&file' ampersand (& ) makes it easy to set shortcuts. Because there is an ampersand in front of 'F', 'Alt+F' becomes the shortcut to the File menu. If you put the ampersand in front of the 'i', 'Alt+I' becomes the shortcut.