0

I'm using a QWebEngineViewer widget in my QMainWindow and I want it to have the scrollbar always at the botom of the page every time I open my application. I have found some suggestions but none of them seem to work for me. For example, a posible answer i found used .runJavaScript() to modify de scrollbar position from there, but no matter what I but in the x or y axis the scrollbar doesn't move:

self.webEngine.page().runJavaScript("window.scrollTo(0, 0);")

Another suggestion used the setScrollBarValue() function, but I can't find it in QWebEngineViewer (I'm pretty sure that is from a previous version of qt). Here is the example provided in C++:

webView->page()->mainFrame()->setScrollBarValue(Qt::Vertical, webView->page()->mainFrame()->scrollBarMaximum(Qt::Vertical));

Thanks in advance for your help!

musicamante
  • 41,230
  • 6
  • 33
  • 58
  • Web page loading always take some time, as the renderer is always asynchronous (due to the fact that elements can be dynamic). If you want to scroll to the bottom, you have to wait for the page to finish its loading, for instance by connecting to the [`loadFinished`](https://doc.qt.io/qt-5/qwebengineview.html#loadFinished) signal. – musicamante Jul 09 '22 at 02:48
  • @musicamente Thank you very much for your answer! I connected the runJavaScript solution to the loadFinished signal and it worked like a charm! – Antigona_curiosa Jul 09 '22 at 03:04
  • Good! Then I suggest you to click the "Answer your question" button and provide your own answer by providing a proper [mre]. – musicamante Jul 09 '22 at 03:07
  • @musicamente Thank you! I got a new question tho: for now I put a great number (10000) in the y axis of window.scrollTo, and it worked in my test webpage but it may not work in longer pages. Is there any way to get the "maximum" value for the y axis for any webpage? – Antigona_curiosa Jul 09 '22 at 03:15
  • Well, that's tricky, most importantly because the dynamic nature of webpages (which could load contents when scrolling is detected) prevents to really reach the "bottom", since it could change in the meantime. Unfortunately, I'm afraid that the question is a bit off topic here, since it mostly relates to javascript. Consider looking for answers on that topic, maybe starting from [here](https://stackoverflow.com/q/11715646). – musicamante Jul 09 '22 at 03:30
  • I think I found a solution for the y axis problem. Thanks again for the suggestion! – Antigona_curiosa Jul 09 '22 at 03:39

1 Answers1

0

Here is what I did to solve the problem. First I implemented scrollDown as follows:

    def scrollDown(self):
        self.webEngine.page().runJavaScript("window.scrollTo(0, document.body.scrollHeight);") 

document.body.scrollHeight helps in locating the scrollbar at the bottom of the page.

Then I connected scrollDown to the loadFinished signal:

self.webEngine.loadFinished.connect(self.scrollDown)

Thanks @musicamante for the suggestion!