Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 497
Sid411 Avatar asked Dec 19 '22 22:12

Sid411


2 Answers

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.

like image 173
vahancho Avatar answered Dec 28 '22 07:12

vahancho


Here is one more implementation idea in which the current zoom factor is obtained from the transformation matrix for the view:

void View::wheelEvent(QWheelEvent *event) {
   const qreal detail = QStyleOptionGraphicsItem::levelOfDetailFromTransform(transform());
   const qreal factor = 1.1;

   if ((detail < 10) && (event->angleDelta().y() > 0)) scale(factor, factor);
   if ((detail > 0.1) && (event->angleDelta().y() < 0)) scale((1 / factor), (1 / factor));
}
like image 29
rzr_f Avatar answered Dec 28 '22 06:12

rzr_f