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

Phil Thompson phil at riverbankcomputing.co.uk
Fri Jul 20 11:34:54 BST 2007


On Friday 20 July 2007 11:17 am, Giovanni Bajo wrote:
> 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.

No, in C++ you would have a memory leak but your code would still work.

Phil


More information about the PyQt mailing list