1

I'm trying to use QStandardItemModel to represent a hierarchy of data, but when I'm adding QStandardItems to the model, I have to assign them in object member variables, or the objects seems to be deleted.

For example

self.tree_model = QStandardItemModel()
self.tree_model.setHorizontalHeaderLabels(['Category'])
self.out_insertions = QStandardItem("Insertions")
self.tree_model.invisibleRootItem().appendRow(self.out_insertions)

Works as expected (an "Insertion" row is inserted under the column "Category"). But if I remove the self.out_insertion assignment, like:

self.tree_model = QStandardItemModel()
self.tree_model.setHorizontalHeaderLabels(['Category'])
self.tree_model.invisibleRootItem().appendRow(QStandardItem("Insertions"))

It doesn't work (an empty row is shown).

I'm using Qt 4.6.3 and PySide 0.4.1. Can someone explain me why this happens?

Thanks in advance

~Aki

AkiRoss
  • 11,745
  • 6
  • 59
  • 86

1 Answers1

4

Your object get garbage collected since no more (Python) references to it exist.

This behavior is described in the 'things to be aware of' in the PyQt documentation.

Most of these problems (in PyQt land) can be avoided by correct parenting (which makes Qt take ownership instead of PyQt).

ChristopheD
  • 112,638
  • 29
  • 165
  • 179
  • It means that QStandardItemModel doesn't keep internal references to items?!? This sounds pretty odd... – AkiRoss Nov 01 '10 at 20:47
  • Well, I thought about that issue anyway, probably it's a matter of deallocation/destruction... That explains why using local variables instead of object variables would not solve. Anyway what I just find odd is that objects shall be referenced inside StandardItemModel and thus not destroyed... But why? – AkiRoss Nov 01 '10 at 22:15
  • it is explained quite well in the "things to be aware of" link above. basically its a side effect of following the pyqt method of doing bindings rather than a more pythonic view - which hopefully pyside will implement in a future release. In the meantime - just make sure the thing you create is associated with a more persistent higher level entity. (like a parent window) – Neon22 Jan 14 '11 at 16:58