在 Qt 中使用不同模型的另一个列表视图的委托中访问列表视图模型数据

Access listview model data in the delegate of another listview with a different model in Qt

问题: 我在 qml 中有两个列表视图,它们都有基于 QAbstractListModel 用 C++ 实现的模型。

举个例子,假设两个列表视图只有两个角色,颜色和大小,这两个都是动态的,可以从一些外部数据输入(即 tcp 客户端)改变。 第二个列表视图中的每个项目都与第一个列表视图相关,其中第二个列表视图中的任何元素都将包含第一个列表视图中的一个元素的索引。 第二个列表视图不仅要显示自己的角色,还要显示第一个列表视图中元素的颜色和大小,其中它具有存储的索引。

如何在第二个列表视图中动态更新此值?

我已经使用了一些 setter 和 getter 并且可以在我第一次实例化第二个 listview 时填充数据,但是之后对第一个 listview 中的属性所做的任何更改都不会显示在第二个 listview 中,因为这个 listview 是未连接第一个列表中的数据,数据更新时不会更新。

问题是更具体地说,我如何连接这两者?最好不要更新整个第二个列表视图,而只更新连接到第一个列表中不断变化的元素的委托。

如果这个文本示例令人困惑,我可以尝试编写一些代码来进一步解释。

您的委托人可以在 ListView 中访问自己的 index,您可以将其与其他人的 ListView itemAtIndex 功能一起使用。

在第一个列表的委托中用属性绑定你想要的模型数据角色,并在第二个列表委托中使用它,即

// In the delegate of the first listview, named firstList
property text nameBind: name

// In the delegate of the second listview, where storedIndex is an index of an element in the first listview.
text: firstList.itemAtIndex(storedIndex).nameBind

我使用 itemAtIndex 用我在评论中写的内容尝试了上面的答案,但这不会在新数据到达时更新第二个列表中的 属性。

我通过在第二个列表的委托中创建一个函数来实现此功能,该函数搜索第一个列表的 contentItem 的子项,然后从那里绑定角色,如下所示:

function getDelegateInstanceAt(index) {
                    var len = cameraList.contentItem.children.length;
                    if(len > 0 && index > -1 && index < len) {
                        return cameraList.contentItem.children[index];
                    } else {
                        return undefined;
                    }
                }
property text firstListName: getDelegateInstanceAt(storedFirstListIndex).name