我通过子类化QMainWindow
和覆盖keyPressEvent
andkeyReleaseEvent
函数来处理多个按键,然后在按键是否按下时更新字典......
def keyPressEvent(self,event):
self.pressedKeys[event.key()] = True
def keyReleaseEvent(self,event):
self.pressedKeys[event.key()] = False
...和pressedKeysArray
存在:
pressedKeys = {Qt.Key_Left: False,
Qt.Key_Right: False,
Qt.Key_Down: False,
Qt.Key_Up: False}
但是,我希望能够捕捉到双右箭头单击,例如在 100 或 200 毫秒内。我会扩展pressedKeys
字典以包含可以设置为的双击键True
or False
,但我不知道如何知道该键是否已连续按下两次。
到目前为止,这是我的代码:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
pressedKeys = {Qt.Key_Left: False,
Qt.Key_Right: False,
Qt.Key_Down: False,
Qt.Key_Up: False}
def __init__(self,parent=None,*args,**kwargs):
QMainWindow.__init__(self,parent,*args,**kwargs)
self.parent = parent
self.timer = QTimer()
self.timer.timeout.connect(self.keyAction)
self.timer.start(50)
self.show()
def keyPressEvent(self,event):
self.pressedKeys[event.key()] = True
def keyReleaseEvent(self,event):
self.pressedKeys[event.key()] = False
def keyAction(self):
if self.pressedKeys[Qt.Key_Left] and self.pressedKeys[Qt.Key_Down]: print("rolling left")
elif self.pressedKeys[Qt.Key_Right] and self.pressedKeys[Qt.Key_Down]: print("rolling right")
elif self.pressedKeys[Qt.Key_Left]: print("running left")
elif self.pressedKeys[Qt.Key_Right]: print("running right")
elif self.pressedKeys[Qt.Key_Down]: print("crouching") #return here to block effect of 'up' key being pressed
if self.pressedKeys[Qt.Key_Up]: print("jumping")
def exceptHook(exectype,value,traceback):
sys.__excepthook__(exectype,value,traceback)
if __name__ == "__main__":
sys.excepthook = exceptHook
app = QApplication(sys.argv)
mainWindow = MainWindow()
app.quit()