QTreeView中某些索引的自定义文本颜色 [英] Custom text color for certain indexes in QTreeView

查看:1097
本文介绍了QTreeView中某些索引的自定义文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义颜色(取决于与每行相关的数据)在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 角色返回给定的颜色。 / p>

例如:

  virtual QVariant MyModel :: data(const QModelIndex & index,int role)const 
{
if(index.isValid()&&&&& ()== 2)
{
return QVariant(QColor(Qt :: red));
}
return QVariant(QColor(Qt :: black));
}

return QAbstractItemModel :: data(index,role);
}


I would like to draw texts in one of the columns in a QTreeView widget using a custom color (depending on the data related to each row). I tried to overload the drawRow() protected method and change the style option parameter like this (a stripped-down example):

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);
 }

But obviously I am missing something because this does not seem to work (I tried to change also the QPalette::WindowText color role).

解决方案

In your model, extend the data() function to return a given color as the Qt::ForegroundRole role.

For example:

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 );
}

这篇关于QTreeView中某些索引的自定义文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆