C++ QTableView设置特定行的颜色
我知道论坛上和这里有很多关于这个问题的讨论,但我找不到解决这个问题的有效方法 我有一个使用模型的QTableView。我需要能够通过模型更改某些特定行的背景颜色,更准确地说,是通过C++ QTableView设置特定行的颜色,c++,qt,C++,Qt,我知道论坛上和这里有很多关于这个问题的讨论,但我找不到解决这个问题的有效方法 我有一个使用模型的QTableView。我需要能够通过模型更改某些特定行的背景颜色,更准确地说,是通过data函数 QVariant CCustomModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { c
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));
}
您是否以某种方式限制了将从模型请求的角色?代码是否真的到达了语句,并且它不会变成红色?或者你从来没有收到过角色的请求吗
BackgroundColorRole
?我测试过,我总是收到该角色的请求。我只限制标志不可选择或编辑,但我不认为这是问题所在;在角色检查之外,我在每个单元格中收到一个小红方块和旁边的数字,但就是它。