[PyQt] Bug in QTableView.setModel()

Phil Thompson phil at riverbankcomputing.co.uk
Tue Jan 8 09:23:48 GMT 2008

On Tuesday 08 January 2008, Aaron Digulla wrote:
> Quoting Aaron Digulla <digulla at hepe.com>:
> >>> I'm talking about preventing the python class which is used as the
> >>> model being garbage collected; it doesn't matter from which Qt class it
> >>> is derived.
> >>>
> >>> As it is, the class pointer is copied into the view class and then
> >>> python frees the memory. That causes spurious display errors and
> >>> crashes. No matter how you look at it, that's a bug.
> >>
> >> No its not, the view doesn't take ownership of the model, neither in Qt
> >> C++ nor in PyQt, thats why your object is garbage collected. A reason
> >> for not taking ownership is that a model might be used in multiple
> >> views.
> >
> > Incrementing the usage count != ownership. I'm the one who decides
> > which object in my project "owns" the model. This is a design issue.
> Here is another case which argues against you:
> I have a QTextEdit which uses several QTestDocument's (so one view has
> several models, depending on what is selected in the UI). There is one
> use case where I have no model (ie. the selected element just doesn't
> have any text attached).
> So what I did was:
>      if scene is None:
>          edit.setDocument(QTextDocument())
>          edit.setEnabled(False)
>          return
> and guess what: I got spurious crashes because the object returned by
> QTextDocument() is GC'd. Where am I supposed to store this model? It's
> not related to *any* object in my project. It's just a dummy so the
> user doesn't accidentally edit the last selected text.

So the fix is...


...to give ownership (and responsibility for calling the C++ dtor) to "edit".

Note that not doing this in C++ is also a bug - but results in a memory leak 
rather than a crash.

> So all in all, I can't agree to your argumentation. Please fix these
> bugs. Is there an issue tracker somewhere where can I add these issues?

The bug is in your code.


More information about the PyQt mailing list