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

Giovanni Bajo rasky at develer.com
Fri Jul 20 11:17:44 BST 2007


On Fri, 20 Jul 2007 11:56:38 +0200, Florent Rougon <f.rougon at free.fr>
wrote:

> I thought it should be possible to have the views keep a reference to
> their model without "owning" it, as you say. For instance:
> 
>   view1.setModel(model)
> 
> internally would do 'view1.model = model'
> 
> and similarly,
> 
>   view2.setModel(model)
> 
> internally would do 'view2.model = model', so that 'model' cannot get
> garbage-collected as long as either 'view1' or 'view2' is alive.
> 
> What's wrong with this approach?

It is not what Qt does. PyQt doesn't play tricks with object lifetimes: it
exposes Qt's underlying object model.

In Qt, when you call setModel() the model owenrship isn't transferred to
the view. The model still has a separate lifetime, and you need to take
care of it, and explicitly delete the model when you don't need anymore;
or, as Phil suggested, make the model child of an object that takes its
ownership (such as: the view), so that it gets destroyed when the parent is
destroyed as well. So, having the setModel() call take an additional
reference to the model would break the orthogonality between Qt and PyQt.

Whatever problem you're facing, you would be having it in C++ as well. Try
and see how C++ programmers solve it, and do the same.
-- 
Giovanni Bajo



More information about the PyQt mailing list