思路
- 先添加上下文策略
self.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
- 添加QAction,并且链接方法
self.copy = QAction('复制')
self.copy.triggered.connect(lambda: print('复制'))
- 将所有的QAction都添加到窗体
self.addActions([self.copy, self.paste])
代码
from PySide6.QtWidgets import QApplication, QWidget
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
class Mywindow(QWidget):
def __init__(self):
super().__init__()
self.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
self.copy = QAction('复制')
self.copy.triggered.connect(lambda: print('复制'))
self.paste = QAction('粘贴')
self.paste.triggered.connect(lambda: print('粘贴'))
self.addActions([self.copy, self.paste])
if __name__ == '__main__':
app = QApplication([])
window = Mywindow()
window.show()
app.exec()
效果