pythonqtreeviewqstandarditempyside6

QTreeView StandardItem.insertRow(0, new_item) inserts itself instead of new_item?


I want to insert an new item to my treeview at row 0 of a child item. The code seemed pretty straight forward but I think I have run into a bug? I simplified the problem in order to avoid tons of unneeded code. Is there something I am doing wrong?

To be clear, if I call insertRow() on the StandardItemModel itself... it does work. Yet I need it to work on a sub item of the model.

QT version : 6.0.0 PySide version : 6.0.0 OS: Ubuntu 20.10 (KDE)

class MyTreeView(QTreeView):
    def __init__(self, parent):
        super().__init__(parent)
        model = MyModel()
        self.setModel(model)
    
class MyModel(QStandardItemModel):
    def __init__(self):
        super().__init__()
        self.root_item = self.invisibleRootItem()
        self.top_level = QStandardItem("Top level")
        self.root_item.appendRow(self.top_level)

        self.top_level.appendRow(QStandardItem('Appended item'))
        self.top_level.insertRow(0, QStandardItem('Inserted item'))

Now I would expect a result like:

    - Top level
      - Inserted item
      - Appended item

Yet the result I am getting is:

    - Top level
      - Top level
      - Appended item

Solution

  • It seems that when you insertRow() an item directly, it will go out of scope. The solution for this example would be to assign it to self first.

    I still assume this is a bug as appendRow() does mimic this behaviour.

    class MyTreeView(QTreeView):
        def __init__(self, parent):
            super().__init__(parent)
            model = MyModel()
            self.setModel(model)
        
    class MyModel(QStandardItemModel):
        def __init__(self):
            super().__init__()
            self.root_item = self.invisibleRootItem()
            self.top_level = QStandardItem("Top level")
            self.root_item.appendRow(self.top_level)
    
            self.top_level.appendRow(QStandardItem('Appended item'))
            # CHANGE START
            self.insert_item = QStandardItem('Inserted item')
            self.top_level.insertRow(0, self.insert_item)
            # CHANGE END