student
student

Reputation: 380

QTableView set the color of a specific row

I know there are plenty of discussion on forums and here about this subject but I could not find a working solution for this problem.

I have a QTableView that uses a model. I need to be able to change the background color of some specific rows through the model, more precisely from the data function.

QVariant CCustomModel::data(const QModelIndex &index, int role) const
{
  if (role == Qt::DisplayRole)
  {

    switch (index.column())
    {
      case colName:         return QVariant(QString::number(1));
      case colAdress:       return QVariant(QString::number(2));
      case colGender:       return QVariant(QString::number(3));
      case colTelephone:    return QVariant(QString::number(4));
      default:
        return QVariant();
    }
  }

  if(role == Qt::BackgroundColorRole)  //also tried Qt::BackgroundRole and Qt::ForegroundRole
  {
    return QVariant(QColor(Qt::red));
  }
  return QVariant();
}

This is simple not working. The numbers are displayed but the background color is still the basic one. Is there any possible solution here?

Upvotes: 2

Views: 1597

Answers (1)

m. c.
m. c.

Reputation: 895

Try this:

  if(role == Qt::BackgroundRole) 
  {
      return QBrush(QColor(Qt::red));
  }

Upvotes: 1

Related Questions