I have a treeview in the qml, the selection mode is ExtendedSelection. Whenever the selected index changes by the user I need to exactly know which tree rows are selected. Here is the TreeView:
Controls.TreeView {
id: myTreeView
Controls.TableViewColumn {
title: "Name"
role: "name"
}
headerVisible: false
anchors.fill: parent
selection: ItemSelectionModel {
onCurrentIndexChanged: {
console.log(myTreeView.selection.selectedRows(0))
console.log(currentIndex)
}
}
selectionMode: Controls.SelectionMode.ExtendedSelection
onDoubleClicked: {
if (isExpanded(index))
collapse(index);
else
expand(index);
}
}
In the example above I just try to print the selected rows to the console to make sure I have the right selection. currentIndex
always holds the last selected index(as expected), but the selection.selectedRows()
which is supposed to hold all the rows that are currently selected, is always one step behind. For example:
if user (while holding Ctrl) selects rows 1, 2, 3
one by one the selection.selectedRows()
will be null, "1", "1,2"
and currentIndex
will be 1, 2, 3
respectively. Combining these two together, one can get the list of all indexes that are in selected state.
My problem is that if the user releases the Ctrl and selects row 4
, then the selection.selectedRows()
will be "1,2,3"
although it should be null
.
To summarize it is not possible to distinguish between the case that the user selects (holding Ctrl) rows 1,2,3,4
and the case in which user first selects rows (holding Ctrl) 1,2,3
and then releases Ctrl and just selects row 4
.
I have also tested with myTreeView.selection.selectedIndexes
, but still the same behaviour.
It looks like a bug in TreeView to me, please advice how to solve.
Thanks.
You should use onSelectionChanged
instead of onCurrentIndexChanged
. With that signal you can get a list of selected indexes.
I don't know your whole code, but using the File System Browser example provided by Qt you can check the difference.
In that example, replace
ItemSelectionModel {
id: sel
model: fileSystemModel
}
by
ItemSelectionModel {
id: sel
model: fileSystemModel
onSelectionChanged: {
console.log("onSelectionChanged - selectedRows: " + selectedIndexes)
}
onCurrentIndexChanged: {
console.log("onCurrentIndexChanged - selectedRows: " + selectedIndexes)
}
}
To see how both signals work.