QTableView设置特定行的颜色

QTableView set the color of a specific row

本文关键字:颜色 设置 QTableView      更新时间:2023-10-16

我知道在论坛和这里有很多关于这个主题的讨论,但我找不到一个有效的解决方案。

我有一个使用模型的QTableView。我需要能够通过模型改变一些特定行的背景颜色,更精确地从data函数。

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();
}

这是简单的不工作。数字显示,但背景颜色仍然是基本的。这里有什么可能的解决方案吗?

试试这个:

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