shape.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. # These are class variables so that changing them changes ALL shapes!
  8. point_type = P_SQUARE
  9. point_size = 8
  10. def __init__(self, label=None,
  11. line_color=QColor(0, 255, 0, 128),
  12. fill_color=QColor(255, 0, 0, 128)):
  13. self.label = label
  14. self.line_color = line_color
  15. self.fill_color = fill_color
  16. self.points = []
  17. self.fill = False
  18. def addPoint(self, point):
  19. self.points.append(point)
  20. def popPoint(self):
  21. if self.points:
  22. return self.points.pop()
  23. return None
  24. def isClosed(self):
  25. return len(self.points) > 1 and self[0] == self[-1]
  26. # TODO:
  27. # The paths could be stored and elements added directly to them.
  28. def paint(self, painter):
  29. if self.points:
  30. pen = QPen(self.line_color)
  31. painter.setPen(pen)
  32. line_path = QPainterPath()
  33. vrtx_path = QPainterPath()
  34. line_path.moveTo(QPointF(self.points[0]))
  35. self.drawVertex(vrtx_path, self.points[0])
  36. for p in self.points[1:]:
  37. line_path.lineTo(QPointF(p))
  38. # Skip last element, otherwise its vertex is not filled.
  39. if p != self.points[0]:
  40. self.drawVertex(vrtx_path, p)
  41. painter.drawPath(line_path)
  42. painter.fillPath(vrtx_path, self.line_color)
  43. if self.fill:
  44. painter.fillPath(line_path, self.fill_color)
  45. def drawVertex(self, path, point):
  46. d = self.point_size
  47. if self.point_type == self.P_SQUARE:
  48. path.addRect(point.x() - d/2, point.y() - d/2, d, d)
  49. else:
  50. path.addEllipse(QPointF(point), d/2.0, d/2.0)
  51. def __len__(self):
  52. return len(self.points)
  53. def __getitem__(self, key):
  54. return self.points[key]
  55. def __setitem__(self, key, value):
  56. self.points[key] = value