Search code examples
c++qtloadingqwebview

QWebView Wait for load


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

Say me, is that a correct code? App sometimes freezes after line

loopLoad.exec();

And always returns true even here has happened some problem (timeout, errors when loading, ect -- always true).


Solution

  • start(timeout); starts the timer with a timeout interval of msec milliseconds. So after calling it the timer is running and timer.isActive() always returns true and the if block does not get executed.

    You should stop the timer when loadFinished is emitted :

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

    If the timer is active then the event loop is stopped by the timer so you should return false because a timeout has been occurred. You should replace if(!timer.isActive()) with if(timer.isActive()).

    The correct code is :

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