Handling MacOS Gesture Events (Pinch, Zoom, Rotate) in PyQt or PySide2

  • Python
When using a QWidget and QMainWindow, we can use overridden methods to handle mouse and key-press events.
However, such predefined methods do not contain anything specific for gestures produced by a trackpad in MacOS.
This article tells you how a gesture event can be obtained and handled in PyQt or PySide2.

Where a Gesture Event is Generated?

As documented in Qt, a gesture event is stored as a QNativeGestureEvent event.
However, the native QWidget and QMainWindow classes do not include methods for handling such an event directly.
As a result, we will have to recognize the gesture events by ourselves in the QWidget.event() method.

Overriding the event() Method

In your QWidget or QMainWindow class, use the following method as a base to override the event() method:

def event(self, e):
    pass
    return QMainWindow(self, e)
where pass is where we are going to recognize our gesture events (described next) and QMainWindow should be altered by QWidget if you are using QWidget here.

Handling Gesture Events

To check QNativeGestureEvent, remember to import the dependency:

from PySide2.QtGui import QNativeGestureEvent
in which PySide2 should be PyQt if that’s your case.

Now we can check the type for the incoming event:

def event(self, e):
    if isinstance(e, QNativeGestureEvent):
        print(e.gestureType(), e.pos(), e.value())
    return QMainWindow(self, e)
in which we print three most important values when a gesture event is identified:
e.gestureType() gives you the type of gestures (either pinch, zoom or rotate) the current event is.
e.pos() gives you the cursor position where gesture is happening.
e.value() gives you the percentage of either the degree of zooming or rotating angle.
For detailed description, check the Qt official page.

Note that doing what stated above does not impact how you handle events from other overridden event handling methods since we have called return QMainWindow(self, e).

Was this post helpful?

Leave a Reply

Your email address will not be published.