BuGiZ400
BuGiZ400

Reputation: 415

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).

Upvotes: 2

Views: 2423

Answers (1)

Nejat
Nejat

Reputation: 32685

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

Upvotes: 3

Related Questions