[PyQt] Shouldn't an item view keep a reference to its associated model?

Florent Rougon f.rougon at free.fr
Fri Jul 20 01:37:33 BST 2007


I had a hard time figuring out why my QAbstractItemModel subclass wasn't
working properly. I added debug statements everywhere, which showed that
my subclass was behaving fine. The only symptoms were:

  1. The associated QTreeView() had an empty display.

  2. My model was only queried for the columnCount() of the root item
     (twice) and for part of the headerData(), and that's all. No
     rowCount(), no index(), no data(), nothing.

I reduced the problem to a minimal example, and eventually found that it
was caused by the model (subclass of QAbstractItemModel) falling off the
scope, and therefore presumably gargabe-collected by Python. If I keep
an explicit reference to the model, everything works fine.

My question is: is this behavior normal?

I mean, I have something like:

  return view

followed by:

  view = [...]

so that the view is surely not garbage-collected when the app is
running. It seems to me that 'view.setModel(model)' should have added a
reference from 'view' to 'model', so that 'model' doesn't get
garbage-collected either.

But clearly, this isn't the case, because everything works fine as long
as I keep an explicit reference to 'model' when running app.exec_().

To make this clear, I'm attaching my minimal example. There you'll find
the following function:

def test():
    model = FooBarModel(files)
    view = QtGui.QTreeView()

    return view, model

If my main() function calls:

  view, model = test()

then everything works fine, because we keep a reference to the model as
long as app.exec_() runs.

But if I change this line into:

  view = test()[0]

then everything fails in a very hard-to-debug way, the reason being
presumably that the model is garbage-collected by Python during the
exection of app.exec_().

The tools I'm using are:

  * Python 2.4.4 (#2, Apr  5 2007, 20:11:18) 
    [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
    (from Debian etch)

  * Qt 4.2.1
     (from Debian etch; version 4.2.1-2+etch1 of the qt4 packages)

  * PyQt 4.2
    (from Debian unstable; python-qt4 packages version 4.2-1 backported
    by myself)

Thanks in advance for your comments.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: minimaltreemodel.py
Type: text/x-python
Size: 3475 bytes
Desc: Minimal example
Url : http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20070720/7e01e834/minimaltreemodel.py
-------------- next part --------------


More information about the PyQt mailing list