问题
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
回答1:
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).
来源:https://stackoverflow.com/questions/4071740/objects-seems-to-be-deleted-if-not-assigned-to-object-variable-in-pyside