c – QTreeView中某些索引的自定义文本颜色

前端之家收集整理的这篇文章主要介绍了c – QTreeView中某些索引的自定义文本颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用自定义颜色(取决于与每行相关的数据)在QTreeView小部件的其中一列中绘制文本.我试图重载drawRow()受保护的方法,并像这样更改样式选项参数(一个精简的示例):
  1. virtual void drawRow(QPainter* p_painter,const QStyleOptionViewItem& option,const QModelIndex& index) const
  2. {
  3. QStyleOptionViewItem optionCustom = option;
  4. if (index.column() == 2)
  5. {
  6. optionCustom.palette.setColor(QPalette::Text,Qt::red);
  7. }
  8. QTreeView::drawRow(p_painter,optionCustom,index);
  9. }

但显然我错过了一些东西,因为这似乎不起作用(我试图改变QPalette :: WindowText颜色角色).

解决方法

在您的模型中,扩展data()函数以返回给定颜色作为Qt :: ForegroundRole角色.

例如:

  1. virtual QVariant MyModel::data( const QModelIndex &index,int role ) const
  2. {
  3. if ( index.isValid() && role == Qt::ForegroundRole )
  4. {
  5. if ( index.column() == 2 )
  6. {
  7. return QVariant( QColor( Qt::red ) );
  8. }
  9. return QVariant( QColor( Qt::black ) );
  10. }
  11.  
  12. return QAbstractItemModel::data( index,role );
  13. }

猜你在找的C&C++相关文章