如果只是需要简直的改变如QTableView的Item显示的文字的颜色, 可以继承自QStandardItem, 然后修改data返回的角色的值.
#ifndef COLORITEM_H
#define COLORITEM_H
#include <QStandardItem>
#include <QString>
class ColorItem : public QStandardItem {
public:
ColorItem(const QString & text = "", const QString & coloredText = "否");
~ColorItem();
virtual QVariant data(int role = Qt::UserRole + 1) const;
private:
QString coloredText;
};
#endif // COLORITEM_H
#include "ColorItem.h"
#include <qDebug>
ColorItem::ColorItem(const QString & text, const QString & coloredText)
: QStandardItem(text) {
this->coloredText = coloredText;
}
ColorItem::~ColorItem() {
//qDebug() << "Destruct Color Item";
}
QVariant ColorItem::data(int role) const {
if (role == Qt::ForegroundRole) {
if (QStandardItem::data(Qt::DisplayRole) == coloredText) {
return QColor(Qt::red);
}
}
return QStandardItem::data(role);
}