QNetworkReply wait for finished

yolo picture yolo · Mar 30, 2011 · Viewed 27.2k times · Source

I am using Qt 4.6.3 and the following not-working code

QStringList userInfo;
QNetworkRequest netRequest(QUrl("http://api.stackoverflow.com/1.1/users/587532"));
QNetworkReply *netReply = netman->get(netRequest);

// from here onwards not working
netReply->waitForReadyRead(-1);
if (netReply->isFinished()==true)
{userInfo << do sth to reply;}
return userInfo;

as this function returns an empty QStringList, the app crashes. How to wait until the request has finished and then process the reply within one function

Answer

Kamil Klimek picture Kamil Klimek · Mar 31, 2011

You can use event loop:

QEventLoop loop;
connect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
// here you have done.

Also you should consider adding some shorter then network timeout (20s?). I'm not sure if finished is called even if an error occured. So it is possible, that you have connect to error signal also.