Search code examples
python-3.xpyqt5zoomingqgraphicsviewqgraphicsscene

Zooming into cursor in GraphicsView/GraphicsScene


I have a QGraphicsView widget which I'm using as a drawing canvas.

I want to be able to zoom into the mouse cursor position on ctrl+mwheel. As my code stands, it is scrolling only it seems into the center of the canvas, and not into the cursor position. It seems that the translation logic is wrong but I don't see how:

def zoomCanvas(self, event):
    zoomInFactor = 1.25
    zoomOutFactor = 1 / zoomInFactor
    oldPos = event.scenePos()
    if event.delta() > 0:
        zoomFactor = zoomInFactor
    else:
        zoomFactor = zoomOutFactor
    self.graphicsView.scale(zoomFactor, zoomFactor)
    newPos = event.scenePos()
    delta = newPos - oldPos
    self.graphicsView.translate(delta.x(), delta.y())

Solution

  • Yo

    Add these 2 to graphicsView init

        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)