如何在PyQT5对话窗口中记录按键组合

时间:2019-02-20 03:20:23

标签: python pyqt pyqt5 key-bindings

我从主窗口打开对话框,在其中夹住按键,将其名称填充到该行中。问题是我无法理解您需要在哪里执行检查所有键状态的循环。也许还有另一种方法来按下按键?或者,您需要听夹紧信号的位置,以免对话框挂起并更新字符串。

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)

1 个答案:

答案 0 :(得分:2)

使用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_())