Custom text color for specific indexes in QTreeView

I would like to draw texts in one of the columns of the QTreeView widget using a custom color (depending on the data related to each row). I tried to overload the drawRow () method and change the style parameter parameter like this (trimmed 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 it does not work (I tried to change the color role QPalette::WindowText).

+5
source share
1 answer

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

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 );
}
+10
source

All Articles