lib.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from math import sqrt
  2. import os.path as osp
  3. from numpy.linalg import norm
  4. import numpy as np
  5. from qtpy import QtCore
  6. from qtpy import QtGui
  7. from qtpy import QtWidgets
  8. here = osp.dirname(osp.abspath(__file__))
  9. def newIcon(icon):
  10. icons_dir = osp.join(here, 'icons')
  11. return QtGui.QIcon(osp.join(':/', icons_dir, '%s.png' % icon))
  12. def newButton(text, icon=None, slot=None):
  13. b = QtWidgets.QPushButton(text)
  14. if icon is not None:
  15. b.setIcon(newIcon(icon))
  16. if slot is not None:
  17. b.clicked.connect(slot)
  18. return b
  19. def newAction(parent, text, slot=None, shortcut=None, icon=None,
  20. tip=None, checkable=False, enabled=True):
  21. """Create a new action and assign callbacks, shortcuts, etc."""
  22. a = QtWidgets.QAction(text, parent)
  23. if icon is not None:
  24. a.setIcon(newIcon(icon))
  25. if shortcut is not None:
  26. if isinstance(shortcut, (list, tuple)):
  27. a.setShortcuts(shortcut)
  28. else:
  29. a.setShortcut(shortcut)
  30. if tip is not None:
  31. a.setToolTip(tip)
  32. a.setStatusTip(tip)
  33. if slot is not None:
  34. a.triggered.connect(slot)
  35. if checkable:
  36. a.setCheckable(True)
  37. a.setEnabled(enabled)
  38. return a
  39. def addActions(widget, actions):
  40. for action in actions:
  41. if action is None:
  42. widget.addSeparator()
  43. elif isinstance(action, QtWidgets.QMenu):
  44. widget.addMenu(action)
  45. else:
  46. widget.addAction(action)
  47. def labelValidator():
  48. return QtGui.QRegExpValidator(QtCore.QRegExp(r'^[^ \t].+'), None)
  49. class struct(object):
  50. def __init__(self, **kwargs):
  51. self.__dict__.update(kwargs)
  52. def distance(p):
  53. return sqrt(p.x() * p.x() + p.y() * p.y())
  54. def distancetoline(point, line):
  55. p1, p2 = line
  56. p1 = np.array([p1.x(), p1.y()])
  57. p2 = np.array([p2.x(), p2.y()])
  58. p3 = np.array([point.x(), point.y()])
  59. if np.dot((p3 - p1), (p2 - p1)) < 0:
  60. return norm(p3 - p1)
  61. if np.dot((p3 - p2), (p1 - p2)) < 0:
  62. return norm(p3 - p2)
  63. return norm(np.cross(p2 - p1, p1 - p3)) / norm(p2 - p1)
  64. def fmtShortcut(text):
  65. mod, key = text.split('+', 1)
  66. return '<b>%s</b>+<b>%s</b>' % (mod, key)