labelDialog.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #
  2. # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
  3. #
  4. # This file is part of Labelme.
  5. #
  6. # Labelme is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Labelme is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Labelme. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. try:
  20. from PyQt5.QtGui import *
  21. from PyQt5.QtCore import *
  22. from PyQt5.QtWidgets import *
  23. PYQT5 = True
  24. except ImportError:
  25. from PyQt4.QtGui import *
  26. from PyQt4.QtCore import *
  27. PYQT5 = False
  28. from .lib import newIcon, labelValidator
  29. # TODO:
  30. # - Calculate optimal position so as not to go out of screen area.
  31. BB = QDialogButtonBox
  32. class LabelDialog(QDialog):
  33. def __init__(self, text="Enter object label", parent=None):
  34. super(LabelDialog, self).__init__(parent)
  35. self.edit = QLineEdit()
  36. self.edit.setPlaceholderText(text)
  37. self.edit.setValidator(labelValidator())
  38. self.edit.editingFinished.connect(self.postProcess)
  39. layout = QVBoxLayout()
  40. layout.addWidget(self.edit)
  41. self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
  42. bb.button(BB.Ok).setIcon(newIcon('done'))
  43. bb.button(BB.Cancel).setIcon(newIcon('undo'))
  44. bb.accepted.connect(self.validate)
  45. bb.rejected.connect(self.reject)
  46. layout.addWidget(bb)
  47. self.setLayout(layout)
  48. def validate(self):
  49. if PYQT5:
  50. if self.edit.text().strip():
  51. self.accept()
  52. else:
  53. if self.edit.text().trimmed():
  54. self.accept()
  55. def postProcess(self):
  56. if PYQT5:
  57. self.edit.setText(self.edit.text().strip())
  58. else:
  59. self.edit.setText(self.edit.text().trimmed())
  60. def popUp(self, text='', move=True):
  61. self.edit.setText(text)
  62. self.edit.setSelection(0, len(text))
  63. self.edit.setFocus(Qt.PopupFocusReason)
  64. if move:
  65. self.move(QCursor.pos())
  66. return self.edit.text() if self.exec_() else None