如何使用 PyQt5 添加到 Python 文本框中的默认上下文菜单



我正在尝试向文本框添加一项功能,用户可以在其中突出显示一个单词,右键单击并能够选择是定义还是获取突出显示单词的同义词。我编写了一个上下文菜单,但它仅在我在文本框外部单击时才出现。无论如何,我可以向默认上下文菜单添加功能,包括复制,粘贴等吗?这是我的上下文菜单代码。

self.setContextMenuPolicy(Qt.ActionsContextMenu)
defineAction = QtWidgets.QAction("Define", self)
defineAction.triggered.connect(lambda: self.define(event))
self.addAction(defineAction)
synonymAction = QtWidgets.QAction("Find Synonyms", self)
synonymAction.triggered.connect(lambda: self.synonym(event))
self.addAction(synonymAction)
您需要

对文本编辑小部件进行子类化并覆盖createStandardContextMenu(point)

在重写的方法中,cal 基本调用实现以获取标准上下文菜单对象(它返回 QMenu (。使用自定义操作修改此菜单,然后返回菜单。

当用户请求上下文菜单时,将调用该函数。

有关更多详细信息,请参阅 http://doc.qt.io/qt-5/qplaintextedit.html#createStandardContextMenu

编辑:你可以像这样子类

class MyTextEdit(QLineEdit):
    def createStandardContextMenu(self, menu):
          #as above, reimplement this method

然后,在制作 GUI 时使用该类而不是QLineEdit

或者我记得有一个信号叫做customContextMenuRequested。你像这样使用它

#assume you have the textbox in a variable called self.my_textbox
self.my_textbox.setContextMenuPolicy(Qt.CustomContextMenu)
self.my_textbox.customContextMenuRequested.connect(self.generate_context_menu)

然后将一个方法添加到生成 GUI 的类中,如下所示:

def generate_context_menu(self, location):
    menu = self.my_textbox.createStandardContextMenu()
    # add extra items to the menu
    # show the menu
    menu.popup(self.mapToGlobal(location))

最新更新