Search code examples
pythonpyqtpyqt5key-bindings

How to record a pressed key combination in the PyQT5 dialog window


I open the dialog from the main window, where by clamping the keys, I fill the line with their names. The problem is that I can not understand where you need to do a cycle of checking all the keys on their state. Maybe there is another way to get the keys pressed? Or where you need to listen to the clamping so that the dialog box does not hang and the string is updated.

MainWindow:
    def showBindings(self, param):
        from dialogs import KeyBindingsDialog
        self.dialog = KeyBindingsDialog()
        self.dialog.show()

Dialog:
class KeyBindingsDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(KeyBindingsDialog, self).__init__(parent)
        self.ui = KeyBindings()
        self.ui.setupUi(self)

Solution

  • Use QKeySequenceEdit:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class KeySequenceEdit(QtWidgets.QKeySequenceEdit):
        def keyPressEvent(self, event):
            super(KeySequenceEdit, self).keyPressEvent(event)
            seq_string = self.keySequence().toString(QtGui.QKeySequence.NativeText)
            if seq_string:
                last_seq = seq_string.split(",")[-1].strip()
                le = self.findChild(QtWidgets.QLineEdit, "qt_keysequenceedit_lineedit")
                self.setKeySequence(QtGui.QKeySequence(last_seq))
                le.setText(last_seq)
                self.editingFinished.emit()
    
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self._keysequenceedit = KeySequenceEdit(editingFinished=self.on_editingFinished)
            button = QtWidgets.QPushButton("clear", clicked=self._keysequenceedit.clear)
            hlay = QtWidgets.QHBoxLayout(self)
            hlay.addWidget(self._keysequenceedit)
            hlay.addWidget(button)
    
        @QtCore.pyqtSlot()
        def on_editingFinished(self):
            sequence = self._keysequenceedit.keySequence()
            seq_string = sequence.toString(QtGui.QKeySequence.NativeText)
            print("sequence: ", seq_string)
    
    if __name__ == '__main__':
        import sys 
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())