unique_label_qlist_widget.py 1.4 KB
Newer Older
1 2
# -*- encoding: utf-8 -*-

3
from PyQt5.QtCore import Qt, QSize
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from PyQt5 import QtWidgets


class EscapableQListWidget(QtWidgets.QListWidget):
    def keyPressEvent(self, event):
        super(EscapableQListWidget, self).keyPressEvent(event)
        if event.key() == Qt.Key_Escape:
            self.clearSelection()


class UniqueLabelQListWidget(EscapableQListWidget):
    def mousePressEvent(self, event):
        super(UniqueLabelQListWidget, self).mousePressEvent(event)
        if not self.indexAt(event.pos()).isValid():
            self.clearSelection()

20
    def findItemsByLabel(self, label, get_row=False):
21 22 23 24 25
        items = []
        for row in range(self.count()):
            item = self.item(row)
            if item.data(Qt.UserRole) == label:
                items.append(item)
26 27
                if get_row:
                    return row
28 29 30 31 32 33 34 35 36 37
        return items

    def createItemFromLabel(self, label):
        item = QtWidgets.QListWidgetItem()
        item.setData(Qt.UserRole, label)
        return item

    def setItemLabel(self, item, label, color=None):
        qlabel = QtWidgets.QLabel()
        if color is None:
38
            qlabel.setText(f"{label}")
39
        else:
40
            qlabel.setText('<font color="#{:02x}{:02x}{:02x}">●</font> {} '.format(*color, label))
41 42
        qlabel.setAlignment(Qt.AlignBottom)

43 44
        # item.setSizeHint(qlabel.sizeHint())
        item.setSizeHint(QSize(25, 25))
45 46

        self.setItemWidget(item, qlabel)