pythonpyqt5keyboard-shortcutsqkeysequenceqshortcut

QShortcut & QKeySequence with Shift+Return in a QPlainTextEdit element


I have an element, editorBox which is of the PyQt5 element type QPlainTextEdit. My target goal is to call a function when the hotkey Shift + Return is pressed, and my goal with this function is that it will also insert text into the editorBox element (this isn't the part I'm stressed about, it's fairly easy to do with the .insertPlainText() method).

I've done searching, and the closest result I could find was to use QShortcut & QKeySequence paired together like so:

# Initialize the QShortcut class
self.keybindShiftEnter = QShortcut(QKeySequence("Shift+Return"), self)
# Connect the shortcut event to a lambda which executes my function
self.keybindShiftEnter.activated.connect(lambda: self.editorBox.insertPlainText("my text to insert"))

For clarification, I have tried using other characters in the QKeySequence constructor, such as Ctrl+b, and I've had success with it. Oddly enough, only the combination Shift+Return doesn't work for me.

I've analyzed a problem with it in relation to my bug. Some of the posts I've viewed:


Solution

  • Solved my own problem:

    # ... editorBox Initialization code ...
    self.editorBox.installEventFilter(self)
    
    # Within App class
    def eventFilter(self, obj, event):
        if obj is self.editorBox and event.type() == QEvent.KeyPress:
            if isKeyPressed("return") and isKeyPressed("shift"):
                self.editorBox.insertPlainText("my text to insert")
                return True
        return super(App, self).eventFilter(obj, event)
    

    What I'm doing here is setting a filter function- basically, every time a key is pressed (any key, including space/backspace/etc) it will call the eventFilter function. The first if statement makes sure that the filter will only pass through if it is a key stroke (not entirely sure if this part is necessary, I don't think clicks trigger the function). Afterwards, I utilize the isKeyPressed function (a renamed version of the keyboard module's is_pressed function) to detect if the current key is held down. With the and operator, I can use this to make keybind combos.