【问题标题】:QTableView set the color of a specific rowQTableView 设置特定行的颜色
【发布时间】:2016-11-09 14:11:46
【问题描述】:

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

我有一个使用模型的 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();
}

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

【问题讨论】:

  • 您是否以某种方式限制了从模型中请求的角色?代码是否真的到达了语句并且它不会画红?或者你从来没有收到BackgroundColorRole这个角色的请求?
  • 我测试过,我总是收到对该角色的请求。我对标志有限制,不能选择或编辑,但我不认为这是问题所在。
  • 另外,如果我使用 return QVariant(QColor(Qt::red));在角色检查之外,我在每个单元格中收到一个红色小方块和旁边的数字,仅此而已。

标签: c++ qt


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2012-04-30
    • 1970-01-01
    • 2014-06-20
    • 2013-10-01
    • 2015-12-28
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多