Search code examples
pythonpyqtkeyboard-shortcutssignals-slotsqplaintextedit

PyQt QPlainTextEdit: How to replace right-click with key combination


How do I substitute "right-click" in the following snippet with a key combo (for example Ctrl-S)? I searched google and Qt manuals but still have no idea how to do it. I am new to Qt. Any help will be greatly appreciated.

(P.S. to @ekhumoro: I can't seem to @you in your answer to the "PyQt: How to insert text at the cursor in QTableView" question. I used your idea here. But I'd like to use key combination or a button.)

class MyDelegate(QStyledItemDelegate):
    contextMenuRequested = pyqtSignal(object, QPoint)

    def __init__(self, parent=None):
        super(MyDelegate, self).__init__(parent)

    def createEditor(self, parent, option, index):
        editor = QPlainTextEdit(parent)
        editor.setContextMenuPolicy(Qt.CustomContextMenu)
        editor.customContextMenuRequested.connect(
            self.commitAndCloseEditor)  # !!! right-click

    def commitAndCloseEditor(self):
        pass

Solution

  • You can use a QShortCut:

    class MyDelegate(QStyledItemDelegate):
        def __init__(self, parent=None):
            super(MyDelegate, self).__init__(parent)
            self.shortcut = QtGui.QShortcut(
                QtGui.QKeySequence('Ctrl+S'), parent)
            self.shortcut.activated.connect(self.commitAndCloseEditor)
    
        def createEditor(self, parent, option, index):
            editor = QPlainTextEdit(parent)
            return editor