[Solved] Easy way to run loops without GUI freezing?
-
Hello there,
I've got a little problem which i can't solve by myself. I have written a program which recieves pictures from a TCP-Socket. The program has to start and find its server by itself, because the computer it's going to run on hasn't got a monitor or a keyboard. When the program starts, it checks an IP-List for a running server. Following function is called from the GUI:
@void MultiClientSocket::firstTryConnect()
{
QString helper = QString::number(host);blockSignals(true); int counter = 0; while((state() == QAbstractSocket::UnconnectedState) == true) { ipAddress = ipList.at(counter); connectToHost(ipAddress,host,QIODevice::ReadWrite); if(waitForConnected(200)) break; if((counter == (ipList.size()-1))==true) { counter = 0; } else { counter++; } } disconnectFromHost(); blockSignals(false); emit setIP(ipAddress); QTimer::singleShot(100,this,SLOT(tryConnect())); emit setStatus("Connecting...");
}@
Of course the GUI is freezing when the program is searching for a server. I know there are many ways to stop that, with threading for example. But I don't know how to use them. Is there a possibility without threading or finding a running server without connecting?
Thank you for your help!
Zamahra
I'm using QT 5.0.1 with QT Creator 2.6.2 on a Windows 7 64Bit Computer
-
You can use qApp::processEvents() inside your loop to keep the GUI responsive. It's probably better to rethink the design, though.
-
why do you care if the gui freezes when the program is supposted to run on a computer without keyboard and a monitor? :)
-
You can try "QEventLoop":http://qt-project.org/doc/qt-5.0/qtcore/qeventloop.html
-
You probably want to put functions that take a lot of time into a "background" thread.
You can emit a signal from the "background" thread and then have the GUI thread react on it in a slot, as soon as the final result is known or some status update (which the GUI needs to know about) has occurred.
Use the Qt::QueuedConnection connection type for this purpose, so the slot will be executed in "main" thread.
--
See also:
-
Thank you for your help!
@qApp->processEvents();@
works very fine.Even when the program should start by itself, I have to use the GUI for test-purposes. I think its better when the program runs on every computer and doesn't confuse users by freezing =)
-
Nevertheless, keep in mind that qApp->processEvents() processes all pending events, which means that it may process also pending signals, which in turn, may call into slot functions - which probably is not what you want in the middle of your loop. Also, it can easily construct a nice infinite recursion, if you call qApp->processEvents() from within a slot, as it might result in calling exactly that slot. So, you have to be very careful with it...
(Doesn't mean it can't work nice for your particular program)