Maybe you are confused because you are thinking that a QAbstractItemModel of a tree is like the usual computer science implementation of a tree: that there is an actual node that represents the root of the tree, and that node holds pointers to the top level items in the tree, and so forth.To get the index value of a top level item, I need to send the row and column of the item and the index value of the item's parent (which technically is the root) to the index function.
In a Qt tree model, there is no root node. It is an imaginary, null QModelIndex, such that the parent of any topmost node in the tree is QModelIndex(). If you call QModelIndex::parent() for any top-level QModelIndex, you get QModelIndex(), for which QModelIndex::isValid() returns false.
If you ask the model for QAbstractItemModel::rowCount() (with no argument; that is, the default argument QModelIndex()), the correct return value is the number of top-level items. columnCount() for the root should return 0.
When calling QAbstractItemModel::index() for a top-level item in the tree, you pass a null QModelIndex(). For all other levels of the tree, you pass the result of parent() for that item.
Remember that QAbstractItemModel really is an abstraction of a tree. There is nothing behind it, and you have to derive from it and wrap the interface around your own data structure. That's one of the reasons why the createIndex() protected method takes a quintptr as its last argument - you can use that to pass a pointer to the item in your internal data structure represented by the index in the Qt tree. You can retrieve that pointer using QModelIndex::internalId() and use it to go back to the appropriate entry in your internal data.
Then you probably haven't implemented setData() correctly (or you are calling it incorrectly). setData() takes a QModelIndex that points to the actual item you want to change, not the parent of that item. If you do pass a null QModelIndex, the setData() should correctly return false because that would mean you are trying to change the imaginary root of the tree. However, if you pass a valid QModelIndex, and that index's parent is null, that's fine - it just means you are trying to change a top-level item.If I send QModelIndex() as the parent, the setData() function sees the value as invalid and simply returns a false.
Maybe give a bit more detail about the shape of your tree - what underlying data structure are you trying to represent?Yes, I have pored over those examples extensively and perhaps due to blindness, didn’t see a solution to my particular situation.
Bookmarks