unique_label_qlist_widget.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -*- encoding: utf-8 -*-
  2. from PyQt5.QtCore import Qt, QSize
  3. from PyQt5 import QtWidgets
  4. class EscapableQListWidget(QtWidgets.QListWidget):
  5. def keyPressEvent(self, event):
  6. super(EscapableQListWidget, self).keyPressEvent(event)
  7. if event.key() == Qt.Key_Escape:
  8. self.clearSelection()
  9. class UniqueLabelQListWidget(EscapableQListWidget):
  10. def mousePressEvent(self, event):
  11. super(UniqueLabelQListWidget, self).mousePressEvent(event)
  12. if not self.indexAt(event.pos()).isValid():
  13. self.clearSelection()
  14. def findItemsByLabel(self, label, get_row=False):
  15. items = []
  16. for row in range(self.count()):
  17. item = self.item(row)
  18. if item.data(Qt.UserRole) == label:
  19. items.append(item)
  20. if get_row:
  21. return row
  22. return items
  23. def createItemFromLabel(self, label):
  24. item = QtWidgets.QListWidgetItem()
  25. item.setData(Qt.UserRole, label)
  26. return item
  27. def setItemLabel(self, item, label, color=None):
  28. qlabel = QtWidgets.QLabel()
  29. if color is None:
  30. qlabel.setText(f"{label}")
  31. else:
  32. qlabel.setText('<font color="#{:02x}{:02x}{:02x}">●</font> {} '.format(*color, label))
  33. qlabel.setAlignment(Qt.AlignBottom)
  34. # item.setSizeHint(qlabel.sizeHint())
  35. item.setSizeHint(QSize(25, 25))
  36. self.setItemWidget(item, qlabel)