QML 中 ItemSelectionModel 的目的和用法

Purpose and usage of ItemSelectionModel in QML

在浏览 QML 文档时,我发现这个值得称赞的文档 class:ItemSelectionModel

C++-Class QItemSelectionModel 提供了更多详细信息,说明了跟踪模型中项的选择的目的。

但是在 QML 方面,我对如何使用它一无所知。

比方说,我有这个 ListModel

ListModel {
    id: lm
    ListElement { value: 0 }
    ListElement { value: 0 }
    ListElement { value: 0 }
    ListElement { value: 0 }
    ListElement { value: 1 }
    ListElement { value: 1 }
    ListElement { value: 2 }
    ListElement { value: 2 }
    ListElement { value: 0 }
    ListElement { value: 0 }
    ListElement { value: 2 }
    ListElement { value: 2 }
}

现在我有一个 View 在其中显示所有模型,在第二个视图中我只想显示模型的一部分。所以我创建了一个 ItemSelectionModel 并从第一个视图的委托中调用了它的 select 方法,这似乎根本没有效果。甚至 hasSelection-属性 也懒得去改变。

Repeater {
    model: lm
    delegate: Rectangle {
        property int row: Math.floor(index / 4)
        property int column: index % 4
        width: 100
        height: 100
        x: 100 * column
        y: 100 * row
        border.color: 'black'

        MouseArea {
            anchors.fill: parent
            onClicked: {
                ism.select(index, ItemSelectionModel.Select | ItemSelectionModel.Current)
                console.log(ism.hasSelection)
            }
        }
    }
}

ItemSelectionModel {
    id: ism
    model: lm
}

所以我想知道这个组件的目的是什么,它似乎什么都不做。或者,我怎样才能让它做一些有目的的事情?

文档确实一点帮助也没有。抱歉,我已经 filed a bug 考虑修复它。

在QML的世界里,它应该实现与QItemSelectionModel相同的功能(即保持多个视图的选择状态同步)——事实上,QML中的实现是直接实例化和调用是实际上和QItemSelectionModel的一样。

这实际上可能是问题的根源,因为 QML 的视图不使用 QModelIndexQItemSelectionModel 需要),而是 int index 引用行号模型的。要获得 QModelIndex,您可以调用 QAbstractItemModel::index,如下所示:

onClicked: {
    // note: lm here is the id of your ListModel
    ism.select(lm.index(index, 0), ItemSelectionModel.Select | ItemSelectionModel.Current)
    console.log(ism.selectedIndexes)
    console.log(ism.hasSelection)
}