在模型/视图配置中使用时如何更改 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()