【问题标题】:QTableView/custom table model: set text color in headerQTableView/自定义表格模型:在标题中设置文本颜色
【发布时间】:2012-10-05 14:29:25
【问题描述】:
我的自定义表格模型源自QAbstractTableModel,然后显示在QTableView 中。
看起来像这样:
我想更改某些行标题的文本颜色,这可以在模型中决定。是否可以从那里为某些标题着色?到目前为止我找不到方法。我发现的是关于为所有标题设置背景/文本颜色,而不是为特别少的部分设置背景/文本颜色。颜色应该是用户的一种标记。
【问题讨论】:
标签:
c++
colors
qtableview
qabstracttablemodel
【解决方案1】:
你要做的是重新实现QAbstractTableModel::headerData()。
根据部分的值(从零开始的标题索引),您可以单独设置标题项的样式。
Qt::ItemDataRole 中前景(=文本颜色)和背景的相关值为 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();
}