canvas.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. # Add first point in the list so that it is consistent
  39. # with shapes created the normal way.
  40. self.current.addPoint(self.current[0])
  41. self.finalise()
  42. def paintEvent(self, event):
  43. super(Canvas, self).paintEvent(event)
  44. qp = QPainter()
  45. qp.begin(self)
  46. qp.setRenderHint(QPainter.Antialiasing)
  47. for shape in self.shapes:
  48. shape.paint(qp)
  49. if self.current:
  50. self.current.paint(qp)
  51. self.line.paint(qp)
  52. qp.end()
  53. def finalise(self):
  54. assert self.current
  55. self.current.fill = True
  56. self.shapes.append(self.current)
  57. self.current = None
  58. # TODO: Mouse tracking is still useful for selecting shapes!
  59. self.setMouseTracking(False)
  60. self.repaint()
  61. def closeEnough(self, p1, p2):
  62. #d = distance(p1 - p2)
  63. #m = (p1-p2).manhattanLength()
  64. #print "d %.2f, m %d, %.2f" % (d, m, d - m)
  65. return distance(p1 - p2) < self.epsilon
  66. def distance(p):
  67. return sqrt(p.x() * p.x() + p.y() * p.y())