this is a question to understand QTimer
. I create a QTimer()
event that run a function every 1000ms. This function lasts as long as the GUI is running. So that, I used QTimer()
in the main thread (GUI thread), I didn't create a QThread
for this timer event. My questions are:
1- Is using QTimer
in the GUI thread (Main thread), affects the functionality of the GUI at any time?
2- Do you recommend to create a QThread
and run this timer event on it, or it is not worth it and it's better to save resources. if yes, may you provide me how to move this timer to a QThread
?
If you want to perform a periodic task then QTimer is the best option, and the logic of QTimer is to use the Qt event loop to check if it triggers or not. Instead, you should worry about the function that the QTimer executes since in general any function connected to a signal should not be very time consuming and that is the developer's task.
In general, you should avoid using threads as much as possible since they add more complexity and possibly more problems. So the only reason threads is an alternative is when a task is very time consuming. In conclusion: The use or non-use of thread does not depend on QTimer but on the task you are executing.
If you are going to perform a periodic task then there are many alternatives (not only QThread) but the functionality depends on the specific task:
Create a QObject that lives in a secondary thread and call it using the QTimer (here the condition is that the task time is much less than the QTimer period)
Use a QThreadPool that starts a QRunnable with the QTimer (QThreadPool can have a maximum number of runnables active)