1

I'm trying to add a functionality to a text box where a user can highlight a word, right click and be able to choose whether to define or get synonyms for the highlighted word. I coded a context menu but it only appears when I click outside of the textbox. Is there anyway I can add functions to the default context menu that includes Copy, Paste, etc.? Here is my code for the context menu.

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)

1 Answer 1

6

You'll need to subclass the text edit widget and override createStandardContextMenu(point).

In your overridden method, cal the base call implementation to get the standard context menu object (it returns QMenu). Modify this menu with custom actions and then return the menu.

The function will be called when the user requests a context menu.

See http://doc.qt.io/qt-5/qplaintextedit.html#createStandardContextMenu for more details

EDIT: You can subclass like this

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

Then you use that class instead of QLineEdit when you make your GUI.

Alternatively I've remembered there is a signal called customContextMenuRequested. You use this instead like this

#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)

and then add a method to the class that generates the GUI like:

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))
Sign up to request clarification or add additional context in comments.

2 Comments

@three_pineapples I am pretty sure the line is supposed to be self.my_textbox.customContextMenuRequested.connect(self.generate_context_menu). I couldn't get it to work regardless, though -- the menu wouldn't pop up -- but overriding contextMenuEvent as shown in the docs worked.
@nimble_ninja You're right, that was a mistake!. I've fixed it. It should work with that fix, not sure why it didn't for you. I've done something almost identical (using a lineedit instead of a textedit) here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.