Home > Software design >  Qtimer event not executing
Qtimer event not executing

Time:06-23

I'm trying my first play with Python timers for use with QT GUI's, but this simple example I have created is not triggering the 'update_time' event. 'start' is printed ok as expected.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(): 
        timer = QTimer()
        timer.timeout.connect(update_time)
        timer.start(1000)
        print("start")

def update_time():
        time = QTime.currentTime()
        #not executed
        print("executed")

if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
change_time()
sys.exit(app.exec_())

CodePudding user response:

Alternatively to what @musicamante suggested you could also define the timer outside of the function so that if you ever decide to stop the timer, future calls to change_time can reuse the same timer and avoid creating a new one.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(timer): 
    timer.timeout.connect(update_time)
    timer.start(1000)
    print("start")

def update_time():
    time = QTime.currentTime()
    #not executed
    print("executed")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    timer = QTimer()
    change_time(timer)
    sys.exit(app.exec_())
  • Related