尝试创建计时器时,我想使用Space
激活我创建的计时器函数:
def keyReleaseEvent(self, e):
# if e.key() == Qt.Key_Space:
if (e.key() == Qt.Key_T):
self.isCounting = not self.isCounting
if self.isCounting == True:
self.timerStart = time.time()
else:
#return elapsed time
print(time.time() - self.timerStart)
然而,这是行不通的。我使用的任何其他按钮,如“t”、“0”等。。。干活儿。默认情况下是否有其他东西在使用Space
,或者是什么导致了这个问题
MRE:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import time
import sys
class Listener(QObject):
def __init__(self, button):
super().__init__(button)
self._button = button
self.button.installEventFilter(self)
@property
def button(self):
return self._button
def eventFilter(self, obj, event):
if obj is self.button and event.type() == QEvent.KeyPress:
return True
return super().eventFilter(obj, event)
class App(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.SCREEN_WIDTH = 1920
self.SCREEN_HEIGHT = 1080
self.WIN_HEIGHT = self.SCREEN_HEIGHT*.8
self.WIN_WIDTH = self.SCREEN_WIDTH/2
self.isCounting = False
self.timerStart = time.time()
self.setGeometry(self.SCREEN_WIDTH/2-self.WIN_WIDTH/2,self.SCREEN_HEIGHT/2-self.WIN_HEIGHT/2, self.WIN_WIDTH, self.WIN_HEIGHT)
self.setWindowTitle('Timer')
scrambleButton = QPushButton(self)
scrambleButton.setText('New Scramble')
scrambleButtonGeometry = QRect(self.WIN_WIDTH/2-65, 80, 130,35)
scrambleButton.setGeometry(scrambleButtonGeometry)
scrambleButton.clicked.connect(lambda: print('hey'))
listener = Listener(scrambleButton)
self.show()
def keyReleaseEvent(self, e):
# if e.key() == Qt.Key_Space:
if (e.key() == Qt.Key_T):
self.isCounting = not self.isCounting
if self.isCounting == True:
self.timerStart = time.time()
else:
#return elapsed time
print(time.time() - self.timerStart)
def main():
app = QApplication(sys.argv)
win = App()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
问题在于,尽管按键事件没有发送到QPushButton,但它不会被忽略,因此不会通知窗口。解决方案是忽略eventFilter中的按键按下和按键释放:
更简单的解决方案是使用QShortcut:
相关问题 更多 >
编程相关推荐