效果如下:
代码:
1 """ 2 This program creates a menubar. 3 The menubar has one menu with an exit action. 4 """ 5 6 import sys 7 from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication 8 from PyQt5.QtGui import QIcon 9 10 11 class Example(QMainWindow): 12 13 def __init__(self): 14 super().__init__() 15 16 self.initUI() 17 18 def initUI(self): 19 20 # create an action with a specific icon and an 'Exit' label. 21 exitAct = QAction(QIcon('pictures\exit.png'), '&Exit', self) 22 23 # a shortcut is defined for this action 24 exitAct.setShortcut('Ctrl+Q') 25 # creates a status tip which is shown in the statusbar 26 # when we hover a mouse pointer over the menu item 27 exitAct.setStatusTip('Exit application') 28 # The signal is connected to the quit() method of the QApplication widget 29 exitAct.triggered.connect(qApp.quit) 30 31 self.statusBar() 32 33 # The menuBar() method creates a menubar 34 menubar = self.menuBar() 35 # create a file menu with addMenu() 36 fileMenu = menubar.addMenu('&File') 37 # add the action with addAction() 38 fileMenu.addAction(exitAct) 39 40 self.setGeometry(300, 300, 300, 200) 41 self.setWindowTitle('Simple menu') 42 self.show() 43 44 45 if __name__ == '__main__': 46 47 app = QApplication(sys.argv) 48 ex = Example() 49 sys.exit(app.exec_())