Problem with selection in TreeView Qt6
-
I'm trying to implement a TreeView in which i want to highlight the selected row.
The model is a c++ implemented QAbstractItemModel which is set to the qml context from the main.cppHere is the main.qml
import QtQuick import QtQuick.Controls Window { id: mainWin visible: true width: 640 height: 480 title: qsTr("QML Test") TreeView { id: treeView anchors.fill: parent model: projectModel selectionModel: ItemSelectionModel { model: treeView.model } delegate: TreeViewDelegate { id: treeDelegate required property bool selected required property int row background: Rectangle { opacity: treeDelegate.selected ? 1 : 0 color: "red" } onClicked: { treeView.selectionModel.select(treeView.modelIndex(treeDelegate.row, 0), ItemSelectionModel.Toggle | ItemSelectionModel.Rows) console.log("clicked:", treeView.model.data(treeView.modelIndex(treeDelegate.row, 0))) console.log("Selection model selected? ", treeView.selectionModel.isSelected(treeView.modelIndex(treeDelegate.row, 0))) console.log("Delegate selected? ", treeDelegate.selected) } } }
this is how the model is shown by the TreeView, which is ok
If i click on Parent1 it get selected properly and it becomes red
If i click on Parent2, the item Child1 is higlighed in red instead
The log present in the onClicked slot show this:qml: clicked: Parent2 qml: Selection model selected? true qml: Delegate selected? false
So it seems the the proper item is actully retrived by the model, and the selection model should properly use it, BUT the selected property is set to the wrong delegate, to the Child1 delegate instead that to the Parent2 one.
I guess it's somehow reletaed to the fact that Child1 is in row=1 in the view and Parent2 has also row=1 in the QModelIndex; infact if i hide the child1 the selection of parent2 works, but how can i fix this? -
@bee65 Thanks for the asnwer.
the selection model seem to work properly. in fact the log of clicked item state is always coherent:onClicked: { ... console.log("Selection model selected? ", treeView.selectionModel.isSelected(treeView.modelIndex(treeDelegate.row, 0))) }
i get true on the first click (when it's selected) and false on the second (when is toggled). This is always correct, no matter if it's on a child or parent item or if expand/reduce the tree in between clicks. It seems selection model is doing its job.
What is wrong is how the selected state of the delegate is syncronized (not sure by who). I'm not sure but i think that it's the TreeViewDelegate that should properly transalte the model QModelIndex into "view" row but it consider the QModel indx as a "linear" table index (as you point that out).
Anyway, how can i fix this? -
you can record the currentIndex int model and the currentViewIndex in view, and when you click the item and expand or collapse the item in treeview, converts index in the view to the index in the model