上下文菜单

上下文菜单也称为弹出菜单,是在某些上下文下出现的命令列表。

例如,在Opera Web浏览器中,当我们右键单击一个Web页面时,就会得到一个上下文菜单。

在这里,我们可以重新加载一个页面,返回或查看一个页面源。如果我们右键单击工具栏,就会得到另一个用于管理工具栏的上下文菜单。

效果如下:

代码如下:

 1 #!/usr/bin/python3
 2 # -*- coding: utf-8 -*-
 3 """
 4 ZetCode PyQt5 tutorial
 5 This program creates a context menu.
 6 """
 7 
 8 import sys
 9 from PyQt5.QtWidgets import QMainWindow, qApp, QMenu, QApplication
10 
11 
12 class Example(QMainWindow):
13 
14     def __init__(self):
15         super().__init__()
16 
17         self.initUI()
18 
19     def initUI(self):
20 
21         self.setGeometry(300, 300, 300, 200)
22         self.setWindowTitle('Context menu')
23         self.show()
24 
25     # reimplement the contextMenuEvent() method.
26     def contextMenuEvent(self, event):
27 
28         cmenu = QMenu(self)
29 
30         newAct = cmenu.addAction("New")
31         opnAct = cmenu.addAction("Open")
32         quitAct = cmenu.addAction("Quit")
33 
34         # The mapToGlobal() method translates the widget coordinates
35         # to the global screen coordinates
36         action = cmenu.exec_(self.mapToGlobal(event.pos()))
37 
38         # If the action returned from the context menu equals to quit action,
39         # we terminate the application.
40         if action == quitAct:
41             qApp.quit()
42 
43 
44 if __name__ == '__main__':
45 
46     app = QApplication(sys.argv)
47     ex = Example()
48     sys.exit(app.exec_())
原文地址:https://www.cnblogs.com/fuqia/p/8710861.html