C++ QTableView/自定义表格模型:设置标题中的文本颜色
我的自定义表格模型源自C++ QTableView/自定义表格模型:设置标题中的文本颜色,c++,colors,qtableview,qabstracttablemodel,C++,Colors,Qtableview,Qabstracttablemodel,我的自定义表格模型源自QAbstractTableModel,然后显示在QTableView中 看起来像这样: QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const { //make all odd horizontal header items black background with white text //for even ones just kee
QAbstractTableModel
,然后显示在QTableView
中
看起来像这样:
QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
//make all odd horizontal header items black background with white text
//for even ones just keep the default background and make text red
if (orientation == Qt::Horizontal) {
if (role == Qt::ForegroundRole) {
if (section % 2 == 0)
return Qt::red;
else
return Qt::white;
}
else if (role == Qt::BackgroundRole) {
if (section % 2 == 0)
return QVariant();
else
return Qt::black;
}
else if (...) {
...
// handle other roles e.g. Qt::DisplayRole
...
}
else {
//nothing special -> use default values
return QVariant();
}
}
else if (orientation == Qt::Vertical) {
...
// handle the vertical header items
...
}
return QVariant();
}
我想更改某些行标题的文本颜色,这可以在模型中确定。可以从那里给某些标题上色吗?到目前为止我找不到路。我发现的是为所有标题设置背景/文本颜色,而不是为少数特殊标题设置背景/文本颜色。颜色应该是用户的一种标记。您需要做的是重新实现
QAbstractTableModel::headerData()
。
根据节的值(标题索引从零开始),可以单独设置标题项的样式。
中前景(=文本颜色)和背景的相关值为Qt::BackgroundRole
和Qt::ForegrondRole
例如,像这样:
QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
//make all odd horizontal header items black background with white text
//for even ones just keep the default background and make text red
if (orientation == Qt::Horizontal) {
if (role == Qt::ForegroundRole) {
if (section % 2 == 0)
return Qt::red;
else
return Qt::white;
}
else if (role == Qt::BackgroundRole) {
if (section % 2 == 0)
return QVariant();
else
return Qt::black;
}
else if (...) {
...
// handle other roles e.g. Qt::DisplayRole
...
}
else {
//nothing special -> use default values
return QVariant();
}
}
else if (orientation == Qt::Vertical) {
...
// handle the vertical header items
...
}
return QVariant();
}