PyQt5 Menubar Example Mar 13th 2021 Words: 267

Screenshot

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from functools import partial

from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QMainWindow, QStatusBar, QMenuBar, QActionGroup

from AboutWindow import AboutWindow


class MainWindow(QMainWindow):

def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("My App")

# Toolbar
menu_bar = QMenuBar()

# Menu
menu_menu = menu_bar.addMenu("Menu")

## Import
action_import = menu_menu.addAction("Import data")
action_import.setStatusTip("Import data from file")
action_import.triggered.connect(self.on_action_import_click)

## Export
action_export = menu_menu.addAction("Export data")
action_export.setStatusTip("Export data to file")
action_export.triggered.connect(self.on_action_export_click)

## Exit
action_exit = menu_menu.addAction("Exit")
action_exit.setStatusTip("Exit the app")
action_exit.triggered.connect(self.on_action_exit_click)

# Settings
menu_settings = menu_bar.addMenu("Settings")

## Language
menu_settings_lang = menu_settings.addMenu("Language")

action_group_lang = QActionGroup(self)
action_group_lang.setExclusive(True)

lang_list = [
("English (US)", "en_us"),
("中文(简体)", "zh_cn")
]
for lang_name, lang_code in lang_list:
action_lan_item = menu_settings_lang.addAction(lang_name)
action_lan_item.setCheckable(True)
action_lan_item.setActionGroup(action_group_lang)
action_lan_item.triggered.connect(partial(self.on_action_lang_select, lang_code))

# About
self.window_about = AboutWindow(self)
action_about = menu_bar.addAction("About")
action_about.setStatusTip("About this application")
action_about.triggered.connect(self.on_action_about_click)

self.setMenuBar(menu_bar)

# Status bar
self.setStatusBar(QStatusBar(self))

def on_action_import_click(self):
pass # TODO

def on_action_export_click(self):
pass # TODO

def on_action_about_click(self):
self.window_about.show()

def on_action_exit_click(self):
QCoreApplication.quit()

def on_action_lang_select(self, lang_code: str):
print(lang_code) # TODO

Note

To create the mutally exclusive options (eg. language selection), first create a QActionGroup and setExclusive(True), then set group for the QActions and add those QActions to a QMenu. QActionGroup does not need to be attached to anything.