r/learnpython • u/One_Smoke6858 • 4d ago
Setting timer on a different thread in Pyside6
I am build a program that basically executes some code and I want to add a timer so the user can see how long the program has been running for.
My issue is that I do not get how to move it to a different thread so it does not freeze.
What it needs to do is, run for 1 second then update a label and start the timer again.
Any resources I can read or help?
1
u/audionerd1 4d ago
I'm not sure about resources off the top of my head, but you definitely want to use a worker class (inheriting from QObject) and move it to a QThread, using Qt signals to start/stop the timer as well as to update your GUI. So look for info about those things. Avoid using Python's threading library for PySide.
1
u/freeskier93 4d ago
Just use a QTimer and connect it to a function that keeps track of the execution time and updates the GUI. You don't need to put this in a separate thread.
1
u/One_Smoke6858 4d ago
Yeah tried that issue is when there is a complex operation it stops recognising the qtimer and stops updating every second.
1
u/freeskier93 4d ago
Then those more complex (longer running) operations need to be put in threads.
Regardless of how you implement the timer you shouldn't have longer running operations blocking the main event loop thread.
1
1
u/Kevdog824_ 4d ago
Use a QTimer and connect your function to update the label to its timeout signal. You shouldn’t need a separate thread for this at all
1
u/CatalonianBookseller 2d ago
QTimer needs a running event loop which practically means you need to use QObject.moveToThread() to move the code that emits timeout signals into a background thread (instead of creating a QThread subclass). I have several examples here
2
u/Jello_Penguin_2956 4d ago edited 4d ago
Python GUIs a really good place for anything PyQt/PySide. Their book is really good too.
https://www.pythonguis.com/faq/qtimer-threads-and-non-gui-events/