I have a QTreeView
with items from my own model (QAbstractItemModel
derived). Now I would like to style the items (with a stylesheet on the QTreeView
) so that depending on various properties they would have various backgrounds.
Also it seems that this problem applies to any Model/View containers. Not just QTreeView
.
For example doing alternate backgrounds is easy. alternatingRowColors
on the QTreeView
has to be true
. Then in stylesheet you may use :alternate
pseudo-selector to change properties for the alternate items so:
QTreeView::item {
background: green;
}
QTreeView::item:alternate {
background: blue;
}
Doing selected items is similarly simple. In fact doing anything that is handled by Qt's pseudo-selectors is easy.
But what about properties that are not pseudo-selectors? In particular how to select style based on values associated with ItemDataRole
(which seams to be the only reasonably generic method of storing data in models)?
Note that there is a trick. If for example you do not use checked state you might "reuse" that state to map to something of your own and then you have a pseudo-selector for it... But this is just a workaround and not even a general one.
With QTreeWidget
it seems you can go by having a dedicated QWidget
-derived class for the items where you would add Q_PROPERTY
with whatever you want. Then you can access that property by name in the stylesheet.
See for example "Using custom Q_PROPERTY with Stylesheet" question on Qt Centre and "Trigger an update for the widget while using dynamic properties." note at the end of Qt Style Sheets Examples.
But the *View
classes do not have any QWidget
s or even QObject
s for their items (or at least not public accessible ones).
There is also possibility to provide own QAbstractItemDelegate
, possibly one derived from QStyledItemDelegate
. But that makes stylesheet interaction a bit harder.
With simple staff like background-color
property it seems doable. But how would you simulate border-image
, padding
and many other styles in complex sets?
Not to mention that once you write an item delegate the code is frozen. If Qt
changes ways of rendering stylesheet (improves it somehow) you will not benefit from it... Also is makes logic/presentation separation a bit harder. Now you need a programmer to style those items, not just a CSS-enabled graphics-guy...
So is there any way to subclass in stylesheet based on model-provided properties/data?