Simple While loop without classes or events?
-
Depending on the refresh rate you need, a QTimer could be enough to do what you want.
-
Sure, you can subclass QThread and reimplement the run method with your loop.
-
Hi
Just a note.
The reason we talk about Threads is that plain looping (while/for) strangulate the main event loop and makes application unresponsive.
Its sometimes possible to help the situation a little by calling
QApplication::processEvents() in the loop but
its not good design and in the long run, using a thread will just work
so much better overall.I know looking at the docs seems a bit involved but its not so bad after fiddling with it for some time.
I personally liked this tut
http://www.bogotobogo.com/Qt/Qt5_QThreads_Creating_Threads.php
Please notice that besides overriding the run method, there is also the worker approach.
https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ -
Hi @Injunear,
If you do GUI programming, you can't just have endless loops as your app needs to process events, like user clicks, window movements, system color changes and so on.
So the way to go is really either using a
QThread
as suggested by @SGaist or to create a second thread (beside the main thread which handles all GUI events).For 20 repeats per second I'd go with a
QTimer
(I guess your function will execute quite fast).All you need is a slot function that is effectively the "body" of your loop, a QTimer with intervall 50 ms, and a connect that binds both together. Very basic, no threads involved.
-
Yep, I strongly concur with mrjj on this. In particular if you are new to Qt, there is no need for threads.
Threads are very nice, and maybe one day, you'll need some, so it's not lost time to learn how to use them. But for what you want, a QTimer is enough. Put the content of your loop in a slot. And connect the QTimer timeout() signal to this slot.From the moment you call start(50) on your timer, the slot will be executed every 50ms.
Threads become useful if the content of your slot becomes a bit heavy.
-
Since nobody mentioned it yet. event loops are started calling
QCoreApplicatio::exec()
orQEventLoop::exec()
orQThread::exec()
-
Thank you all for your help. I have been able to create a thread with my loop inside and it reads the buttons pushed on the GUI.
12/12