Archive

Posts Tagged ‘multithreading’

Qt: (Nearly) synchronous QNetworkAccessManager calls

July 8, 2010 9 comments

The QNetworkAccessManager class is very user-friendly, but it makes asynchronous calls. I was in the need for synchronous calls to handle my HTTP communication, but I did not want the overhead of another thread, so I googled a bit and finally came up with a short call to an event loop that processed the request. Like this:

QNetworkAccessManager * pnam = new QNetworkAccessManager(this);
// the slot was declared at another place
connect(pnam, SIGNAL(finished(QNetworkReply *)), this,
  SLOT(loginFinished(QNetworkReply*)));
QNetworkRequest req(QUrl("http://foo.bar"));
pnam->post(req, postData);

// execute an event loop to process the request (nearly-synchronous)
QEventLoop eventLoop;
// also dispose the event loop after the reply has arrived
connect(pnam, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
eventLoop.exec();

This way my user-defined slot for the pnam->finished() signal was called immediately, and I could be sure to have the HTTP reply at the end of this code snippet.

Found here: Qt-Interest Mailing List: QNetworkAccessManager and QNetworkReply, synchronous


Flattr this