PDA

View Full Version : How to Change QTreeView highlight color



jshafferman
5th May 2011, 15:46
I am curious if there is a way to change the default blue highlight color for a QTreeView item, when a particular situation occurs. For instance if you make a QTreeView from data contained in say a QHash, based on a value in the QHash you want the highlight color to be green instead of blue.

How would you do this?

Thanks for any help!

high_flyer
6th May 2011, 10:08
I am not aware of a convenience method for that, but I am not that heavy user of model/view.
Generally speaking you should override the delegate paint() method, and insert the specific logic you want for : option.state & QStyle::State_Selected

MarekR22
6th May 2011, 13:00
Threre is easy way:
QWidgte::palette-prop and QPalette, QPalette::ColorRole-enum == QPalette::Highlight.

high_flyer
6th May 2011, 14:29
And how you would use set palette in this case?

MarekR22
6th May 2011, 14:39
A sorry, I didn't notice that he wants different colors for different nodes of tree (my fault).
So he have to deliver own delegate like you said.

anyway it still quite simple. Subclass QStyledItemDelegate and override paint method like that:

void QStyledItemDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
if (index.data(someRole).toInt()==1 && option.state.testFlag(QStyle::State_Selected)) {
QStyleOptionViewItem newOption(option);
newOption.palette.setBrush(QPalette::Normal, QPalette::Highlight , someOtherBrush);
QStyledItemDelegate::paint(painter, newOption, index);
return;
}
QStyledItemDelegate::paint(painter, option, index);
}

jshafferman
6th May 2011, 18:13
This might have went over my head a little bit but I think I see what you are both saying...

So if I currently have each tree item as class TreeItem where a private variable contains the data (as mentioned a QHash/QList/QVector...). Then those items are added to the tree model class called TreeModel which is a sub-class of AbstractItemModel.

Your saying to sub-class QStyledItemDelegate... would that be the TreeItem or TreeModel? My guess is TreeItem because that seems to make more sense to me but I see where you say index.data which leads me to believe your talking about the AbstractItemModel.

Just in case your curious the TreeModel class is then attached to QTreeView with QTreeView::setModel(TreeModel).

I hope I am making myself clear but if you need anything else please let me know and thanks for any suggestions!