【发布时间】: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));在角色检查之外,我在每个单元格中收到一个红色小方块和旁边的数字,仅此而已。