Question

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

Was it helpful?

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.

OTHER TIPS

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));
}

Another way to solve the problem:

void GraphWidget::wheelEvent(QWheelEvent *event)
{
    int scaleFactor = pow((double)2, - event->delta() / 240.0);

    qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
    if (factor < 0.5 || factor > 20)
        return;
    scale(scaleFactor, scaleFactor);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top