c++ - QTableView/自定义表格模型 : set text color in header

标签 c++ colors qtableview qabstracttablemodel

我的自定义表格模型源自 QAbstractTableModel,然后显示在 QTableView 中。

看起来像这样:

enter image description here

我想更改某些行标题的文本颜色,这可以在模型中决定。是否可以从那里为某些标题着色?到目前为止我找不到办法。我发现的是为所有标题设置背景/文本颜色,而不是为少数特殊标题设置背景/文本颜色。颜色应该是用户的一种标记。

最佳答案

您需要做的是重新实现QAbstractTableModel::headerData()。 根据部分的值(标题索引从零开始),您可以单独设置标题项的样式。 Qt::ItemDataRole 中前景(=文本颜色)和背景的相关值是 Qt::BackgroundRoleQt::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/

相关文章:

c++ - 检查二维井字数组位置 C++

ios - 我的 iOS 应用程序如何为一系列颜色设置动画?

Extjs 4 : how to change progressbar colour dynamically?

python - pyqt打印预览QTableView

c++ - 加载带有 362 项目的解决方案后,Win XP 上的 VS2005 SP1 崩溃,没有任何错误、日志或跟踪

c++ - include 语句中的斜线是什么意思?

javascript - 单击更改 Iris 颜色选择器值

c++ - QTableView - 添加命名行

python - QListView 中自定义 IndexWidget 的平滑延迟加载和卸载

c++ - 将一系列分数的 n 次方相加并求和 - C++