Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. PyQt5 - QGraphicsItem/QGraphicsPixmapItem Drag - Snap to Grid
Forum Updated to NodeBB v4.3 + New Features

PyQt5 - QGraphicsItem/QGraphicsPixmapItem Drag - Snap to Grid

Scheduled Pinned Locked Moved Solved Qt for Python
2 Posts 1 Posters 1.5k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    Felip
    wrote on last edited by
    #1

    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!

    1 Reply Last reply
    0
    • F Offline
      F Offline
      Felip
      wrote on last edited by
      #2

      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)
              self.setPos(pos)
      
      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved