Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Creating Custom Model for QTreeView
travistrue08 last edited by
I've been wanting to develop a nice GUI for my simple 3D game engine for placing various types of entities. Right now, I have a Transform hierarchy in which all of my scene's objects are listed. It's essentially my Transform that has its own list of children Transform pointers like so:
My Scene class contains the root transform, and all subsequent transforms are children of it, or a child down that hierarchy. I'd like to represent my scene's hierarchy in a QTreeView using a model to keep my engine's native Transform's hierarchy in sync with Qt's QTreeView. I'd like to list each Transform by name (just text) where the user is able to drag transforms around in the hierarchy to change formation. It'll also make sure that I'm not trying to add a parent to one of its children (my code currently guards against that). I think the way I need to go about it is either by creating a custom subclass of QAbstractItemModel, or using QStringListModel. Am I on the right track? I'm still pretty new to Qt!
EDIT: Technically, the top-level of my QTreeView will be my Scene as I can have multiple scenes open at once, and then everything that's a child under that are Transforms which can also their their own set of children. This would be similar to how IDEs will have multiple projects in their workspace/solution tree view, and then they'd have multiple folders/files below that. That said, my Scenes can't be moved underneath other Scenes. They're just always top-level.
Jan-Willem last edited by
A QStringListModel can't be used for a QTreeView. If you want to use a model out of the box, use a QStandardItemModel.
But since your project is game related, you probably want to use an QAbstractItemModel, which (according to the documentation) gives better performance and flexibility.
Perhaps you should take a look at the Simple Tree Model Example and after that the Editable Tree Model Example. When I started with models, I at first adjusted the examples to suite my needs. But working through the examples from scratch, will give you more insight. Both examples make use of the QAbstractItemModel, which can be used for a QTreeView.
Just bear in mind that these examples teach you about working with models, they are not perfect solutions.
I hope this helps.
minbraz last edited by
you should subclass QAbstractItemModel. I wrote a very basic program, that shows how (transformation) objects can be managed and showed in QTreeView. The source code: "is here":https://www.dropbox.com/s/0vwop6ke6fgrpok/2014-08-06_qt_1.zip
p.s. I am learning Qt as well, so my solution is not necessary the optimal one.