简体   繁体   中英

PyQt5 store time of keyPressEvent

Issue:

I have a program where I will be showing several pages with a stacked widget, and users will have to press a button (using code I've written below) to go to the next page of the stacked widget. What I am trying to do is to calculate the time the reaction time of the user. So to measure how quick they were to press a button.

Possible solution:

I was thinking of storing the time that a key was pressed (point B) and the time that the page was shown (point A) and to subtract these points to get the reaction time. I was thinking of using a QTimer running throughout all the pages and whenever a key is pressed, it will store the time in a variable (that would be point b). And store the time that the page was shown (point a), and subtract these points to get the reaction time. However, I am quite a beginner in coding and don't know how I would code this. Or whether there is a simpler way.

The second solution I thought of was to used QElapsedTimer, but I don't know how to code that either.

Button press:

I have also created a subclass of a QWidget that will emit a signal every time I press the key 'F' or 'J' (KeybaordWidget). So I was thinking, I would need to write a function that does what I have described and connect that function to the 'fPress' or 'jPress' signal.

class KeyboardWidget (QWidget):
    fPress = pyqtSignal(str)
    jPress = pyqtSignal(str)
    def keyPressEvent(self,event):
        if event.key() == Qt.Key_F:
            self.fPress.emit('f')
        elif event.key() == Qt.Key_J:
            self.jPress.emit ('j')

In the keyPressEvent method, you can get the actual time in milliseconds since the epoch with time.time() , and save that in an attribute of your KeyboardWidget class. On the next keyPressEvent call, you can get the time again, subtract the first time from the second time, and you have the time in milliseconds the user needed between two button presses.

import time

class KeyboardWidget(QWidget):
    ...
    
    def __init__(self):
        QWidget.__init__(self)
        self.last_time = time.time()

    def keyPressEvent(self,event): 
        actual_time = time.time()
        print(actual_time - self.last_time) # will print the duration since the button was pressed the last time in milliseconds
        self.last_time = actual_time

        if event.key() == Qt.Key_F:
            self.fPress.emit('f')
        elif event.key() == Qt.Key_J:
            self.jPress.emit ('j')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM