Search code examples
qtqtwebkit

Restore scrollbar position of QWebView after setHtml()


I constantly generate new HTML pages that I display in a QWebView. Now I have trouble to restore the current position of the vertical scrollbar after the setHtml() call, if the HTML contains images. The scrollbar always jumps back to the top.

The following code works as long as the HTML only contains text:

void MainWindow::htmlResultReady(const QString &html)
{
     // remember scrollbar position
     int scrollBarPos = ui->webView->page()->mainFrame()->scrollBarValue(Qt::Vertical);

     ui->webView->setHtml(html);

     // restore previous scrollbar position
     ui->webView->page()->mainFrame()->setScrollBarValue(Qt::Vertical, scrollBarPos);
}

I also tried to use the signal QWebView::loadFinished() without success:

void MainWindow::setupHtmlPreview()
{
     connect(ui->webView, SIGNAL(loadFinished(bool)),
             this, SLOT(restoreScrollBarPosition()));
}

void MainWindow::htmlResultReady(const QString &html)
{
     // remember scrollbar position
     scrollBarPos = ui->webView->page()->mainFrame()->scrollBarValue(Qt::Vertical);

     ui->webView->setHtml(html);
}

void MainWindow::restoreScrollBarPosition()
{
     // restore previous scrollbar position
     ui->webView->page()->mainFrame()->setScrollBarValue(Qt::Vertical, scrollBarPos);
}

Solution

  • Perhaps the size of the page changes. Call setScrollBarValue when contentsSizeChanged is emitted by the frame (typically webView->page()->mainFrame()).