[PyQt] Reference leak in QListView.setModel?

dfragi daelfin at gmail.com
Wed Sep 10 17:59:04 BST 2008


Hello,
While trying to get rid of a memory leak in my program, I 
tracked it down to this:

##########################################################
# 
# import sys, gc
# from PyQt4.Qt import *
# 
# class MyModel(QAbstractListModel):
#     def rowCount(self, parent):
#         return 5
#     
#     def data(self, index, role):
#         if role == Qt.DisplayRole:
#             return QVariant(str(index.row()))
#         else:
#             return QVariant()
# 
# def main():
#     app = QApplication(sys.argv)
#     
#     model = MyModel()
# 
#     lv = QListView()
#     print gc.get_referrers(model)
#     lv.setModel(model)
#     print gc.get_referrers(model)
#     QApplication.processEvents()
#     print gc.get_referrers(model)
#     lv.setModel(None)
#     print gc.get_referrers(model)    
#     lv.show()
# 
#     app.exec_()
# 
# if __name__ == '__main__':
#     main()
##########################################################

This outputs the following:

[<frame object at 0x8c7bd0>]
[<frame object at 0x8c7bd0>]
[<frame object at 0x8c7bd0>, 
 <bound method MyModel.rowCount of <__main__.MyModel object at 0xd8f1e0>>,
 <bound method MyModel.data of <__main__.MyModel object at 0xd8f1e0>>]
[<frame object at 0x8c7bd0>, 
 <bound method MyModel.rowCount of <__main__.MyModel object at 0xd8f1e0>>,
 <bound method MyModel.data of <__main__.MyModel object at 0xd8f1e0>>]

i.e. after setModel(), the model isn't referenced anywhere else other
than the current frame (the local name 'model'), which is ok. But after
QApplication.processEvents, references to the bound methods rowCount() 
and data() are being kept by PyQt, and not released even after the
model is released. This keeps the model from being garbage-collected.

Is this a bug or should I be doing something differently?

Thanks a lot, 
--D.



More information about the PyQt mailing list