1、介绍
菜单组件。有两种场景:
- 窗口的菜单栏设置一个或多个QMenu
- 其他组件绑定右键菜单,探出一个QMenu
2、类和初始化
class QMenu(QWidget):
"""
QMenu(parent: QWidget = None)
QMenu(str, parent: QWidget = None)
"""
def __init__(self, *__args):
pass
3、属性
4、方法
(1)addAction
"""
addAction(self, QAction)
addAction(self, str) -> QAction
addAction(self, QIcon, str) -> QAction
addAction(self, str, PYQT_SLOT, shortcut: Union[QKeySequence, QKeySequence.StandardKey, str, int] = 0) -> QAction
addAction(self, QIcon, str, PYQT_SLOT, shortcut: Union[QKeySequence, QKeySequence.StandardKey, str, int] = 0) -> QAction
"""
- 添加动作项
- 会返回添加的动作项对象,可以直接使用
(2)addMenu
"""
addMenu(self, QMenu) -> QAction
addMenu(self, str) -> QMenu
addMenu(self, QIcon, str) -> QMenu
"""
- 添加子菜单
- 会返回添加的菜单对象,可以直接使用
(3)addSeparator
- 添加分隔符,即一条横线
(4)clear
- 清除
5、事件
(1)mouseDoubleClickEvent
- 鼠标双击事件
(2)triggered
triggered(self, QAction)
- 触发事件,返回QAction对象,即触发的项。
- 即点击菜单内部的动作项触发该事件,点击该菜单本身是不会触发的
6、右键菜单示例
from PyQt5.QtCore import Qt
self.ui.plainTextEdit: QPlainTextEdit
self.ui.plainTextEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.ui.plainTextEdit.customContextMenuRequested.connect(self.plainTextEdit_rightmenu)
- 设置上下文菜单setContextMenuPolicy,必须在定义右键 菜单之前调用
- customContextMenuRequested定义右键菜单事件
def plainTextEdit_rightmenu(self, pos):
print('右键菜单')
menu = QMenu(self.plainTextEdit)
menu.addAction(QAction('动作1', menu))
menu.addAction(QAction('动作2', menu))
menu.addAction(QAction('动作3', menu))
menu.triggered.connect(self.menuSlot)
# 将菜单显示在鼠标位置
menu.exec_(QCursor.pos())
def menuSlot(self, act):
print(act.text())
标签:addAction,菜单,QMenu,self,QAction,pyqt5,menu
From: https://www.cnblogs.com/wd404/p/17324482.html