PDA

View Full Version : Changing the background color of a cell in a QTableView



scarleton
30th June 2010, 04:20
I am trying to figure out how to change the background color of one cell, the changing of the actual text and changing the text alignment is also working correctly, but the background color isn't changing. Any thoughts?


QVariant FavoriteSqlModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);

if(index.column() == _statusIdx)
{
int status = value.toInt();

switch(role)
{
case Qt::DisplayRole:
if(value.isValid())
{
switch(status)
{
case 0:
return tr("");
case 1:
return tr("Uncopied");
case 2:
return tr("Modified");
case 3:
return tr("Copied");
}
}
break;
case Qt::TextAlignmentRole:
return Qt::AlignHCenter | Qt::AlignVCenter;
//case Qt::BackgroundColorRole:
case Qt::BackgroundRole:
switch(status)
{
case 0:
case 1:
// use the default
break;
case 2:
return QColor(Qt::yellow);
case 3:
return QColor(Qt::darkGreen);
}
break;
}
}

return value;
}

scarleton
30th June 2010, 13:23
I figured it out, when the role was the BackgroundRole, I was switching on the background color value, not on the actual value (Qt::DisplayRole). After the code gets into the Qt::BackgroundRole, I now do a int stateCode = QSqlQueryModel::data(index, Qt::DisplayRole).toInt(); and switch off that, it works GREAT!