I have a QML TreeView
containing some onClicked()
logic that calls a Q_INVOKABLE function that takes in the current row number and the parent row number of the TreeView
as parameters. The problem is that when I select something, and then I click to expand or collapse something. The previous values are still getting passed which sometimes makes the application crash. I've tried to call treeView.selection.clearCurrentIndex()
and treeView.selection.clearSelection()
in onCollapsed()
and onExpanded()
which deselects the item, but for some reason still passes the values from the previously selected item.
//main.qml
TreeView {
id: treeView
anchors.fill: parent
model: treeviewmodel
selection: ItemSelectionModel {
model: treeviewmodel
}
TableViewColumn {
role: "name_role"
title: "Section Name"
}
onCollapsed: {
treeView.selection.clearSelection() // deselects the item, but still passes the previous values
}
onExpanded: {
treeView.selection.clearSelection()
}
onClicked: {
console.log("Current Row: " + treeView.currentIndex.row + "Parent Row: " + treeView.currentIndex.parent.row)
//I need something here that will set treeView.currentIndex.row and treeView.currentIndex.parent.row to -1
//so that when I collapse or expand, -1 gets passed instead of the previous values
}
}
I was able to solve this by setting some additional flags (thanks @Tarod for the help). I had to save the value of the rows so that I could check if they changed. If they did not change, I would not call the function, so no obsolete values would get passed.
TreeView {
id: treeView
anchors.fill: parent
model: treeviewmodel
property int currentRow: -1
property int parentRow: -1
property int lastCurrentRow: -1
property int lastParentRow: -1
selection: ItemSelectionModel {
model: treeviewmodel
}
TableViewColumn {
role: "name_role"
title: "Section Name"
}
onCollapsed: {
currentRow = -1
parentRow = -1
}
onExpanded: {
currentRow = -1
parentRow = -1
}
onClicked: {
console.log("Row: " + treeView.currentIndex.row + " Parent : " + treeView.currentIndex.parent.row)
//logic needed to not reselect last item when collpasing or expanding tree
if (lastCurrentRow === treeView.currentIndex.row && lastParentRow === treeView.currentIndex.parent.row)
{
currentRow = -1
parentRow = -1
}
else
{
lastCurrentRow = treeView.currentIndex.row
lastParentRow = treeView.currentIndex.parent.row
currentRow = treeView.currentIndex.row
parentRow = treeView.currentIndex.parent.row
}
if (currentRow === -1 && parentRow === -1)
{
//nothing selected - do nothing
}
else
{
//omitted some additional logic
}
}
}