canvas.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from math import sqrt
  2. from PyQt4.QtGui import *
  3. from PyQt4.QtCore import *
  4. from shape import Shape
  5. class Canvas(QLabel):
  6. epsilon = 9.0 # TODO: Tune value
  7. def __init__(self, *args, **kwargs):
  8. super(Canvas, self).__init__(*args, **kwargs)
  9. self.shapes = []
  10. self.current = None
  11. self.line_color = QColor(0, 0, 255)
  12. self.line = Shape(line_color=self.line_color)
  13. def mouseMoveEvent(self, ev):
  14. """Update line with last point and current coordinates."""
  15. if self.current:
  16. if len(self.current) > 1 and self.closeEnough(ev.pos(), self.current[0]):
  17. self.line[1] = self.current[0]
  18. self.line.line_color = self.current.line_color
  19. else:
  20. self.line[1] = ev.pos()
  21. self.line.line_color = self.line_color
  22. self.repaint()
  23. def mousePressEvent(self, ev):
  24. if ev.button() == 1:
  25. if self.current:
  26. self.current.addPoint(self.line[1])
  27. self.line[0] = self.current[-1]
  28. if self.current.isClosed():
  29. self.finalise()
  30. self.repaint()
  31. else:
  32. self.current = Shape()
  33. self.line.points = [ev.pos(), ev.pos()]
  34. self.current.addPoint(ev.pos())
  35. self.setMouseTracking(True)
  36. def mouseDoubleClickEvent(self, ev):
  37. if self.current:
  38. self.current.addPoint(self.current[0])
  39. self.finalise()
  40. def paintEvent(self, event):
  41. super(Canvas, self).paintEvent(event)
  42. qp = QPainter()
  43. qp.begin(self)
  44. qp.setRenderHint(QPainter.Antialiasing)
  45. for shape in self.shapes:
  46. shape.paint(qp)
  47. if self.current:
  48. self.current.paint(qp)
  49. self.line.paint(qp)
  50. qp.end()
  51. def finalise(self):
  52. assert self.current
  53. self.current.fill = True
  54. self.shapes.append(self.current)
  55. self.current = None
  56. # TODO: Mouse tracking is still useful for selecting shapes!
  57. self.setMouseTracking(False)
  58. self.repaint()
  59. def closeEnough(self, p1, p2):
  60. #d = distance(p1 - p2)
  61. #m = (p1-p2).manhattanLength()
  62. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  63. return distance(p1 - p2) < self.epsilon
  64. def distance(p):
  65. return sqrt(p.x() * p.x() + p.y() * p.y())