SoFunction
Updated on 2025-03-02

How to drag and zoom pictures through mouse events

Move the picture by dragging the mouse, and use the mouse wheel to zoom the picture.

1. Implementation steps:

1. Mobile pictures:

Use QPoint to record the offset of the picture, update this offset when the mouse drags, and draw the picture according to the offset in paintEvent().

2. Zoom pictures:

Use the scroll wheel event to adjust the zoom multiple of the picture and apply the zoom when redrawing the picture in paintEvent().

2. Complete solution:

1、

#ifndef IMAGEWIDGET_H
#define IMAGEWIDGET_H

#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPixmap>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QPainter>
#include <QVBoxLayout>
#include <QDebug>

class ImageWidget : public QWidget
{
    Q_OBJECT

public:
    ImageWidget(QWidget *parent = nullptr);
protected:
    // Rewrite paintEvent to draw pictures    void paintEvent(QPaintEvent *event) override;

    // Mouse press event    void mousePressEvent(QMouseEvent *event) override;

    // Mouse movement event    void mouseMoveEvent(QMouseEvent *event) override;
    // Mouse release event    void mouseReleaseEvent(QMouseEvent *event) override;
    // Scroller event, used to zoom in pictures    void wheelEvent(QWheelEvent *event) override;

private:
    QPixmap pixmap;            // picture    QPoint lastMousePosition;  // The location of the last mouse click    QPoint offset;             // The offset of the picture    bool isDragging;           // Tag whether the image is being dragged    double scaleFactor;        // Scaling multiple};

#endif // IMAGEWIDGET_H

2、

#include ""

ImageWidget::ImageWidget(QWidget *parent) : QWidget(parent)
{
    // Load the picture    pixmap = QPixmap(R"(C:\Users\LiangQL\Desktop\Basic Developer Certification.jpg)");  // Replace with your image path    scaleFactor = 1.0;        // The initial scaling factor is 1    isDragging = false;       // Don't drag in the initial state    offset = QPoint(0, 0);    // The initial offset of the picture is (0, 0)}
// Rewrite paintEvent to draw picturesvoid ImageWidget::paintEvent(QPaintEvent *event)
{
    // Create a QPainter for drawing pictures    QPainter painter(this);
    (QPainter::SmoothPixmapTransform);  // Turn on smooth zoom
    // Calculate the zoomed image size    QSize scaledSize = () * scaleFactor;

    // Draw pictures, apply scaling and offsets    (offset, (scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
}

// Mouse press eventvoid ImageWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = true;                // Start dragging        lastMousePosition = event->pos(); // Record the mouse click position    }
}

// Mouse movement eventvoid ImageWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (isDragging) {
        // Calculate the distance of the mouse        QPoint delta = event->pos() - lastMousePosition;

        // Update the offset of the image        offset += delta;

        // Update mouse position        lastMousePosition = event->pos();

        // Trigger redraw        update();
    }
}

// Mouse release eventvoid ImageWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = false;  // End drag    }
}

// Scroller event, used to zoom in picturesvoid ImageWidget::wheelEvent(QWheelEvent *event)
{
    // The roller is enlarged up and down    if (event->angleDelta().y() > 0) {
        scaleFactor *= 1.1;  // Zoom in    } else {
        scaleFactor /= 1.1;  // Shrink    }

    // Limit the scaling range    scaleFactor = qBound(0.1, scaleFactor, 10.0);

    // Update display    update();
}

3. Call

#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPixmap>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QPainter>
#include <QVBoxLayout>
#include <QDebug>
#include ""

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Create the main window    QWidget window;
    (800, 600);  // Set the window size
    // Create image control (custom class)    ImageWidget *imageWidget = new ImageWidget;

    // Use Layout Manager to place the image control in the window    QVBoxLayout *layout = new QVBoxLayout(&window);
    layout->addWidget(imageWidget);

    // Show the main window    ();

    return ();
}

3. Detailed explanation:

1. paintEvent() repaint the picture:

The paintEvent() method is used to customize the drawing of the control. In this method, we use QPainter object to draw the picture.
(): Use the () method to scale the picture, scale the picture according to the scaleFactor and maintain its aspect ratio.
(offset, ...): Draw the picture at the specified offset position. Offset indicates the offset of the picture in the control.

2. Picture move:

mousePressEvent(): When the left mouse button is pressed, record the mouse click position and start dragging the image (isDragging = true).
mouseMoveEvent(): If the image is being dragged (isDragging is true), the mouse movement distance is calculated, and the offset offset of the image is updated to the original offset plus the distance of the mouse movement.
mouseReleaseEvent(): When the left mouse button is released, dragging ends (isDragging = false).

3. Image zoom:

wheelEvent(): handles mouse wheel events. When the roller is upward, enlarge the picture; when the roller is downward, shrink the picture.
scaleFactor *= 1.1: Each time you scroll, the scaling multiple changes by 10%.
qBound(0.1, scaleFactor, 10.0): Limit the scaling ratio between 0.1 and 10 times to prevent the image from shrinking too small or too large.

4. Smooth zoom:

Qt::SmoothTransformation: Use smooth scaling algorithm to prevent jagging after image scaling.

5. The function of offset:

offset is used to record the offset of the picture relative to the window, and update this offset when the mouse drags.
In paintEvent(), this offset is used to control the position of the picture every time you draw.
Running effect:
Drag the picture: Hold down the left mouse button and move it to see the picture move inside the window.
Zoom picture: Scroll the mouse wheel, the picture will be enlarged or reduced while maintaining the aspect ratio.

Summarize

This is the article about how QT can drag and zoom images through mouse events. For more related content related to QT mouse events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!