How to get QModelIndex of children in QML TreeView
-
Hi,
I have a QML TreeView which shows a QStandardItemModel. The QStandardItemModel has different files on the first level, and each file can have several calculations as children. The view displays this like this
- file 1
- calculation 1
- calculation 2
- file 2
-file 3- calculation 1
but for files and calculations, I use different delegates (using a Loader). In order to set the selection of an ItemSelectionModel assigned to the TreeView, I do the following:
treeView.selection.clearSelection() treeView.selection.select(myList.index(model.index,0),2)
This works perfectly for my file delegate, but in the calculation delegate, for some reason myList.index(model.index,0) seems not to work. A console.log of the Index gives QModelIndex(). I wonder whether this is because the calculations are child items of the files?
But more precisely: How do I get the QModelIndex() of the calculation entries in my view?
- file 1
-
@maxwell31 Hi,
Probably you need to give the parent to get the index of a child from
index()
method:treeView.selection.select(myList.index(model.index,0, indexOfParent),2)
It's working with file delegate because their parents is the root, and it's like if they have no parents.
-
@maxwell31 That's a good question. I never used TreeView...
I would say you can use QModelIndex::parent(). But it seems it's not callable from QML.
treeView.selection.select(myList.index(model.index, 0, model.index.parent()), 2)
Why do you need to make this selection ? is it coming from user ?
-
@maxwell31 I don't know about
model.index
. But according to itemDelegate documentation: styleData.index - the QModelIndex of the current item in the modelYou can also retrieve the row and column index using styleData.row and styleData.column