shape.py 2.2 KB

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