lib.py 1.9 KB

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