Electricmonk

Ferry Boender

Programmer, DevOpper, Open Source enthusiast.

Blog

Manually scrolling a Python GTK Webview

Wednesday, March 2nd, 2016

I was trying to manually scroll a (Python) GTK embedded Webview in order to position the webview back to where it was after setting new contents with webview.load_html_string(html, 'file:///'). I couldn't get it to work, and Google wasn't of much help either.

I could scroll the Webview just fine from a key-press-event handler on the main window like this:

def __init__(self):
    # -- Removed some code here for brevity --
    self.scroll_window = gtk.ScrolledWindow(None, None)
    self.scroll_window.add(self.webview)
    self.win_main.connect("key-press-event", self.ev_key_press_event)

def ev_key_press_event(self, widget, ev):
    if ev.keyval == gtk.keysyms.t:
        self.scroll_window.get_vadjustment().set_value(100)    

But automatically scrolling when something happened to the webview (in my case new content being set via webview.load_html_string()) didn't work. 

It turns out that the webview is still handling events and won't allow scrolling using `scroll_window.get_vadjustment().set_value()` until all the events are handled.

You can manually handle all the pending GTK events before starting scrolling like this:

def __init__(self):
    # -- Removed some code here for brevity --
    self.scroll_window = gtk.ScrolledWindow(None, None)
    self.scroll_window.add(self.webview)
    webview.connect('notify::load-status', self.ev_load_status)

def ev_load_status(self, webview, load_status):
    if self.webview.get_load_status() == webkit.LOAD_FINISHED:
        while gtk.events_pending():
            gtk.main_iteration_do()

        self.scroll_window.get_vadjustment().set_value(100)

The solution above works for me on both initial load of a document and subsequent changing of the webkit contents using `webview.load_html_string()`.

The text of all posts on this blog, unless specificly mentioned otherwise, are licensed under this license.