canvas.py 2.3 KB

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