shape.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. select_color = QColor(255, 255, 255)
  14. point_type = P_SQUARE
  15. point_size = 8
  16. def __init__(self, label=None, line_color=None):
  17. self.label = label
  18. self.points = []
  19. self.fill = False
  20. self.selected = False
  21. if line_color is not None:
  22. # Override the class line_color attribute
  23. # with an object attribute. Currently this
  24. # is used for drawing the pending line a different color.
  25. self.line_color = line_color
  26. def addPoint(self, point):
  27. self.points.append(point)
  28. def popPoint(self):
  29. if self.points:
  30. return self.points.pop()
  31. return None
  32. def isClosed(self):
  33. return len(self.points) > 1 and self[0] == self[-1]
  34. # TODO:
  35. # The paths could be stored and elements added directly to them.
  36. def paint(self, painter):
  37. if self.points:
  38. pen = QPen(self.select_color if self.selected else self.line_color)
  39. painter.setPen(pen)
  40. line_path = QPainterPath()
  41. vrtx_path = QPainterPath()
  42. line_path.moveTo(QPointF(self.points[0]))
  43. self.drawVertex(vrtx_path, self.points[0])
  44. for p in self.points[1:]:
  45. line_path.lineTo(QPointF(p))
  46. # Skip last element, otherwise its vertex is not filled.
  47. if p != self.points[0]:
  48. self.drawVertex(vrtx_path, p)
  49. painter.drawPath(line_path)
  50. painter.fillPath(vrtx_path, self.line_color)
  51. if self.fill:
  52. painter.fillPath(line_path, self.fill_color)
  53. def drawVertex(self, path, point):
  54. d = self.point_size
  55. if self.point_type == self.P_SQUARE:
  56. path.addRect(point.x() - d/2, point.y() - d/2, d, d)
  57. else:
  58. path.addEllipse(point, d/2.0, d/2.0)
  59. def containsPoint(self, point):
  60. path = QPainterPath(QPointF(self.points[0]))
  61. for p in self.points[1:]:
  62. path.lineTo(QPointF(p))
  63. return path.contains(QPointF(point))
  64. def moveBy(self,dx,dy):
  65. index=0
  66. for point in self.points:
  67. newXPos= point.x()+dx
  68. newYPos=point.y()+dy
  69. self.points[index]=QPoint(newXPos,newYPos)
  70. index +=1
  71. def __len__(self):
  72. return len(self.points)
  73. def __getitem__(self, key):
  74. return self.points[key]
  75. def __setitem__(self, key, value):
  76. self.points[key] = value