Reputation: 1103
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.
Upvotes: 2
Views: 2618
Reputation: 1103
So this is how I solved it.
class MyDelegate : public QStyledItemDelegate {
public:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
QString text_highlight;
if (index.column() == 0)){
text_highlight = BLUE;
} else{
text_highlight = RED;
}
QStyleOptionViewItem s = *qstyleoption_cast<const QStyleOptionViewItem*>(&option);
s.palette.setColor(QPalette::HighlightedText, QColor(text_highlight));
QStyledItemDelegate::paint(painter, s, index);
}
}
Upvotes: 1
Reputation: 11513
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);
Upvotes: 4