Important: Please read the Qt Code of Conduct -

PyQt5 - QGraphicsItem/QGraphicsPixmapItem Drag - Snap to Grid

  • Hey,

    I'm trying to implement a snap to grid function while dragging a QGraphicsPixmapItem in a QGraphicsScene. So far I used

    setFlag(QGraphicsItem.ItemIsMovable, True)

    in the QGraphicsPixmapItem subclass to enable the dragging itself. Now I want to implement a way to snap the item to a grid when the item is moved. Meaning the next grid position based on the current mouse position is estimated and the item is placed correspondingly. When the dragging is stopped, the item should stay in the current grid position.
    Does anybody have an idea on how to implement this? I will gladly provide more code if needed, but need to know which part is relevant. Please consider, that I'm fairly new to PyQt and may not understand more advanced terms immediately. Thank you in advance!

  • I figured it out myself, for anyone interested, it was sufficient to edit the mouseMoveEvent.

    class PixmapItem(QGraphicsPixmapItem):
        def __init__(self, path):
            QGraphicsPixmapItem.__init__(self, QPixmap(path))
            self.setFlag(QGraphicsItem.ItemIsMovable, True)
            self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):
            block_size = 50
            x = round(event.scenePos().x()/block_size)*block_size
            y = round(event.scenePos().y()/block_size)*block_size
            pos = QPointF(x, y)

Log in to reply