PDA

View Full Version : Adding Icons to QTreeView-QAbstractItemModel



chithara
28th September 2018, 04:34
Hi,

I am using QTreeView model derived from QAbstractItemModel. I am following "SimpleTreeModelExample" provided by Qt. I have two columns with parent/child hierarchy. I want to add Icon (one for each Parent, one for each child).. But i don't know how to add Icon as part of TreeItem and how to modify the Model ::data function with respect to decoration role. Please help me with some example code

d_stranz
28th September 2018, 21:34
First, your data() method has to know whether the icon is being requested for a child or a parent. You can test that by determining whether QModelIndex::parent() returns a valid QModelIndex. If it does it's a child node, if not, it's a parent node.

Then, you check to see if the role being passed in the data() method is Qt::DecorationRole. If it is, then you check to see if QModelIndex::column() is zero. If it is, then you return a QVariant containing the QIcon instance for either the parent or the child node, whichever you determined in the first step.

If every parent has the same icon, and every child has the same icon (but different from the parent), you can simply store two QIcon instances as member variables in your abstract item model class, load them from resources when the model is created, and simply return a QVariant contain the right QIcon. If you have a lot of different icons, then you may need to store the correct one with every item in your model.

There is a simple example in the second answer here (https://forum.qt.io/topic/17176/how-to-display-icons-in-qtableview-via-a-custom-qabstractitemmodel).

Note that you do not use QTreeWidgetItem if you have constructed your own QAbstractItemModel class and are using QTreeView to display it. QTreeWidgetItem is a special class used only with QTreeWidget, and represents an item in the internal custom model used by the widget.

chithara
24th October 2018, 10:33
Thank you very much for the detailed explanation:)