Line data Source code
1 : # SPDX-FileCopyrightText: 2025 Pairinteraction Developers 2 : # SPDX-License-Identifier: LGPL-3.0-or-later 3 : 4 1 : from typing import Optional 5 : 6 1 : import matplotlib.pyplot as plt 7 1 : import numpy as np 8 1 : from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg 9 1 : from PySide6.QtCore import Qt, QTimer 10 1 : from PySide6.QtGui import QWheelEvent 11 1 : from PySide6.QtWidgets import QWidget 12 : 13 : 14 1 : class MatplotlibCanvas(FigureCanvasQTAgg): 15 : """Canvas for matplotlib figures.""" 16 : 17 1 : def __init__(self, parent: Optional[QWidget] = None) -> None: 18 : """Initialize the canvas with a figure.""" 19 1 : self.fig, self.ax = plt.subplots() 20 1 : super().__init__(self.fig) 21 : 22 1 : self.setup_zoom() 23 : 24 1 : def setup_zoom(self) -> None: 25 : """Set up mouse wheel zoom functionality.""" 26 : # Wheel event accumulation variables 27 1 : self.wheel_accumulation: float = 0 28 1 : self.last_wheel_pos: list[list[float]] = [] 29 1 : self.wheel_timer = QTimer(self) 30 1 : self.wheel_timer.setSingleShot(True) 31 1 : self.wheel_timer.timeout.connect(self.apply_accumulated_zoom) 32 1 : self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) 33 1 : self.setMouseTracking(True) 34 : 35 1 : def wheelEvent(self, event: QWheelEvent) -> None: 36 : """Handle mouse wheel events for zooming.""" 37 0 : self.wheel_accumulation += event.angleDelta().y() / 120 38 0 : self.last_wheel_pos.append([event.position().x(), event.position().y()]) 39 0 : self.wheel_timer.start(100) # Apply zoom after 100ms of inactivity 40 : 41 1 : def apply_accumulated_zoom(self) -> None: 42 : """Apply the accumulated zoom from wheel events.""" 43 0 : if not self.wheel_accumulation: 44 0 : return 45 : 46 0 : x_min, x_max = self.ax.get_xlim() 47 0 : y_min, y_max = self.ax.get_ylim() 48 : 49 0 : scale_factor = 1 - 0.1 * self.wheel_accumulation 50 : 51 : # Get the mouse position in data coordinates 52 0 : wheel_pos_mean = np.mean(self.last_wheel_pos, axis=0) 53 0 : x_data, y_data = self.ax.transData.inverted().transform(wheel_pos_mean) 54 0 : y_data = -(y_data - (y_max + y_min) / 2) + (y_max + y_min) / 2 # y_data is mirrored bottom / top 55 : 56 0 : self.wheel_accumulation = 0 57 0 : self.last_wheel_pos = [] 58 : 59 0 : if x_data > x_max or y_data > y_max or (x_data < x_min and y_data < y_min): 60 0 : return 61 : 62 0 : if x_min <= x_data <= x_max: 63 0 : x_min_new = x_data - (x_data - x_min) * scale_factor 64 0 : x_max_new = x_data + (x_max - x_data) * scale_factor 65 0 : self.ax.set_xbound(x_min_new, x_max_new) 66 0 : self.ax.set_autoscalex_on(False) 67 : 68 0 : if y_min <= y_data <= y_max: 69 0 : y_min_new = y_data - (y_data - y_min) * scale_factor 70 0 : y_max_new = y_data + (y_max - y_data) * scale_factor 71 0 : self.ax.set_ybound(y_min_new, y_max_new) 72 0 : self.ax.set_autoscaley_on(False) 73 : 74 : # Redraw the canvas 75 0 : self.draw()