キー入力イベント

2022/08/28

Python3.8.2,PySide2 5.15.2

import sys
from PySide2 import QtCore,QtGui,QtWidgets

class Test(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Test, self).__init__(parent)

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return
        key = QtGui.QKeySequence(event.key()).toString(QtGui.QKeySequence.NativeText)
        print('Pressed %s' % key)

    def keyReleaseEvent(self, event):
        if event.isAutoRepeat():
            return
        key = QtGui.QKeySequence(event.key()).toString(QtGui.QKeySequence.NativeText)
        print('Released %s' % key)

        if event.key() == QtCore.Qt.Key_Z:
            self.close()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    T = Test()
    T.show()
    sys.exit(app.exec_())


Qt.Key
https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.Key.html