Search code examples
pythongtkgtk3

Listen to Control + mouse wheel scroll event in Python GTK3


I am building a Python GTK application and I need to listen to the "Ctrl+Mouse wheel" event. I want to implement "zoom" feature in Webview. Do I need to setup an accelerator? If yes, what is the key code for mouse wheel?

There isn't really much documentation on these topics.

Any help?

Thank you.


Solution

  • As it happens many times, After posting in SO I found the solution :)

    Here it is:

    Listen the "scroll event" on webview:

     self.connect('scroll-event', self.on_scroll)
    

    Signal handler

     def on_scroll(self, widget, event):
        """ handles on scroll event"""
    
       # Handles zoom in / zoom out on Ctrl+mouse wheel
       accel_mask = Gtk.accelerator_get_default_mod_mask()
       if event.state & accel_mask == Gdk.ModifierType.CONTROL_MASK:
         direction = event.get_scroll_deltas()[2]
         if direction > 0:  # scrolling down -> zoom out
            self.set_zoom_level(self.get_zoom_level() - 0.1)
         else:
            self.set_zoom_level(self.get_zoom_level() + 0.1)
    

    Reference: GDK signal, keypress, and key masks