Search code examples
qtstylesheetselecteditemqtreewidget

Change text color of a specific column for QTreeView


I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected.

QTreeView::item:selected {color: red}

I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.


Solution

  • You can use a delegate for that:

    class MyDelegate : public QStyledItemDelegate {
    public:
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
            if (option.state & QStyle::State_Selected) {
                QStyleOptionViewItem optCopy = option;
                optCopy.palette.setColor(QPalette::Foreground, Qt::red);
            }
            QStyledItemDelegate::paint(painter, optCopy, index);
        }
    }
    
    myTreeWidget->setItemDelegateForColumn(0, new MyDelegate);