PyQt Quickie: QTimer
QTimer is a fairly simple class: you use it when you want something to happen "in a while" or "every once in a while".
The first case is something like this:
The second is this:
# Create a QTimer timer = QTimer() # Connect it to f timer.timeout.connect(f) # Call f() every 5 seconds timer.start(5000)
Simple, right? Well, yes, but it has some tricks.
-
You have to keep a reference to``timer``
If you don't, it willget garbage-collected, and f() will never be called.
-
It may not call
f()
in 5 seconds.It will call
f()
more or less 5 seconds after you enter the event loop. That may not be quickly after you start the timer at all! -
You may get overlapping calls.
If
f()
takes long to finish and re-enters the event loop (for example, by callingprocessEvents
) maybe the timer will timeout and call it again before it's finished. That's almost never a good thing.
So, you can do this:
What that snippet does, is, calls f()
only once. But f
itself schedules itself to run in 5 seconds. Since it does it in a finally
, it will do so even if things break.
That means no overlapping calls. It also means it won't be called every 5 seconds, but 5 seconds plus whatever f
takes to run. Also, no need to keep any reference to a QTimer.
Final tip: You can also use QTimer to do something "as soon as you are in the event loop"
Hope it was useful!
Gracias! Me ha servido de mucho!
Very helpful and simple tutorial. Thank You!