ToolMeasurement.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from PyQt4 import QtGui
  2. from FlatCAMTool import FlatCAMTool
  3. from copy import copy
  4. from math import sqrt
  5. class Measurement(FlatCAMTool):
  6. toolName = "Measurement Tool"
  7. def __init__(self, app):
  8. FlatCAMTool.__init__(self, app)
  9. # self.setContentsMargins(0, 0, 0, 0)
  10. self.layout.setMargin(0)
  11. self.layout.setContentsMargins(0, 0, 3, 0)
  12. self.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Maximum)
  13. self.point1 = None
  14. self.point2 = None
  15. self.label = QtGui.QLabel("Click on a reference point ...")
  16. self.label.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Plain)
  17. self.label.setMargin(3)
  18. self.layout.addWidget(self.label)
  19. # self.layout.setMargin(0)
  20. self.setVisible(False)
  21. self.click_subscription = None
  22. self.move_subscription = None
  23. def install(self, icon=None, separator=None, **kwargs):
  24. FlatCAMTool.install(self, icon, separator, **kwargs)
  25. self.app.ui.right_layout.addWidget(self)
  26. self.app.plotcanvas.mpl_connect('key_press_event', self.on_key_press)
  27. def run(self):
  28. self.toggle()
  29. def on_click(self, event):
  30. if self.point1 is None:
  31. self.point1 = (event.xdata, event.ydata)
  32. else:
  33. self.point2 = copy(self.point1)
  34. self.point1 = (event.xdata, event.ydata)
  35. self.on_move(event)
  36. def on_key_press(self, event):
  37. if event.key == 'r':
  38. self.toggle()
  39. def toggle(self):
  40. if self.isVisible():
  41. self.setVisible(False)
  42. self.app.plotcanvas.mpl_disconnect(self.move_subscription)
  43. self.app.plotcanvas.mpl_disconnect(self.click_subscription)
  44. else:
  45. self.setVisible(True)
  46. self.move_subscription = self.app.plotcanvas.mpl_connect('motion_notify_event', self.on_move)
  47. self.click_subscription = self.app.plotcanvas.mpl_connect('button_press_event', self.on_click)
  48. def on_move(self, event):
  49. if self.point1 is None:
  50. self.label.setText("Click on a reference point...")
  51. else:
  52. try:
  53. dx = event.xdata - self.point1[0]
  54. dy = event.ydata - self.point1[1]
  55. d = sqrt(dx**2 + dy**2)
  56. self.label.setText("D = %.4f D(x) = %.4f D(y) = %.4f" % (d, dx, dy))
  57. except TypeError:
  58. pass
  59. if self.update is not None:
  60. self.update()