Custom class objects in a tree
24se7en last edited by
Im very new to Qt and having trouble getting my head around some of the concepts.
What I have is an abstract class (Foo) that I would like to keep in a tree structure, much like the Object tree in Designer. I would like the tree view to display two properties of Foo, the Name and Type. I would like this to work with internal drag and drop.
I see two approaches:
- I add a parent and children pointers to my Foo class and use that to populate a QTreeWidget
- I make use of the QTreeView and implement QAbstractItemModel.
Option 1 feels comfortable but wasteful, so I started on option 2. Using the Editable Tree Model Example I quickly ran into problems.
Firstly I have two columns that I want to see in the tree, Name and Type, but these values are driven from Foo. So I wanted each TreeItem to hold an instance of Foo that it would query for the Name and Type columns. I did this by adding a third column to hold a pointer to a Foo instance (also added Q_DECLARE_METATYPE to Foo so QVariant would work).
Then I changed the data method in TreeModel to switch on the index.column and query the TreeItem via a getter i.e. getName and removed the data method in TreeItem and added the getters for name and type.
At this point it seemed to work but as soon as I tried to implement internal drag and drop I realised that this isn't going to 'just work'. The instance of Foo inside the TreeItem is lost during the insert/remove row dance.
Am I going about this the right way? Is adding a third column the only way to add an arbitrary class object to my tree nodes? Should I merge the concept of TreeItem and Foo? How would I do that when Foo is abstract?
Any help being pointed in the right direction to solve this (especially the Qt way) would be appreciated.