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

时间:2016-12-02 22:08:21

标签: qt qml qtquick2 qtquickcontrols

我有一个QML TreeView,其中包含一些调用Q_INVOKABLE函数的onClicked()逻辑,该函数将当前行号和TreeView的父行号作为参数。问题是,当我选择一些东西,然后我点击展开或折叠一些东西。之前的值仍然传递,有时会导致应用程序崩溃。我已尝试在treeView.selection.clearCurrentIndex()treeView.selection.clearSelection()中调用onCollapsed()onExpanded()来取消选择该项目,但由于某种原因,仍会传递先前所选项目中的值。

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

1 个答案:

答案 0 :(得分:0)

我能够通过设置一些额外的标志来解决这个问题(感谢@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
        }
    }
}