QStandardItemModel中设置项目的背景颜色
如何根据内容显示不同的背景颜色?
参照ECMWF的Metview源码实现。
Qt的Model中不同类型的数据用role区分,Qt的宏ItemDataRole提供了一些角色:
[cpp]
enum ItemDataRole {
DisplayRole = 0,
DecorationRole = 1,
EditRole = 2,
ToolTipRole = 3,
StatusTipRole = 4,
WhatsThisRole = 5,
// Metadata
FontRole = 6,
TextAlignmentRole = 7,
BackgroundColorRole = 8,
BackgroundRole = 8,
TextColorRole = 9,
ForegroundRole = 9,
CheckStateRole = 10,
// Accessibility
AccessibleTextRole = 11,
AccessibleDescriptionRole = 12,
// More general purpose
SizeHintRole = 13,
InitialSortOrderRole = 14,
// Internal UiLib roles. Start worrying when public roles go that high.
DisplayPropertyRole = 27,
DecorationPropertyRole = 28,
ToolTipPropertyRole = 29,
StatusTipPropertyRole = 30,
WhatsThisPropertyRole = 31,
// Reserved
UserRole = 32
};
[/cpp]
也可以自定义角色,只要数值大于UserRole即可。
[cpp]
enum ImageNavigtionModelRole{
CachedImageRole = Qt::UserRole + 100,
ImageMetaDataRole = Qt::UserRole +200
};
[/cpp]
Qt的Model使用data函数、setData函数来获取和设置各种角色的具体数值。当我们需要修改背景颜色时,可以修改BackgroundColorRole角色的返回数据:
[cpp]
QVariant ImageNavigationModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::BackgroundRole)
{
QStandardItem* node = itemFromIndex(index.sibling(index.row(),0)); // 每行颜色均相同
QVariant cached_image_role = node->data(CachedImageRole);
if(!cached_image_role.isNull())
{
if(index.row()%2 == 0)
return QColor(“#FFE6BF”);
else
return QColor(“#FFF2DE”);
}
else
{
return QStandardItemModel::data(index, role);
}
}
return QStandardItemModel::data(index, role);
}
[/cpp]
这样就可以自定义数据的背景色。