blag: make calendar start on monday
[www-rohieb-name.git] / blag / post / qt-nearly-synchronous-qnetworkaccessmanager-calls.mdwn
1 [[!meta title="Qt: (Nearly) synchronous QNetworkAccessManager calls"]]
2 [[!meta date="2010-07-08"]]
3 [[!meta author="rohieb"]]
4 [[!meta license="CC-BY-SA 3.0"]]
5
6 The [QNetworkAccessManager][0] class is very user-friendly, but it makes
7 asynchronous calls. I was in the need for synchronous calls to handle my
8 HTTP communication, but I did not want the overhead of another thread,
9 so I googled a bit and finally came up with a short call to an event
10 loop that processed the request. Like this:
11
12 [[!format c """
13 QNetworkAccessManager * pnam = new QNetworkAccessManager(this);
14 // the slot was declared at another place
15 connect(pnam, SIGNAL(finished(QNetworkReply *)), this,
16 SLOT(loginFinished(QNetworkReply*)));
17 QNetworkRequest req(QUrl("http://foo.bar"));
18 pnam->post(req, postData);
19
20 // execute an event loop to process the request (nearly-synchronous)
21 QEventLoop eventLoop;
22 // also dispose the event loop after the reply has arrived
23 connect(pnam, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
24 eventLoop.exec();
25 """]]
26
27 This way my user-defined slot for the `pnam->finished()` signal was
28 called immediately, and I could be sure to have the HTTP reply at the
29 end of this code snippet.
30
31 Found here: [Qt-Interest Mailing List: QNetworkAccessManager and
32 QNetworkReply, synchronous][1]
33
34 [0]: http://doc.qt.nokia.com/4.6/qnetworkaccessmanager.html
35 [1]: http://lists.qt.nokia.com/public/qt-interest/2010-April/022031.html
36
37 [[!tag howto programming multithreading network Qt signals slots]]
This page took 0.040047 seconds and 5 git commands to generate.