且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-14 16:19:52

在您的模型中,扩展 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 );
}