c++ - QWebView等待加载

标签 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),也始终返回 true。

最佳答案

start(timeout); 以 msec 毫秒的超时间隔启动计时器。因此,在调用它之后,计时器正在运行,timer.isActive() 始终返回 true,并且 if block 不会被执行。

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

关于c++ - QWebView等待加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218444/

相关文章:

C++ 记录器性能和可移植性

c++ - 最快的预打包键值对搜索

C++/Qt - 可选参数默认为 NULL

javascript - 使用javascript动态加载内容的问题

java - Android 中的 *loading screen* 究竟是什么?

c++ - 如何修复cocosdx中的钻石子类

c++ - 将 int8_t 转换为 int,以便我可以对其执行操作

qt - 如何将 qundo 命令保存到文件并重新加载它?

c++ - QT绘图不删除widget

javascript - 网站加载时间的脚本