0

在模型/视图配置中使用时如何更改 QStandardItem 的文本颜色。似乎它总是会显示为黑色测试。

下面是一个将“Hello World”显示为黑色文本的可执行示例代码。我正在尝试将其更改为绿色文本。

我也试过用_component.setForeground(QColor(0,255,0))

import sys
import string
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class ComponentItem(QStandardItem):
    """docstring for ComponentItem"""
    def __init__(self, text, role=Qt.DisplayRole):
        super(ComponentItem, self).__init__()
        self.component = text
        self.role = role

    def data(self, role=Qt.DisplayRole):
        if role != self.role:
            return QVariant()
        if role == Qt.DisplayRole:
            return QVariant(self.component)
        if role == Qt.ForegroundRole:
            return QColor(0,255,0)
        return QVariant()

class ComponentModel(QStandardItemModel):
    """docstring for ComponentModel"""
    def __init__(self, parent=None):
        super(ComponentModel, self).__init__()
        self.parent = parent

        _component = ComponentItem("Hello World")  #How do I change Text Color?
        _component.setData(QColor(255,0,0), Qt.ForegroundRole) #Does not work

        self.appendRow([_component])

class ComponentTree(QTreeView):
    """docstring for ComponentTree"""
    def __init__(self, parent=None):
        super(ComponentTree, self).__init__()
        self.parent = parent

        self.setModel(ComponentModel(self))

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()

        _tree = ComponentTree()

        vBox = QVBoxLayout()
        vBox.addWidget(_tree)

        self.setLayout(vBox)
        self.show()

def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
4

1 回答 1

2

问题是由以下几行引起的:

if role != self.role:
    return QVariant()
...

因为 if roleis Qt.ForegroundRoleand self.roleis Qt.DisplayRolethenQVariant()被返回并且你想要的句子不会被执行。

我不明白维护文本和角色的原因。我认为不需要覆盖data().

所以解决方案如下:

class ComponentItem(QStandardItem):
    def __init__(self, text, role=Qt.DisplayRole):
        super(ComponentItem, self).__init__()
        self.setData(text, role)

在此处输入图像描述


当我测试您的代码时,另一个无声错误已发布,并带有以下警告:

QObject::startTimer: QTimer can only be used with threads started with QThread
QObject::startTimer: QTimer can only be used with threads started with QThread

该警告是因为您没有将父级传递给模型,因此没有正确删除内存,解决方案如下:

class ComponentModel(QStandardItemModel):
    def __init__(self, parent=None):
        super(ComponentModel, self).__init__(parent)

        _component = ComponentItem("Hello World")  #How do I change Text Color?
        _component.setData(QColor(255,0,0), Qt.ForegroundRole) #Does not work
        self.appendRow([_component])
于 2018-07-25T04:57:49.260 回答