如何在 PyQT5 对话窗口中记录按下的组合键 [英] How to record a pressed key combination in the PyQT5 dialog window

查看:39
本文介绍了如何在 PyQT5 对话窗口中记录按下的组合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从主窗口打开对话框,通过夹住键,我在行中填入它们的名称.问题是我不明白你需要在哪里循环检查所有键的状态.也许还有另一种方法可以按下按键?或者哪里需要监听,让对话框不挂起,字符串更新.

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)

推荐答案

使用QKeySequenceEdit:

Use QKeySequence

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

这篇关于如何在 PyQT5 对话窗口中记录按下的组合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆