How to wait synchronously for a Signal in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

Template:Abstract

Template:Note

  • 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());



Template:Warning 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());

}