shape.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from PyQt4.QtGui import *
  4. from PyQt4.QtCore import *
  5. class Shape(object):
  6. P_SQUARE, P_ROUND = range(2)
  7. ## The following class variables influence the drawing
  8. ## of _all_ shape objects.
  9. line_color = QColor(0, 255, 0, 128)
  10. fill_color = QColor(255, 0, 0, 128)
  11. point_type = P_SQUARE
  12. point_size = 8
  13. def __init__(self, label=None, line_color=None):
  14. self.label = label
  15. self.points = []
  16. self.fill = False
  17. if line_color is not None:
  18. # Override the class line_color attribute
  19. # with an object attribute. Currently this
  20. # is used for drawing the pending line a different color.
  21. self.line_color = line_color
  22. def addPoint(self, point):
  23. self.points.append(point)
  24. def popPoint(self):
  25. if self.points:
  26. return self.points.pop()
  27. return None
  28. def isClosed(self):
  29. return len(self.points) > 1 and self[0] == self[-1]
  30. # TODO:
  31. # The paths could be stored and elements added directly to them.
  32. def paint(self, painter):
  33. if self.points:
  34. pen = QPen(self.line_color)
  35. painter.setPen(pen)
  36. line_path = QPainterPath()
  37. vrtx_path = QPainterPath()
  38. line_path.moveTo(QPointF(self.points[0]))
  39. self.drawVertex(vrtx_path, self.points[0])
  40. for p in self.points[1:]:
  41. line_path.lineTo(QPointF(p))
  42. # Skip last element, otherwise its vertex is not filled.
  43. if p != self.points[0]:
  44. self.drawVertex(vrtx_path, p)
  45. painter.drawPath(line_path)
  46. painter.fillPath(vrtx_path, self.line_color)
  47. if self.fill:
  48. painter.fillPath(line_path, self.fill_color)
  49. def drawVertex(self, path, point):
  50. d = self.point_size
  51. if self.point_type == self.P_SQUARE:
  52. path.addRect(point.x() - d/2, point.y() - d/2, d, d)
  53. else:
  54. path.addEllipse(QPointF(point), d/2.0, d/2.0)
  55. def __len__(self):
  56. return len(self.points)
  57. def __getitem__(self, key):
  58. return self.points[key]
  59. def __setitem__(self, key, value):
  60. self.points[key] = value