The QEventLoop class provides a means of entering and leaving an event loop.
At any time, you can create a QEventLoop object and call exec() on it to start a local event loop. From within the event loop, calling exit() will force exec() to return.
意思是说QEventLoop类为我们提供了一种进入和退出一个事件循环的方法。在任何时候,你都可以创建一个QEventLoop实例,然后调用exec()来启动一个事件循环,在这个循环期间,可以调用exit()来强制使exct()返回。
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
timer.start(3000); // 3 secs. timeout
loop.exec();
if(timer.isActive()) {
timer.stop();
if(m_reply->error() > 0) {
... // handle error
}
else {
int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (v >= 200 && v < 300) { // Success
...
}
}
} else {
// timeout
disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
reply->abort();
... // handle timeout
}
代码思路很清晰,在reply发送请求后开启一个事件循环等待完成事件,同时开一个定时器,3s内reply收到finished退出事件循环,停止定时器,处理返回结果。3s内reply无返回则超时,定时器结束,断开reply连接,处理超时结果。