Попробуйте так:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMenu, QVBoxLayout
class AppDemo(QWidget):
def __init__(self):
super().__init__()
states_cities = [
{'Список слов': ['Hello', 'World', 'How you been', 'Good to see you']},
{'Список языков': ['Английский', 'Французский', 'Испанский']},
'Help',
'Exit'
]
menu = QMenu()
menu.triggered.connect(lambda x: print(x.text()))
self.add_menu(states_cities, menu)
btn = QPushButton('My Menu', self)
btn.setMenu(menu)
def add_menu(self, data, menu_obj):
if isinstance(data, dict):
for k, v in data.items():
sub_menu = QMenu(k, menu_obj)
menu_obj.addMenu(sub_menu)
self.add_menu(v, sub_menu)
elif isinstance(data, list):
for element in data:
self.add_menu(element, menu_obj)
else:
action = menu_obj.addAction(data)
action.setIconVisibleInMenu(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())
или так:
import sys
from PyQt5.Qt import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
bar = self.menuBar()
self.file = bar.addMenu("File")
self.file.addAction("New")
save = QAction("Save", self)
save.setShortcut("Ctrl+S")
self.file.addAction(save)
edit = self.file.addMenu("Edit")
edit.addAction("copy")
edit.addAction("paste")
quit = QAction(QIcon("D:/_Qt/__Qt/img/exit.png"), "Quit",self)
quit.setShortcut('Ctrl+Q')
quit.triggered.connect(qApp.quit)
self.file.addAction(quit)
self.file.triggered[QAction].connect(self.processtrigger)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.combo = QComboBox()
self.combo.addItems(["option1", "option2", "option3", "option4"])
layout = QVBoxLayout(self.centralWidget)
layout.addWidget(self.combo)
def processtrigger(self, q):
print( q.text()+" is triggered" )
def contextMenuEvent(self, event):
result = self.file.exec_(self.mapToGlobal(event.pos()))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
ex.setWindowTitle("Qmenu")
ex.resize(350,300)
ex.show()
sys.exit(app.exec_())