im_scene.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from enum import Enum
  2. from PyQt5.QtWidgets import QGraphicsScene, QGraphicsItem
  3. from PyQt5.Qt import Qt, QTransform
  4. from sketchUI.graphics_edge_item import GraphicsEdgeItem
  5. from sketchUI.graphics_node_item import GraphicsNodeItem
  6. from sketchUI import mvops
  7. class Mode(Enum):
  8. SELECT = 0
  9. CONNECT = 1
  10. class CustomScene(QGraphicsScene):
  11. def __init__(self, model):
  12. QGraphicsScene.__init__(self)
  13. self._mode = None # set by mainwindow at start
  14. self.connect_from_item = None # store the item to draw the connecting line from
  15. self._cur_model = model # the mv model we operate on
  16. def set_mode(self, mode):
  17. self._mode = mode
  18. def mousePressEvent(self, event):
  19. if event.button() == Qt.LeftButton and self._mode == Mode.CONNECT:
  20. item = self.itemAt(event.scenePos(), QTransform())
  21. if not item:
  22. return
  23. self.connect_from_item = item
  24. QGraphicsScene.mousePressEvent(self, event)
  25. def mouseReleaseEvent(self, event):
  26. if event.button() == Qt.LeftButton and self._mode == Mode.CONNECT:
  27. item = self.itemAt(event.scenePos(), QTransform())
  28. if not item:
  29. return
  30. if item == self.connect_from_item:
  31. print("Not connecting same elements")
  32. return
  33. self.draw_edge(self.connect_from_item, item, is_new=True)
  34. if event.button() == Qt.LeftButton and self._mode == Mode.SELECT:
  35. item = self.itemAt(event.scenePos(), QTransform())
  36. if not item:
  37. return
  38. for item in self.items():
  39. try:
  40. item.__hack__() # hack to check if item is of edge type
  41. item.redraw()
  42. except AttributeError:
  43. continue
  44. QGraphicsScene.mouseReleaseEvent(self, event)
  45. def draw_edge(self, from_item, to_item, is_new):
  46. # type: (GraphicsNodeItem, GraphicsNodeItem, bool) -> None
  47. from_type = from_item.get_type()
  48. to_type = to_item.get_type()
  49. if is_new:
  50. if not mvops.is_edge_supported(from_type, to_type):
  51. print("edge not supported between {} and {}".format(from_type, to_type))
  52. return
  53. line = GraphicsEdgeItem(from_item, to_item)
  54. line.setFlag(QGraphicsItem.ItemIsMovable, False)
  55. line.setFlag(QGraphicsItem.ItemIsSelectable, False)
  56. self.addItem(line)
  57. line.redraw()
  58. if is_new:
  59. mvops.add_edge(self._cur_model, from_item.node_id, to_item.node_id)