tags:

views:

68

answers:

1

I've a tree-like polymorphic data-structure, where the nodes are instances of class Node (implemented by me) or any its subclass. My application heavily uses Boost and the nodes are actually represented by boost::shared_ptr type rather than Node*.

Now, I want to create a QT model to wrap my tree data-structure. Therefore I need a way to associate any model index with a node in my internal data structure. And here comes the problem:

QT supports two ways of doing it:

First:

QModelIndex QAbstractItemModel::createIndex ( int row, int column, void * ptr = 0 ) const

Creates a model index for the given row and column with the internal pointer ptr.

And second:

QModelIndex QAbstractItemModel::createIndex ( int row, int column, quint32 id ) const

Creates a model index for the given row and column with the internal identifier, id.

Ok, and how exactly should I associate the node in my case? There is no possibility to associate a shared_ptr with the model index... Yes, I know, I can receive a raw pointer from my shared_ptr and supply it to CreateIndex(), but it smells bad - seems too unsafe to me.

Any ideas?

By the way, I feel that in general Boost / QT integration seems to be not trivial at least in the area of memory management.

10x a lot.

+1  A: 

If you want to do an easy association without passing a raw pointer, put the shared memory in a container and pass the ID value for that container element into the model index. For example, you could created declare

QMap< quint32, boost::shared_ptr< Foo > > index_map;

and use that. You'd have to be careful to not duplicate IDs for existing pointers, perhaps. It seems somewhat overly complicated to me....

You could also just keep a list of the pointers (to ensure continued availability as you need them) and then use the actual address of the pointer in the QModelIndex as well. This is probably what I would do.

Caleb Huitt - cjhuitt
Yes, I understand you. Both GUID-pointer maps and memory pools may be used to solve this specific problem. But both solutions seem to share the same problem - the look more like attempts to "hack" the problem, instead of properly solve it. If the above proposals are the "right" way of doing things with QT models, then I would say, that this is a real design problem in QT's model/view architecture.
Lev
@Lev: It might well be a design problem, but not one that I think would be very easy to resolve... how else would you suggest tracking *any* of the sorts of data people might want to put in trees? Also, you might want to look into what the Qt people are calling the "NG ModelView classes, and see if they are any better for you: http://qt.nokia.com/developer/learning/online/talks/developerdays2009/tech-talks/the-next-generation-qt-item-views
Caleb Huitt - cjhuitt