Simple While loop without classes or events?
-
Hello,
I have been trying to use Qt for many months. I have created a three page GUI for my project. I am not a C++ programmer but I understand the basics.
I am wanting to know how to create a simple While loop to run my program. I just want to read a few GPIO inputs (external switches and button presses) and write to a few GPIO outputs on a machine I am designing.
Is this possible with Qt? I understand how to do it in C++ but I also need a GUI which is why I selected Qt.
Thank you for your help.
-
Hi,
What would that while loop do exactly ?
Depending on that, you might not need one.
-
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.