pyqt5按键读取

按键0到9键值为48到57,对应QT为Qt.Key_0到Qt.Key_9
按键按下,触发事件,可以读取到键值self.keynum=event.key()
源码:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.Qt import *
import sys
key_dictionariess={
'0':48,
'1':49,
'2':50,
'3':51,
'4':52,
'5':53,
'6':54,
'7':55,
'8':56,
'9':57
}
class keyWindows(QMainWindow):  # 定义类继承自
    def __init__(self):
        super().__init__()  # 调用父类init方法      
        self.setWindowTitle("键盘按键测试")
        self.setGeometry(500, 100, 400, 600)
        self.keysss = QLabel(self)
        self.keysss.setText('按键内容:')
        self.keysss.adjustSize() #使得显示完整
        self.keysss.move(30, 140)
 
    def keyPressEvent(self, event):
        self.keynum=event.key()
        for key, value in key_dictionariess.items():
            if value==self.keynum:        
                self.keysss.setText('按键内容:'+str(key))
                self.keysss.adjustSize() #使得显示完整  
        
        #### 48  -  57
        if event.key()==Qt.Key_0:
            print(event.key())
        if event.key()==Qt.Key_1:
            print(event.key())
        if event.key()==Qt.Key_2:
            print(event.key())
        if event.key()==Qt.Key_3:
            print(event.key())
        if event.key()==Qt.Key_4:
            print(event.key())
        if event.key()==Qt.Key_5:
            print(event.key())
        if event.key()==Qt.Key_6:
            print(event.key())
        if event.key()==Qt.Key_7:
            print(event.key())
        if event.key()==Qt.Key_8:
            print(event.key())
        if event.key()==Qt.Key_9:
            print(event.key())
  
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = keyWindows()
    window.show()
    sys.exit(app.exec_())

测试视频:
https://www.douyin.com/video/7196593190311300411

你可能感兴趣的:(qt,python,开发语言,pyqt)