QWebView等待加载

时间:2014-06-14 09:17:40

标签: c++ qt loading qwebview

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;
}

说我,这是正确的代码吗?应用程序有时会在行后冻结

loopLoad.exec();

并且总是返回true,即使这里发生了一些问题(超时,加载时出错,等等 - 总是如此)。

1 个答案:

答案 0 :(得分:3)

start(timeout);以超时间隔msec毫秒启动计时器。所以在调用它之后,计时器正在运行,timer.isActive()总是返回true而if块没有被执行。

你应该在发出loadFinished时停止计时器:

QObject::connect(&view, SIGNAL(loadFinished(bool)), &timer, SLOT(stop()));

如果计时器处于活动状态,则计时器会停止事件循环,因此您应该返回false,因为已发生超时。您应该将if(!timer.isActive())替换为if(timer.isActive())

正确的代码是:

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;
}