×
Namespaces

Variants
Actions

How to wait synchronously for a Signal in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Compatibility
Platform(s):
Symbian
Article
Created: vasant21 (06 Sep 2010)
Last edited: hamishwillee (11 Oct 2012)

Overview

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( "http://www.google.com" ) ) );
 
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.
loop.exec();
 
// 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( "http://www.google.com" ) ) );
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 04:17.
727 page views in the last 30 days.
×