Reputation: 390
When trying to create a timer, I want to to use Space
to activate the timer function I have created:
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)
However, this does not work. Any other buttons I use, I.E. "t", "0" etc... do work. Is something else using Space
by default, or what could be causing this problem?
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()
Upvotes: 1
Views: 750
Reputation: 243897
The problem is that although the KeyPress event is not sent to the QPushButton, it is not ignored, so the window is not notified. The solution is to ignore the keyPress and keyRelease in the eventFilter:
def eventFilter(self, obj, event):
if obj is self.button and event.type() == QEvent.KeyPress:
event.ignore()
return True
if obj is self.button and event.type() == QEvent.KeyRelease:
event.ignore()
return super().eventFilter(obj, event)
An easier solution is to use QShortcut:
# ...
self.show()
shorcut = QShortcut(Qt.Key_Space, self, autoRepeat=False)
shorcut.activated.connect(self.process_time)
def process_time(self):
self.isCounting = not self.isCounting
if self.isCounting == True:
self.timerStart = time.time()
else:
print(time.time() - self.timerStart)
Upvotes: 4