[PySide] Problem with garbage collection

David Ching dc at dcsoft.com
Thu Feb 9 22:55:05 CET 2023


>from: "henry.wede at yahoo.com" <henry.wede at yahoo.com>

Henry> it seems like the clear method of the listwidget was the problem.?
Here is what I tried.
[...]
 The objects are ~just~ created from XML.  When I display those items using
the ListWidget .addItem() method they display correctly.? But only the first
time!? If I clear the list and display the same objects in the same list a
second time then I get the error. So it seems that the addItem method "takes
control" of the object in the Python list and the clear() method destroys
the internal object - even though I can print the objects in the Python list
so they seem to still exist. They are like zombies without a C++ soul :) 
[...]
Lastly, I eliminated the trouble-causing clear() method completely and now
"remove" the list items manually like this:
for N in range( ListWidget.count(), -1, -1): 
    Whatever = ListWidget.takeItem(N) 
I don't feel very professional doing it this way, but it seems to be
working.

The C++ code for QListWidget::clear() is as follows.  

 1: // NOTE:  QListWidget::clear() calls QListModel::clear()
 2: void QListModel::clear()
 3: {
 4:     beginResetModel();
 5:     for (int i = 0; i < items.count(); ++i) {
 6:         if (items.at(i)) {
 7:             items.at(i)->d->theid = -1;
 8:             items.at(i)->view = nullptr;
 9:             delete items.at(i); 
10:         }
11:     }
12:     items.clear();
13:     endResetModel();
14: }


So yes, on line 9, the QListWidgetItem C++ object is deleted (so it's
"soul") is indeed destroyed!  This is printed in red at
https://doc.qt.io/qt-6/qlistwidget.html#items:  "Warning: All items will be
permanently deleted."

Why do you need to access the QListWidgetItem after you clear it from the
list?  Perhaps you should create new QListWidgetItem's and call
QListWidget.addItem() for those new instances instead.  

Or just use QListWidget.takeItem() as you have done.  Nothing wrong with
that.  

I have also found QListWidgetItem.setHidden() to be great as it lets me keep
the item in the list but the user has no knowledge.

Good luck,
David 






More information about the PySide mailing list