# Copyright 2025–2026 European Union
# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
# SPDX-License-Identifier: EUPL-1.2
"""
Helper utilities for bridging Matplotlib and Qt interactions.
This module provides utilities to manage Matplotlib navigation modes and
handle context menu events between Qt widgets and Matplotlib canvases.
"""
from typing import Any, cast
from matplotlib.backend_bases import MouseButton, MouseEvent, _Mode
from PySide6.QtCore import QPoint
[docs]
class NavigationModeSuspender:
"""
Temporarily suspends Matplotlib navigation mode to allow Qt interactions.
This class is used to temporarily disable Matplotlib's navigation mode
when Qt-specific operations need to take precedence, such as handling
context menus or custom interactions.
"""
def __init__(self, toolbar: Any) -> None:
"""
Initialize the NavigationModeSuspender.
:param toolbar: The Matplotlib toolbar to suspend mode for
:type toolbar: matplotlib.backends.backend_qt5agg.NavigationToolbar2QT
"""
self._toolbar: Any = toolbar
self._saved_mode: _Mode = _Mode.NONE
[docs]
def suspend(self) -> None:
"""
Suspend the current navigation mode.
Saves the current mode and sets it to NONE to prevent Matplotlib
from intercepting mouse events during Qt operations.
"""
if self._toolbar.mode != _Mode.NONE:
self._saved_mode = self._toolbar.mode
self._toolbar.mode = _Mode.NONE
self._toolbar._update_buttons_checked()
else:
self._saved_mode = _Mode.NONE
[docs]
def restore(self) -> None:
"""
Restore the previously saved navigation mode.
Restores the navigation mode that was active before suspension.
"""
if self._saved_mode != _Mode.NONE:
self._toolbar.mode = self._saved_mode
self._toolbar._update_buttons_checked()
self._saved_mode = _Mode.NONE