lib.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # flake8: noqa
  2. #
  3. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  4. #
  5. # This file is part of Labelme.
  6. #
  7. # Labelme is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Labelme is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. from math import sqrt
  21. try:
  22. from PyQt5.QtGui import *
  23. from PyQt5.QtCore import *
  24. from PyQt5.QtWidgets import *
  25. except ImportError:
  26. from PyQt4.QtGui import *
  27. from PyQt4.QtCore import *
  28. def newIcon(icon):
  29. return QIcon(':/' + icon)
  30. def newButton(text, icon=None, slot=None):
  31. b = QPushButton(text)
  32. if icon is not None:
  33. b.setIcon(newIcon(icon))
  34. if slot is not None:
  35. b.clicked.connect(slot)
  36. return b
  37. def newAction(parent, text, slot=None, shortcut=None, icon=None,
  38. tip=None, checkable=False, enabled=True):
  39. """Create a new action and assign callbacks, shortcuts, etc."""
  40. a = QAction(text, parent)
  41. if icon is not None:
  42. a.setIcon(newIcon(icon))
  43. if shortcut is not None:
  44. if isinstance(shortcut, (list, tuple)):
  45. a.setShortcuts(shortcut)
  46. else:
  47. a.setShortcut(shortcut)
  48. if tip is not None:
  49. a.setToolTip(tip)
  50. a.setStatusTip(tip)
  51. if slot is not None:
  52. a.triggered.connect(slot)
  53. if checkable:
  54. a.setCheckable(True)
  55. a.setEnabled(enabled)
  56. return a
  57. def addActions(widget, actions):
  58. for action in actions:
  59. if action is None:
  60. widget.addSeparator()
  61. elif isinstance(action, QMenu):
  62. widget.addMenu(action)
  63. else:
  64. widget.addAction(action)
  65. def labelValidator():
  66. return QRegExpValidator(QRegExp(r'^[^ \t].+'), None)
  67. class struct(object):
  68. def __init__(self, **kwargs):
  69. self.__dict__.update(kwargs)
  70. def distance(p):
  71. return sqrt(p.x() * p.x() + p.y() * p.y())
  72. def fmtShortcut(text):
  73. mod, key = text.split('+', 1)
  74. return '<b>%s</b>+<b>%s</b>' % (mod, key)