How to NOT change text color of selected QTreeWidgetItem
-
I am using QTreeWidget. Each QTreeWidgetItem in this QTreeWidget has its own status, I wanted to display this status by adding to all items second column with symbol ⬤, and after that, just change the text color for this column for particular element, when its status will change. But in my QTreeWidget, items are selectable. When QTreeWidgetItem is selected, it changes background color as specified in my stylesheet:
QTreeWidget::item:selected { background-color: red; }
. But this is also changing the text color of the selected item. This seems strange because by default selected items changes only it's background color, but when you provide background-color with stylesheet it also changes text color.Is it possible to leave the text color unchanged in this situation?
-
@Beatler said in How to NOT change text color of selected QTreeWidgetItem:
QTreeWidget::item:selected
QTreeWidget::item:selected, QTreeWidget::item:selected:active, QTreeWidget::item:selected:!active {
border:none;
background-color:rgba(255,255,255,0);
color:rgba(10,10,255,0);
} -
This is a "feature" of the default delegate. It's easily solved:
just add this classclass HighlightTextDelegate : public QStyledItemDelegate{ Q_OBJECT #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) Q_DISABLE_COPY_MOVE(HighlightTextDelegate) #else Q_DISABLE_COPY(HighlightTextDelegate) #endif public: using QStyledItemDelegate::QStyledItemDelegate; protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { QStyledItemDelegate::initStyleOption(option, index); const QVariant foregroundData = index.data(Qt::ForegroundRole); if (foregroundData.canConvert<QBrush>()) option->palette.setBrush(QPalette::HighlightedText, qvariant_cast<QBrush>(foregroundData)); } };
then call
treeWidget->setItemDelegate(new HighlightTextDelegate(treeWidget));