Search code examples
c++qtqgraphicsviewqgraphicsscene

the zoom in and zoom out a Qgraphicsscene with QSlider


I have a QGraphicsScene and I want to do zooming (in and out) with a QSlider, I have this code:

void fonction(){
    Scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(Scene);
    QPen Pen ;
    QBrush Brush(Qt::red) ;
    Pen.setWidth(5);
    ellipse = Scene->addEllipse(2,2,30,30,Pen,Brush);
}


void HomePage::on_verticalSlider_valueChanged(int value)
{
    float z ;
    if(value==0 )
        z=0.1;
    else
        z  = value*0.01;

    Scene->update();
    ui->graphicsView->transform();
    ui->graphicsView->scale(z,z);
}

The interval of QSlider is [0.1 -> 1 ] My problem is the zoom out does not work, why ? how do I resolve this problem?


Solution

  • Your problem is that the matrix controlling the view of the scene does not reset every update of the slider, it is just a running multiplication. A simple approach would be to save the current value in a member variable for HomePage (lets call it m_current_scale) and undo the zoom before you do another one.

    void HomePage::on_verticalSlider_valueChanged(int value)
    {
        float z ;
        if(value==0 )
            z=0.1;
        else
            z  = value*0.01;
    
        Scene->update();
        ui->graphicsView->transform();
    
        const double scale_inverse = 1.0 / (double)m_current_scale;
        ui->graphicsView->scale(scale_inverse, scale_inverse);
        m_current_scale = z;
    
        ui->graphicsView->scale(z,z);
    }