[PyQt] Bug in QTableView.setModel()

Aaron Digulla digulla at hepe.com
Tue Jan 8 08:03:55 GMT 2008

Quoting Andreas Pakulat <apaku at gmx.de>:

>> 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.

That the table doesn't say "please don't GC this because I still need  
it" has nothing to do with ownership. It's a usage counter bug.

Proof: If N tables access the model, the usage count will be N. As  
every table is GC'd, the usage count drops. When the last table is  
GC'd, the usage count will be 0 and the model will be GC'd, too. So  
there is no reason why a table must not increment the usage count.

But there are plenty of reasons why it should:

1. In Python, I expect all any every object to manage the ownership of  
anything I store in it. If it needs it beyond the time of the call  
where it sees the object for the first time, it must increment and  
decrement the usage counter accordingly. See  

2. This bug doesn't produce deterministic errors. That makes it hard  
to locate and leads to the developer thinking "PyQt is unreliable" (in  
addition to the many wasted hours trying to find the bug).

3. It's simple to fix: In setModel(), you just have to check if there  
already is an old model. If so, check if it's a python object and  
decrement its usage count if it is. Then save the new pointer and  
increment its usage count if it's a python object.

4. The fix doesn't break anything.


Aaron "Optimizer" Digulla a.k.a. Philmann Dark
"It's not the universe that's limited, it's our imagination.
Follow me and I'll show you something beyond the limits."

More information about the PyQt mailing list