PyQt5 menubar

by Atakan

In the forms, we will examine the menu bar topic, which has an important place for user interaction.
Let’s follow these steps to create menubar in Python.

First of all, we should use the menuBar() method to get the menubar object.

menu_bar = menuBar()

This was a general menu and let’s create a general sub-menu.

file_menu = menu_bar.addMenu('File')

Let’s create submenus for this.

subMenuNew = QAction('New', self)

Here we made a sub-menu called new to put it under the File general menu.We need to use the QAction class.
The first parameter specifies the name it will receive.

.setShortcut

we can provide shortcut access from the keyboard.

.setStatusTip 

we can put an explanation of what’s going on here as well.

.triggered.connect 

After clicking, we specify the method to be triggered.

in this way

subMenuNew = QAction('New', self)
subMenuNew.setShortcut('Ctrl+N')
subMenuNew.setStatusTip('New document')
subMenuNew.triggered.connect(self.handle_new)

I added 3 sub-menus in total. The result and the full code are below.

from PyQt5.QtWidgets import QApplication, QMainWindow, QAction
import sys

W_WIDTH = 400
W_HEIGHT = 250
W_X = 400
W_Y = 150


class MainFrame(QMainWindow):
    def __init__(self):
        super(MainFrame, self).__init__()
        self.init()
        self.show()

    def create_sub_menu(self):
        self.subMenuNew = QAction('New', self)
        self.subMenuNew.setShortcut('Ctrl+N')
        self.subMenuNew.setStatusTip('New document')
        self.subMenuNew.triggered.connect(self.handle_new)

        self.subMenuOpen = QAction('Open', self)
        self.subMenuOpen.setShortcut('Ctrl+O')
        self.subMenuOpen.setStatusTip('Open document')
        self.subMenuOpen.triggered.connect(self.handle_open)

        self.subMenuSave = QAction('Save', self)
        self.subMenuSave.setShortcut('Ctrl+S')
        self.subMenuSave.setStatusTip('Save document')
        self.subMenuSave.triggered.connect(self.handle_save)

        self.file_menu.addAction(self.subMenuNew)
        self.file_menu.addAction(self.subMenuSave)
        self.file_menu.addAction(self.subMenuOpen)

    def create_menubar(self):
        self.menu_bar = self.menuBar()
        self.file_menu = self.menu_bar.addMenu('File')
        self.create_sub_menu()

    def handle_save(self):
        print("save clicked")

    def handle_open(self):
        print("open clicked")

    def handle_new(self):
        print("new clicked")

    def init(self):
        self.resize(W_WIDTH, W_HEIGHT)
        self.move(W_X, W_Y)
        self.setWindowTitle("www.langpy.com | Python GUI Tutorial")
        self.create_menubar()


app = QApplication(sys.argv)
win = MainFrame()
sys.exit(app.exec_())

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More