我试图用一个用于替换文本的附加条目来扩展QLineEdit
的上下文菜单。我可以用.createStandardContextMenu()
扩展上下文菜单,它工作得很好。但当我尝试用.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))
添加快捷方式时,它不会对键做出反应。不同的钥匙也是一样,我试过了。此外,用QAction('&Replace', self)
制作的快捷方式也不起作用。SO和其他来源中的一些例子是以同样的方式构建的,所以我想知道其他人是否也有同样的问题。我好像错过了什么。但是什么?我搞不清楚,查了好多次文件。
工作示例:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class ECM(QWidget):
def __init__(self):
super(ECM, self).__init__()
self.setWindowTitle("Extended Context Menu")
self.lineEdit = QLineEdit()
self.lineEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.lineEdit.customContextMenuRequested.connect(self.my_contextMenuEvent)
layout = QVBoxLayout()
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.setFixedSize(800,200)
self.show()
def replace(self):
print("replace")
def my_contextMenuEvent(self):
print("my_contextMenuEvent")
menu = self.lineEdit.createStandardContextMenu()
action = QAction('&Replace', self)
action.setStatusTip('Replace values')
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))
action.triggered.connect(self.replace)
menu.addAction(action)
menu.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
sender = ECM()
app.exec_()
根据musicamante的评论,我得出了以下解决方案:
文档摘录:
- 如果您想扩展标准上下文菜单,请重新实现函数,调用createStandardContextMenu((并扩展菜单返回
- QAction列表(由actions((返回(的默认用途是创建上下文QMenu
这对我来说并不完全符合逻辑,不是第一次;-(
最终代码:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class ECM(QWidget):
def __init__(self):
super(ECM, self).__init__()
self.setWindowTitle("Extended Context Menu")
self.lineEdit = QLineEdit()
self.lineEdit.setContextMenuPolicy(Qt.CustomContextMenu)
self.lineEdit.customContextMenuRequested.connect(self.my_contextMenuEvent)
layout = QVBoxLayout()
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.setFixedSize(800,200)
action = QAction('&Replace', self)
action.setStatusTip('Replace values')
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_R))
action.triggered.connect(self.replace)
self.lineEdit.addAction(action)
self.show()
def replace(self):
print("replace")
def my_contextMenuEvent(self):
menu = self.lineEdit.createStandardContextMenu()
menu.addActions(self.lineEdit.actions())
menu.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
sender = ECM()
app.exec_()