Search code examples
pythonpyqtpyqt5qtimer

How to set PyQt5 Qtimer to update in specified interval?


I would like to update the Qtimer according to a framerate of 15 FPS - so my def update(): recieves a signal every 0,06 s. Can you help me? I have attached a code example below where my setInterval input is 1/15, but I dont know if that is the way to go. Thanks.

from PyQt5 import QtCore

def update():
    print('hey')

fps = 15
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.setInterval(1/fps)
timer.start()

Solution

  • You have the following errors:

    • setInterval() receives the time in milliseconds, so you must change it to timer.setInterval(1000/fps).

    • Like many Qt components, the QTimer needs you to create QXApplication and start the event loop, in this case a QCoreApplication is enough.

    import sys
    
    from PyQt5 import QtCore
    
    
    def update():
        print("hey")
    
    
    if __name__ == "__main__":
    
        app = QtCore.QCoreApplication(sys.argv)
    
        fps = 15
        timer = QtCore.QTimer()
        timer.timeout.connect(update)
        timer.setInterval(1000 / fps)
        timer.start()
    
        app.exec_()