Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

How to wait synchronously for a Signal in Qt

From Wiki
Jump to: navigation, search
Article Metadata
Created: vasant21 (06 Sep 2010)
Last edited: hamishwillee (11 Oct 2012)


This article shows how to receive signal from a synchronous request.

Note.pngNote: This approach works well for test cases, but it is not recommended to use this in real applications. QEventLoop::exec() causes the event loop to recurse, and as such, can cause application code to also recurse. Usually, this recursion is unexpected. If this approach is used often, it's possible to end up with several layers of QEventLoop::exec() which cannot continue due to recursion.

  • There may be times when you want to wait synchronously for signal to proceed eg: when implementing test cases.
  • QEventLoop can be used to wait for specific event.
  • The example below demonstrates how to wait for http response and prints the received response, for simplicity, the example doesn't consider the case when we wait endlessly, timer could be attached to Event loop, so that we end the loop after x time interval.
QNetworkAccessManager *networkMgr = new QNetworkAccessManager(this);
QNetworkReply *reply = networkMgr->get( QNetworkRequest( QUrl( "" ) ) );
QEventLoop loop;
QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));
// Execute the event loop here, now we will wait here until readyRead() signal is emitted
// which in turn will trigger event loop quit.
// Lets print the HTTP GET response.
qDebug( reply->readAll());

Warning.pngWarning: For test cases, this approach works well. For real applications, avoid using it. It's better to split the function that wants to wait in two, and handle the signal is a separate slot.

For the above example, it would look something like this:
void Class::startDownloadSlot() 
QNetworkAccessManager networkMgr = new QNetworkAccessManager();
QNetworkReply *reply = networkMgr.get( QNetworkRequest( QUrl( "" ) ) );
connect(reply, SIGNAL(readyRead()), this, SLOT(downloadFinishedSlot()));
// return to the eventloop here, signal will be emitted later, calling the slot below
void Class::downloadFinishedSlot()
// this signal is sent by QNetworkReply
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
// Lets print the HTTP GET response.
qDebug( reply->readAll());
This page was last modified on 11 October 2012, at 01:17.
860 page views in the last 30 days.