我想使用自定义颜色(取决于与每行相关的数据)在QTreeView小部件的其中一列中绘制文本.我试图重载drawRow()受保护的方法,并像这样更改样式选项参数(一个精简的示例):
- virtual void drawRow(QPainter* p_painter,const QStyleOptionViewItem& option,const QModelIndex& index) const
- {
- QStyleOptionViewItem optionCustom = option;
- if (index.column() == 2)
- {
- optionCustom.palette.setColor(QPalette::Text,Qt::red);
- }
- QTreeView::drawRow(p_painter,optionCustom,index);
- }
但显然我错过了一些东西,因为这似乎不起作用(我试图改变QPalette :: WindowText颜色角色).
解决方法
在您的模型中,扩展data()函数以返回给定颜色作为Qt :: ForegroundRole角色.
例如:
- virtual QVariant MyModel::data( const QModelIndex &index,int role ) const
- {
- if ( index.isValid() && role == Qt::ForegroundRole )
- {
- if ( index.column() == 2 )
- {
- return QVariant( QColor( Qt::red ) );
- }
- return QVariant( QColor( Qt::black ) );
- }
- return QAbstractItemModel::data( index,role );
- }