Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dynamic color for a selected QTreeViewItem?



  • Hi,
    I'm struggling to keep the color of the items of my Treeview when they are getting selected.
    I've set a color with the data role Qt::ForegroundRole.
    The color is displayed right. it is staying when I hover the item BUT it is changing to white when the item is selected....
    The only way I managed to change the color is using the following stylesheet:

    QListView::item:selected,
    QListView::item:selected:active,
    QTreeView::item:selected,
    QTreeView::item:selected:active{
        border: 1px solid #4286F5;
        background-color: #dfedfa;
        color: black;
    }
    

    The problem is that I don't want all my items black. Some should keep a different color.

    I'm using a delegate where I've overridden initStyleOption and even there if I force the option.palette to be the color I want it doesn't affect the text color when selected...

    Idem if I do this in the paint method... (I've tried what was suggested here)

    Any idea how I could do it?



  • @mbruel said in Dynamic color for a selected QTreeViewItem?:

    I'm using a delegate where I've overridden initStyleOption and even there if I force the option.palette to be the color I want it doesn't affect the text color when selected...

    Hi,

    Which ColorRole do you use when setting palette color ? It should work using QPalette::HighlightedText

    QStyleOptionViewItem ViewOption(option);
    ViewOption.palette.setColor(QPalette::HighlightedText, desiredColor);
    

    I took this code from here: https://stackoverflow.com/questions/19362443/qtreeview-selection-clears-text-color



  • Well I thought I tried...
    Then I was overriding the whole QPalette with the constructor with 9 QBrush...
    I've just test your code and it works if I remove any color from the stylesheet on QTreeView:item
    Thanks a lot!

    Here is my code:

    void TreeItemDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
    {
        QStyledItemDelegate::initStyleOption(option, index);
        option->textElideMode = Qt::ElideNone;
    
        TreeItem *item = static_cast<const TreeModel*>(index.model())->itemFromIndex(index);
    
        if (item)
        {
            QColor color = item->data(Qt::ForegroundRole).value<QColor>();
            option->palette.setColor(QPalette::WindowText, color);
            option->palette.setColor(QPalette::HighlightedText, color);
    
            if (item->isLargeItem())
            {
                option->font.setBold(true);
                option->decorationSize = QSize(24,24);
            }
            if (item->isReadOnly() )
                option->font.setItalic(true);
        }
    }
    

Log in to reply