为什么 QML ListView 委托不会立即对选择更改做出反应?

Why QML ListView delegate doesn't react on selection changes immediately?

我想知道为什么这不起作用?

ListView {
   id: root
   property var selection: QtObject {}
   ...
   delegate: MyView {
       focused: ListView.isCurrentItem
       selected: root.selection[index] === true

       Rectangle {
          id: selectionOverlay
          anchors.fill: parent
          color: "red"
          opacity: 0.3
          visible: selected
      }

   }

   Keys.onPressed: if (event.key === Qt.Key_Space) {
                        if(!root.selection[root.currentIndex])
                           root.selection[root.currentIndex] = true;
                       else 
                           root.selection[root.currentIndex] = false;
    }
}

即,委托不会对 selection 对象中的更改做出反应。只有在重新创建索引的委托时才能看到 selection(例如,当滚动得足够远和向后滚动时)。

root.selection[index] 更改为 ListView.view.selection[index] 也无济于事。

我需要在 ListView 级别上有 selection 来管理多个 select 内容。 一直在敲我的头。

谢谢!

问题是,通过更改 selection 属性 的子 属性,selection 属性 的更改信号本身不会被发射。

QML 绑定机制仅在 属性 本身的值发生变化时才起作用。但在您的情况下,selection 指向的对象永远不会改变,因此如果 selection 的某些子 属性 发生变化,您将无法收到通知。

作为解决方法,您可以 re-assign/refresh 整个选择对象,一旦其任何子属性发生变化。