Search code examples
qtqgraphicsview

Set zoom out limit for a picture in QGraphicsView


I am zooming an image on a label using QGraphicsView. But when I zoom out I want to set a specific limit for the zoom out. I am using the following code

scene = new QGraphicsScene(this);
view = new QGraphicsView(label);
QPixmap pix("/root/Image);
Scene->addPixmap(pixmap);
view->setScene(scene);
view->setDragMode(QGraphicsView::scrollHandDrag);

In the slot of wheel event

void MainWindow::wheelEvent(QWheelEvent *ZoomEvent)
{
    view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    double scaleFactor = 1.15;
    if(ZoomEvent->delta() >0)
    {
        view->scale(scaleFactor,scaleFactor);
    }
    else
    {
        view->scale(1/scaleFactor,1/scaleFactor);
    }
}

I want that the image should not zoom out after a certain extent. What should I do? I tried setting the minimum size for QGraphicsView but that didn't help.

Thank You :)


Solution

  • Maybe something like this would help:

    void MainWindow::wheelEvent(QWheelEvent *ZoomEvent)
    {
        view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
        static const double scaleFactor = 1.15;
        static double currentScale = 1.0;  // stores the current scale value.
        static const double scaleMin = .1; // defines the min scale limit.
    
        if(ZoomEvent->delta() > 0) {
            view->scale(scaleFactor, scaleFactor);
            currentScale *= scaleFactor;
        } else if (currentScale > scaleMin) {
            view->scale(1 / scaleFactor, 1 / scaleFactor);
            currentScale /= scaleFactor;
        }
    }
    

    The idea, as you can see, is caching the current scale factor and do not zoom out in case of it smaller than some limit.