Creating a menubar

../_images/2_6_menubar_sample.png

GIn GUI application menubar is commonly used. Many commands are placed on the menu bar. ( QMenuBar official document )

In macOS the menu bar works differently; as seen in the below example, adding one more line of code (menubar.setNativeMenuBar(False)) allows the same results to be yielded in macOS.

First, as shown below, save the icon(exit.png) for the menu in the folder.

../_images/exit.png

Example

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_())

We made a menu bar that has one menu. This menu helps quit application when you click on it. This feature can also be run with shortcut (Ctrl+Q).


Description

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

With these four lines of codes, make an action that has an icon(exit.png) and ‘Exit’ label, and define a shortcut for this action.

Also, use setStatusTip() method to set the status tip to be displayed on the status bar when you put the cursor on the menu.


exitAction.triggered.connect(qApp.quit)

When you select this action, the triggered signal connects to the quit() method from QApplication widget and quits the application.


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

menuBar() method creates a menu bar. Then make ‘File’ menu and add ‘exitAction’ action to it.

Ampersand(&) of ‘&File’ helps create shortkeys easily. Because there is an ampersand in front of ‘F’, ‘Alt+F’ becomes the shortkey for ‘File’ menu. If you put the ampersand in front of ‘i’, then ‘Alt+I’ becomes the shortkey.


Results

../_images/2_6_menubar.png ../_images/2_6_menubar_mac.png

Figure 3-6. Creating a menubar.

Prev/Next