QGraphicsView mousewheel zoom
-
For my application which uses QGraphicsView and QGraphicsScene, I am trying to implement a mousewheel zoom function. The best I've come up with is the following, which (kinda) works but has an annoying issue:
# Method in QGraphicsView def wheelEvent(self, event): factor = 1 * (event.angleDelta().y() / 1000 + 1) view_rect = QRect( 0, 0, self.viewport().width(), self.viewport().height()) visible_scene_rect = QRectF( self.mapToScene(view_rect).boundingRect()) view_width = visible_scene_rect.size().width() scene_width = self.sceneRect().size().width() view_height = visible_scene_rect.size().height() scene_height = self.sceneRect().size().height() if (0 < factor < 1) and ( view_width < scene_width or view_height < scene_height): self.scale(factor, factor) self._zoom = self._zoom * factor elif factor > 1 and self._zoom < 3: self.scale(factor, factor) self._zoom = self._zoom * factor
(The scene's
sceneRect()
has been properly set beforehand).The issue is that if the user is zooming out with a rapid gesture (e.g. on a trackpad), it is possible to zoom much farther than the scene's extents. The scene then becomes ridiculously small.
I feel the code is going through some convoluted calculations which should be handled in a simpler fashion, since this is such a common scenario, but I'm not sure how to achieve this.
Thanks for your help.
-
Hi
This example also has zoom
https://doc.qt.io/qt-5/qtwidgets-graphicsview-chip-example.htmlYou code looks fine.