Search code examples
qtscalingqgraphicsview

Scaling GraphicsView Widget With Sliders While displaying a Pixmap


I am trying to use the scale(qreal x, qreal y) method/function for Graphics view to scale a pixmap in the graphics view widget. Below I've attached code of my attempts. When I execute the program it will display my pixmap but as soon as I move the horizontal slider the pixmap disappears and the graphics view just displays a blank white page. The commented out parts are all things I have tried but produced the same result. I'm not entirely sure if scaling the graphics view will scale everything in the graphics view, I assumed so but could not find anything concrete from the documentation.

*One thing to note is that I have a button that displays two different Pixmaps, even after I am presented with the white screen upon moving the scroll bar, if I press the button it will still update the y axis scroll bar(as one pixmap is slightly larger than the graphics widget) however a blank white graphics view is still displayed

*PixMapView is the name of the graphics view widget

  void CanvasTest::on_horizontalSlider_valueChanged(int value)
{
    //int scaleX = value/(ui->horizontalSlider->maximum())*2;
    //Graph is updating and Y scroll bar is updating to show for it
    //int scaleY = ui->verticalSlider->value();
    QGraphicsScene* scene = ui->PixMapView->scene();
    ui->PixMapView->scale(value/10, 1);

    ui->PixMapView->setScene(scene);
    ui->PixMapView->show();
}

Solution

  • There was truncation issue using integers, this code also uses static variables to keep track of the previous scale values.

    static float valueTracker = 1;\
    static float valueTracker1 = 1;
    static int count = 1;
    
    bool order;
    if (count%2 == 1)
    {
        valueTracker = newSliderValue;
        order = 0;
    }
    else
    {
        valueTracker1 = newSliderValue;
        order = 1;
    }
    if(valueTracker == valueTracker1 || valueTracker == 0 || valueTracker1 == 0)
    {
        count++;
        return;
    }
    else if(order == 0)
    {
        ui->PixMapView->scale(((valueTracker/valueTracker1)), 1);
    }
    
    else if(order == 1)
    {
       ui->PixMapView->scale(((valueTracker1/valueTracker)), 1);
    }
    
    count++;