I did the following for textcolor
changes in what is essentially QSqlTableModel
, sub classed to CustomSqlTableModel
to allow for overriding setData()
and submit, and also to add a custom refresh function. The following should work just the same for QAbstractItemModel
instances:
QVariant ExampleSqlTableModel::data(const QModelIndex &idx, int role) const
{
if (role == Qt::ForegroundRole)
{
QColor color;
// Only the display names need to be coloured.
if(idx.column() == 1)
{
int value = CustomSqlTableModel::data(1, Qt::DisplayRole).toInt();
switch(value)
{
case 0: color = QColor(Qt::yellow); break;
case 1: // same as 2
case 2: color = QColor(Qt::blue); break;
case 3: color = QColor(Qt::green); break;
case 4: // same as 5
case 5: color = QColor(Qt::red); break;
default: color = QColor(Qt::black); break;
}
}
return QVariant(color);
}
return CustomSqlTableModel::data(idx,role);
}
I would also advise being a bit more specific with your widgets. Subclass all the QTableView
instances that you do want your stylesheet
to affect, and don't apply a general stylesheet
to QTableView
if it is going to affect the text color.
That way, if all other QTableViews
have been sub classed to be myAwesomeTableView
, then you could replace your stylesheet
content to be:
myAwesomeTableView::item
{
padding-left:10px;
height:40px;
width:80px;
color: #5a5a5a;
border-bottom :1px solid #f0f0f0;
}
If you always want the other QTableView
to have red text, rather define a second subclass, and handle it via stylesheet
instead of implementing it in code like I did. I needed different rows to have different text colors on a single column based on the value in that column. To do it via stylesheet
, make another QTableView
subclass, for argument, myOtherAwesomeTableView
, and implement stylesheet
as follows:
myOtherAwesomeTableView::item
{
padding-left:10px;
height:40px;
width:80px;
color: #ff0000;
border-bottom :1px solid #f0f0f0;
}
Let me know if this helps you...