Custom text color for certain indexes in QTreeView

落花浮王杯 提交于 2019-12-04 23:20:33

问题


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).


回答1:


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


来源:https://stackoverflow.com/questions/1397484/custom-text-color-for-certain-indexes-in-qtreeview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!