How do you implement a snap-to-grid in QGraphicsScene? Mine didn't work

1.4k Views Asked by At

I don't have any code to show because this was over a year ago. I used a timer I think. It did not work very professionally. How would you do it so that it is a smooth operator?

I am already able to draw the grid efficiently (ie. in view only). I just need the snapping algorithm.

2

There are 2 best solutions below

0
On BEST ANSWER

Here is my mouseReleaseEvent for QGraphicsItem's derivative class. Grid has a step equal to 5:

void RadBox::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    double xx=x();
    double yy=y();
    if((int)xx / 5 != xx/5.) xx=5.0*round(xx/5.);
    if((int)yy / 5 != yy/5.) yy=5.0*round(yy/5.);
    setPos(xx,yy);
    QGraphicsItem::mouseReleaseEvent(event);
    emit moveBox(id,scenePos().x(),scenePos().y()); // you don't need this line, it's specific to my program
}
0
On

Re-implement QGraphicsItem::itemChange() to react upon the QGraphicsItem::ItemPositionChange change. Don't forget to set the QGraphicsItem::ItemSendsGeometryChanges flag.