graphics_sketch_group.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from PyQt5.QtWidgets import QGraphicsItemGroup, QGraphicsRectItem, QGraphicsEllipseItem
  2. from PyQt5.QtCore import QRect
  3. from graphics_sketch_line import SketchedLineItem
  4. class SketchGroup(QGraphicsItemGroup):
  5. def __init__(self):
  6. QGraphicsItemGroup.__init__(self)
  7. self._prev_pos = self.scenePos() # empty initially (why?)
  8. def get_item_coord_relative(self, item):
  9. """
  10. Returns the item coordinate description, relative to the group.
  11. Depending on the type of item, the return type will differ (rectangle for rectangle and ellipse, two points
  12. for line)
  13. """
  14. if item not in self.childItems():
  15. return None
  16. sketch_brect = self.sceneBoundingRect()
  17. if isinstance(item, QGraphicsRectItem) or isinstance(item, QGraphicsEllipseItem):
  18. item_brect = item.sceneBoundingRect()
  19. top_left = (item_brect.topLeft() - sketch_brect.topLeft()).toPoint()
  20. return QRect(top_left.x(), top_left.y(), int(item_brect.width()), int(item_brect.height()))
  21. elif isinstance(item, SketchedLineItem):
  22. return (item.get_p1() - sketch_brect.topLeft()).toPoint(), (item.get_p2() - sketch_brect.topLeft()).toPoint()
  23. else:
  24. return None
  25. def mousePressEvent(self, event):
  26. self._prev_pos = self.scenePos()
  27. #print("Mouse pressed on group, coord {}".format(self._prev_pos))
  28. QGraphicsItemGroup.mousePressEvent(self, event)
  29. def mouseReleaseEvent(self, event):
  30. cur_pos = self.scenePos()
  31. #print("Mouse released on group, coord {}".format(cur_pos))
  32. diff_point = cur_pos - self._prev_pos
  33. #print("Diff is {}".format(diff_point))
  34. # update line coordinates since we moved the group
  35. for item in self.childItems():
  36. if isinstance(item, SketchedLineItem):
  37. #print("Updating coordinates of line")
  38. new_p1 = item.get_p1() + diff_point
  39. new_p2 = item.get_p2() + diff_point
  40. item.set_p1(new_p1)
  41. item.set_p2(new_p2)
  42. QGraphicsItemGroup.mouseReleaseEvent(self, event)