QML TreeView 在单击折叠或展开时传递先前的选择

QML TreeView passes previous selection when clicking to collapse or expand

我有一个 QML TreeView 包含一些 onClicked() 逻辑调用一个 Q_INVOKABLE 函数,该函数接收当前行号和 TreeView 的父行号作为参数。问题是,当我 select 某物时,我单击以展开或折叠某物。以前的值仍在传递,这有时会导致应用程序崩溃。我尝试在 onCollapsed()onExpanded() 中调用 treeView.selection.clearCurrentIndex()treeView.selection.clearSelection() 来删除 select 项目,但由于某种原因仍然传递来自以前 selected 项目。

//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
    }
}

我能够通过设置一些额外的标志来解决这个问题(感谢@Tarod 的帮助)。我必须保存行的值,以便检查它们是否发生了变化。如果它们没有改变,我就不会调用该函数,因此不会传递过时的值。

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
        }
    }
}