Iterate QTreeView and set different icons


#1

Hi all, I need some guidance.

I have created a Gui where it populates a list of items, akin to the Outliner.
Currently I am trying to append the icons towards the ‘different row(s)’ within the tree hierarchy (based on the nodetype of the fullpath), but not sure how I should do it.

The way I had constructed my hierarchy is by splitting up the object’s fullpath. While I can get the fullpath from the Gui is by performing an actual selection (index_selection())
And so, my question would be, is there a way that I can initialize the icon before the Gui shows up?

class MyModel(QtGui.QStandardItemModel):
    def __init__(self, parent=None):
        super(MyModel, self).__init__(parent)
        self.get_contents()


    def get_contents(self):
        self.clear()
        
        # Derive from a function but returns a list of objects' full path
        contents = [
             '|Base|character|Mike|body',
             '|Base|character|John',
             '|Base|camera'
         ]

        icon_dir = "/user_data/icons"
        base_icon = "base_icon.png"
        char_icon = "char_icon.png"
        cam_icon = "cam_icon.png"

        for content in contents:
            parent = self.invisibleRootItem()
            content = "{0}".format(content)
            for word in content.split("|")[1:]:
                child_items = [parent.child(i) for i in range(parent.rowCount())]
                for item in child_items:
                    if item.text() == word:
                        it = item
                        break
                else:
                    it = QtGui.QStandardItem(word)
                    # tried appending icon here but it sets the same icon towards all items
                    # it.setIcon(temp_icon)
                    parent.setChild(parent.rowCount(), it)
                parent = it


class TreeHierarchy(QtGui.QWidget):
    def __init__(self, parent=None):
        super(TreeHierarchy, self).__init__(parent)
        self._setup_ui()

    def _setup_ui(self):
        self.tree_view = QtGui.QTreeView()
        model = MyModel()
        self.tree_view.setModel(model)
        self.tree_view.header().hide()
        self.tree_view.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.tree_view.expandAll()
        self.tree_view.selectionModel().selectionChanged.connect(
            self.index_selection
        )
        self.tree_view.show()


    def index_selection(self):
        # Get current selection in Tree View...
        for sel in self.tree_view.selectedIndexes():
            val = "|" + sel.data()
            while sel.parent().isValid():
                sel = sel.parent()
                val = "|"+ sel.data()+ val
            print(val)

#2

Wondering if anyone here have any insights towards this?