我的自定义表格模型源自 QAbstractTableModel
,然后显示在 QTableView
中。
看起来像这样:
我想更改某些行标题的文本颜色,这可以在模型中决定。是否可以从那里为某些标题着色?到目前为止我找不到办法。我发现的是为所有标题设置背景/文本颜色,而不是为少数特殊标题设置背景/文本颜色。颜色应该是用户的一种标记。
最佳答案
您需要做的是重新实现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();
}
关于c++ - QTableView/自定义表格模型 : set text color in header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748460/