[PyKDE] Model indexes and internal pointers

David Boddie david at boddie.org.uk
Wed Jul 19 12:57:14 BST 2006


On Wednesday 19 July 2006 10:52, Jeremy Sanders wrote:
> On Wed, 19 Jul 2006, David Boddie wrote:
> 
> > Probably, but there's not much you can do if you attach Python objects
> > to temporary C++ objects and pass them back to Qt. If you just prevent
> > them from being collected, there's the chance that they'll become
> > unrecoverable. Maybe the handling of QPersistentModelIndex needs to be
> > looked at more closely.
> 
> I ran into this issue when trying to write a bridging tree layer to 
> convert from the tree in my python code to the treemodel for the treeview. 
> These bridging objects would get collected. It's very hard to do this with 
> the current code.

That's exactly the sort of situation I was afraid of! You passed objects
that describe an aspect of your model's underlying structure into C++
without keeping references to them. The tree view could just throw them
away, and you would never see those objects again!

I do understand your problem, though. These mapping problems do tend
to occur when you are trying to expose an existing tree structure to
views, and this is especially the case with XML models. You want to
create temporary mappings between model indexes and DOM nodes (for
example), but you need to keep those objects around to satisfy the
view, meaning that you end up creating a duplicate tree structure
whose sole purpose is to map between indexes and your original tree.

You can't delete any part of this duplicate tree because you don't
know if any of the mapping objects are secretly being referenced
by the view, and generating new ones almost invariably ends up
confusing the tree view because they aren't identical to the old
ones. (The internal pointers are different.)

> In the end I directly connected the model indexes to my internal python 
> structure. I used a weakref.WeakValueDictionary() to map the model index 
> IDs to my internal objects.

This is the trick that most people end up using. It's the "correct" one,
but it doesn't mean that it's particularly satisfying. :-(

David




More information about the PyQt mailing list