Important: Please read the Qt Code of Conduct -

Moving QGraphicsItems in QGraphicsView after scaling gives fraction values!

  • I'm using the below functions to allow zooming in and out in QGraphicsView.

    void PtcGraphicsView::wheelEvent ( QWheelEvent * event )
     int numDegrees = event->delta() / 8;
     int numSteps = numDegrees / 15; // see QWheelEvent documentation
     _numScheduledScalings += numSteps;
     if (_numScheduledScalings * numSteps < 0) // if user moved the wheel in another direction, we reset previously scheduled scalings
     _numScheduledScalings = numSteps;
     QTimeLine *anim = new QTimeLine(350, this);
    //         QPoint targetViewportPos = pWheelEvent->pos();
             QPoint targetScenePos = mapToScene(event->pos()).toPoint();
     connect(anim, SIGNAL (valueChanged(qreal)), SLOT (scalingTime(qreal)));
     connect(anim, SIGNAL (finished()), SLOT (animFinished()));
    void PtcGraphicsView::scalingTime(qreal x)
     qreal factor = 1.0+ qreal(_numScheduledScalings) / 300.0;
     scale(factor, factor);
    void PtcGraphicsView::animFinished()
     if (_numScheduledScalings > 0)

    the problem is after using the scale and I try to move any item in the scene using dragging as before the movement positions becomes in fractions not in integers as before.
    Here is an example of the position of a rectangle before scaling
    and then when I made scaling and moved it a little bit this became the new position
    0_1535895584062_Screen Shot 09-02-18 at 03.37 PM.png
    Why is this happening and how to overcome it as I need a discrete system

  • What I am doing now as a workaround is that I override itemChanged and return the position approximated to next int position but I don't think that this is the right way of doing it.

  • What I reached as the problem is that the position accepts fraction values by default
    but at first the mapping is 1 : 1 between the scene and view so when I move any Item it is always in integer values, but then when I make any transformation the mapping is no longer 1:1 so items can now move in fraction values, and the solution in my case was 1 of 2 solutions either snapping the values to integers in the graphicsView mouse move event or snapping them in the GraphiscItem itemChange event.

Log in to reply