qtpyqtqgraphicssceneqgraphicsitemsnap-to-grid

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


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.


Solution

  • 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
    }