【问题标题】:Custom text color for certain indexes in QTreeViewQTreeView 中某些索引的自定义文本颜色
【发布时间】:2009-09-09 04:10:54
【问题描述】:

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

【问题讨论】:

    标签: c++ qt qtreeview


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我不知道data() 方法也用于项目的外观。我使用自定义项目委托实现了我想要的,并重写了 paint() 方法,但使用 data() 方法更加优雅。
    • @VladoKlimovský 是的,但有些纯粹主义者认为不应该将其用于外观,因为他们希望将内容和外观分开处理(模型与委托)。
    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多