QStandardItemModel中设置项目的背景颜色
如何根据内容显示不同的背景颜色?
参照ECMWF的Metview源码实现。
Qt的Model中不同类型的数据用role区分,Qt的宏ItemDataRole提供了一些角色:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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
};
|
也可以自定义角色,只要数值大于UserRole即可。
1
2
3
4
5
6
|
enum ImageNavigtionModelRole{
CachedImageRole = Qt::UserRole + 100,
ImageMetaDataRole = Qt::UserRole +200
};
|
Qt的Model使用data函数、setData函数来获取和设置各种角色的具体数值。当我们需要修改背景颜色时,可以修改BackgroundColorRole角色的返回数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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);
}
|
这样就可以自定义数据的背景色。
posted on 2015-09-04 10:12 alleyonine 阅读(3978) 评论(0) 编辑 收藏 举报