根据项目的文本本身更改项目的前景色

Change foreground color of items based on the item's text itself

我有一个包含 5 列的 QTreeView,我为其中的 2 列(第 1 列和第 2 列)设置了一个 QComboBox 委托。他们都有相同的代表,并且他们必须有相同的下拉列表。假设列表始终为:["Next", "Stop"]。 到目前为止一切顺利:代表工作完美。

现在的问题是:我希望第 1 列和第 2 列的项目根据文本本身以不同颜色显示文本。例如:如果文本是“Next”,文本的颜色应该是绿色,如果文本是“Stop”,那么颜色应该是红色。

经过一番搜索,我决定使用委托来设置颜色。我找到了不同的解决方案,但唯一对我有用的解决方案是这个(参见 paint() 函数):

class ComboBoxDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter, option, index):
        painter.save()
        text = index.data(Qt.DisplayRole)
        if text == 'Next':
            color = GREEN
        elif text == 'Stop':
            color = RED
        else:
            color = BLACK
        painter.setPen(QPen(color))
        painter.drawText(option.rect, Qt.AlignLeft | Qt.AlignVCenter, text)
        painter.restore()


    def createEditor(self, parent, option, index):
        editor = QtWidgets.QComboBox(parent)
        editor.currentIndexChanged.connect(self.commitEditor)
        return editor

    # @QtCore.Slot
    def commitEditor(self):
        editor = self.sender()
        self.commitData.emit(editor)
        if isinstance(self.parent(), QtWidgets.QAbstractItemView):
            self.parent().updateEditorGeometries()
        self.closeEditor.emit(editor)

    def setEditorData(self, editor, index):
        try:
            values = index.data(QtCore.Qt.UserRole + 100)
            val = index.data(QtCore.Qt.UserRole + 101).strip('<>')
            editor.clear()
            for i, x in enumerate(values):
                editor.addItem(x, x)
                if val == x:
                    editor.setCurrentIndex(i)
        except (TypeError, AttributeError):
            LOG.warning(f"No values in drop-down list for item at row: {index.row()} and column: {index.column()}")

    def setModelData(self, editor, model, index):
        values = index.data(QtCore.Qt.UserRole + 100)
        if values:
            ix = editor.currentIndex()
            model.setData(index, values[ix], QtCore.Qt.UserRole + 101)
            model.setData(index, values[ix], QtCore.Qt.DisplayRole)

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

如下图所示,选择和悬停无法正常工作:

我做错了什么?

最小可重现示例(记得导入 ComboBoxDelegate):

import sys

from PySide2.QtGui import QStandardItemModel, QStandardItem
from PySide2.QtWidgets import QTreeView, QApplication, QMainWindow

from combo_box_delegate import ComboBoxDelegate

COLUMN_HEADER_LIST = ["0", "1", "2", "3", "4"]


class MyTreeView(QTreeView):
    def __init__(self):
        super(MyTreeView, self).__init__()
        self.model = QStandardItemModel()
        self.root = self.model.invisibleRootItem()
        self.setModel(self.model)
        delegate = ComboBoxDelegate(self)
        self.setItemDelegateForColumn(1, delegate)
        self.setItemDelegateForColumn(2, delegate)
        self.data = {
            "a": {
                "b": {
                    "c": ["Next", "Stop", "1", "Hello World!"],
                    "d": ["Next", "Stop", "2", "Hello World!"],
                    "e": ["Next", "Stop", "3", "Hello World!"],
                    "f": ["Next", "Stop", "4", "Hello World!"]
                }
            }
        }
        self.populate_tree(self.root, self.data)
        self._format_columns()

    def populate_tree(self, parent, data):
        for key, value in data.items():
            if isinstance(value, dict):
                child = QStandardItem(key)
                parent.appendRow(child)
                self.populate_tree(child, data[key])
            elif isinstance(value, list):
                items = [QStandardItem(key)] + [QStandardItem(str(val)) for val in value]
                parent.appendRow(items)

    def _format_columns(self):
        self.model.setHorizontalHeaderLabels(COLUMN_HEADER_LIST)
        self.expandAll()


class Main(QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        tree = MyTreeView()
        self.setCentralWidget(tree)
        self.setMinimumWidth(600)
        self.setMinimumHeight(400)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = Main()
    main_window.show()
    app.exec_()

您注意到的奇怪选择问题可能是因为设置了当前选择。

先设置根模型索引,再设置当前索引。 然后设置回树当前项。

大致如下所述(未测试。还要注意语法。)

yourComboBox.setRootModelIndex(yourTree.currentIndex())
yourComboBox.setCurrentIndex(index)
yourTree.setCurrentItem(yourTree.invisibleRootItem(),0)

物品的绘制比较特殊,一般不建议重写paint()方法,建议在initStyleOption()方法中修改QStyleOptionViewItem的属性,用于绘画,例如更改 QPalette:

from PySide2.QtCore import Qt
from PySide2.QtGui import QBrush, QColor, QPalette
from PySide2.QtWidgets import QAbstractItemView, QComboBox, QStyledItemDelegate

RED = "red"
BLACK = "black"
GREEN = "green"


class ComboBoxDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        text = index.data(Qt.DisplayRole)
        if text == "Next":
            color = GREEN
        elif text == "Stop":
            color = RED
        else:
            color = BLACK
        option.palette.setBrush(QPalette.Text, QBrush(QColor(color)))

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        editor.currentIndexChanged.connect(self.commitEditor)
        return editor

    # @QtCore.Slot
    def commitEditor(self):
        editor = self.sender()
        self.commitData.emit(editor)
        if isinstance(self.parent(), QAbstractItemView):
            self.parent().updateEditorGeometries()
        self.closeEditor.emit(editor)

    def setEditorData(self, editor, index):
        try:
            values = index.data(Qt.UserRole + 100)
            val = index.data(Qt.UserRole + 101).strip("<>")
            editor.clear()
            for i, x in enumerate(values):
                editor.addItem(x, x)
                if val == x:
                    editor.setCurrentIndex(i)
        except (TypeError, AttributeError):
            pass
            # LOG.warning(f"No values in drop-down list for item at row: {index.row()} and column: {index.column()}")

    def setModelData(self, editor, model, index):
        values = index.data(Qt.UserRole + 100)
        if values:
            ix = editor.currentIndex()
            model.setData(index, values[ix], QtCore.Qt.UserRole + 101)
            model.setData(index, values[ix], QtCore.Qt.DisplayRole)

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)