QWebView Wait for load
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | bool MainWindow::waitForLoad(QWebView& view) { QEventLoop loopLoad; QTimer timer; QObject::connect(&view, SIGNAL(loadFinished(bool)), &loopLoad, SLOT(quit())); QObject::connect(&timer, SIGNAL(timeout()), &loopLoad, SLOT(quit())); timer.start(timeout); loopLoad.exec(); if(!timer.isActive()) { timer.stop(); view.stop(); return false; } return true; } |
告诉我,这是一个正确的代码吗?应用程序有时会在 line
之后冻结
1 | loopLoad.exec(); |
即使这里发生了一些问题,也总是返回 true(超时、加载时出错等等——总是 true)。
您应该在发出 loadFinished 时停止计时器:
1 | QObject::connect(&view, SIGNAL(loadFinished(bool)), &timer, SLOT(stop())); |
如果计时器处于活动状态,则事件循环被计时器停止,因此您应该返回 false,因为发生了超时。您应该将
正确的代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | bool MainWindow::waitForLoad(QWebView& view) { QEventLoop loopLoad; QTimer timer; QObject::connect(&view, SIGNAL(loadFinished(bool)), &loopLoad, SLOT(quit())); QObject::connect(&view, SIGNAL(loadFinished(bool)), &timer, SLOT(stop())); QObject::connect(&timer, SIGNAL(timeout()), &loopLoad, SLOT(quit())); timer.start(timeout); loopLoad.exec(); if(timer.isActive()) { timer.stop(); view.stop(); return false; } return true; } |