Search code examples
qtqgraphicsview

zooming GraphicsView with wheelEvent


Im implementing the zooming of my QGraphicsView using wheelEvent

void View::wheelEvent(QWheelEvent *e)
{
    if (e->modifiers().testFlag(Qt::ControlModifier)){ // zoom only when CTRL key pressed

        int numSteps = e->delta() / 15 / 8;

        if (numSteps == 0) {
            e->ignore();
            return;
        }
        qreal sc = pow(1.25, numSteps); // I use scale factor 1.25
        this->zoom(sc);


        e->accept();
    }
}

and the zoom item

void View::zoom(qreal scaleFactor)
{

     scale(scaleFactor, scaleFactor);

}

here i don’t want to zoom out too deeper, all i need it to restrict the scaling to certain point , i have to limit the zoom out so i tried to find the transform point

qreal
View::zoomScale() const
{
    return transform().m11();
}

but with this i cant able to restrict the zooming . please help me find the solution.


Solution

  • You can calculate the zoom factor relative to the "normal zoom" and decide if you can zoom or not.

    For example, you can take a QRect for reference and check its size after the zoom :

    void ClassA::scale(qreal scaleFactor) {
        QRectF(0, 0, 1, 1); // A reference
        qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(r).width(); // absolute zoom factor
        if ( factor > 20 ) { // Don't zoom more than 20x
            return;
        }
    
        this->scale(scaleFactor, scaleFactor);
    }