spacepaste

  1.  
  2. import sys
  3. from PyQt5.QtWidgets import QItemDelegate, QTreeWidget, QVBoxLayout, QLineEdit,\
  4. QMainWindow, QWidget, QTreeWidgetItem, QApplication
  5. from PyQt5.QtCore import QRegExp, Qt
  6. from PyQt5.QtGui import QRegExpValidator, QValidator
  7. class MyValidator(QValidator):
  8. def __init__(self, siblings, parent):
  9. super(MyValidator,self).__init__(parent)
  10. self.siblings = siblings
  11. def validate(self, s, pos):
  12. # look for invalid chars
  13. reg=QRegExp('[A-z0-9\[\]_-]+')
  14. regvd=QRegExpValidator(reg)
  15. regvd_rec=regvd.validate(s,pos)[0]
  16. print('regexp validate result:',regvd_rec)
  17. # check name conflicts
  18. if s in self.siblings:
  19. siblingvd_rec=0
  20. else:
  21. current_len=len(s)
  22. sub_strings=[sii[:current_len] for sii in self.siblings]
  23. if s in sub_strings:
  24. siblingvd_rec=1
  25. else:
  26. siblingvd_rec=2
  27. print('siblings validate result:',siblingvd_rec)
  28. if regvd_rec*siblingvd_rec==0:
  29. print('Invalid')
  30. return (QValidator.Invalid, s, pos)
  31. elif regvd_rec+siblingvd_rec==4:
  32. print('Acceptable')
  33. return (QValidator.Acceptable, s, pos)
  34. else:
  35. print('Intermediate')
  36. return (QValidator.Intermediate, s, pos)
  37. def fixup(self, s):
  38. pass
  39. class TreeWidgetDelegate(QItemDelegate):
  40. def __init__(self, siblings, parent=None):
  41. QItemDelegate.__init__(self, parent=parent)
  42. self.siblings=siblings
  43. self.parent=parent
  44. def createEditor(self, parent, option, index):
  45. editor = QLineEdit(parent)
  46. vd=MyValidator(self.siblings,self.parent)
  47. editor.setValidator(vd)
  48. return editor
  49. class MainWindow(QMainWindow):
  50. def __init__(self):
  51. super(self.__class__, self).__init__()
  52. frame=QWidget()
  53. self.setCentralWidget(frame)
  54. hl=QVBoxLayout()
  55. frame.setLayout(hl)
  56. self.tree=QTreeWidget(self)
  57. hl.addWidget(self.tree)
  58. # add treewidgetitems
  59. for ii in range(5):
  60. item=QTreeWidgetItem([str(ii)*3,])
  61. self.tree.addTopLevelItem(item)
  62. self.tree.itemDoubleClicked.connect(self.rename)
  63. self.show()
  64. def getSiblings(self,item):
  65. siblings=[self.tree.topLevelItem(ii).data(0,0) for ii in \
  66. range(self.tree.topLevelItemCount())]
  67. item_text=item.data(0,0)
  68. if item_text in siblings:
  69. siblings.remove(item_text)
  70. return siblings
  71. def rename(self):
  72. item=self.tree.selectedItems()
  73. if item:
  74. item=item[0]
  75. item.setFlags(item.flags() | Qt.ItemIsEditable)
  76. self.tree.scrollToItem(item)
  77. dele=TreeWidgetDelegate(self.getSiblings(item),self)
  78. self.tree.setItemDelegate(dele)
  79. self.tree.editItem(item)
  80. if __name__ == "__main__":
  81. app = QApplication(sys.argv)
  82. form = MainWindow()
  83. form.show()
  84. sys.exit(app.exec_())
  85.