我发现了一种通过委托来做这件事的方法。下面是代码
class TextColorDelegate: public QItemDelegate
{
public:
explicit TextColorDelegate(QObject* parent = 0) : QItemDelegate(parent)
{ }
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QStyleOptionViewItem ViewOption(option);
QColor itemForegroundColor = index.data(Qt::ForegroundRole).value<QColor>();
if (itemForegroundColor.isValid())
{
if (itemForegroundColor != option.palette.color(QPalette::WindowText))
ViewOption.palette.setColor(QPalette::HighlightedText, itemForegroundColor);
}
QItemDelegate::paint(painter, ViewOption, index);
}
};
而对于使用委托,你应该写这样的事情
pTable->setItemDelegate(new TextColorDelegate(this));
其中pTable
的类型是QTableView*
;
实际上,这会随时更改突出显示的文本颜色,但我需要在更改特定行的文本颜色时进行更改。 – nabroyan