我想使用自定义颜色(取决于与每行相关的数据)在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 ); }
原文地址:https://www.jb51.cc/c/111573.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。