Function:

Zoom in and out with the mouse position as the center

Principle that

The effect of scaling the canvas at the cursor position can be understood as such that the coordinate point on the canvas corresponding to the cursor continues to correspond to the cursor position before and after scaling. When you scale a canvas, the canvas will scale at the top left corner of the canvas.

So after each zoom, we need to move the cursor back on the canvas to achieve the desired effect.

A. Calculation principle:

1. Locate the position of the cursor corresponding to the canvas coordinate system

2. Zoom (see code block below)

3. Calculate the new position of target (_target) after scaling according to the scaling ratio

4. Calculate the displacement

5. Move the canvas

Scaling part

#define ZOOM_IN_TIMES -5 #define ZOOM_OUT_TIMES 5 void scaledemo::wheelEvent(QWheelEvent *event) { qreal s=0; bool in = true; bool out = true; if(event->delta() >= 0) { scaleValue += 1; } if(event->delta() < 0) { scaleValue -= 1; } if( scaleValue < ZOOM_IN_TIMES ) { scaleValue = ZOOM_IN_TIMES; in = false; return; }else if( scaleValue > ZOOM_OUT_TIMES ) { scaleValue = ZOOM_OUT_TIMES; out = false; return; } if(in) {s = qPow(1.01,event->delta()/10); } if(out) {s = qPow(1/1.01,-event->delta()/10); } scale(s,s); }Copy the code