当字符串数组模型更改时,列表视图不会刷新



我的列表视图在添加新条目时不会在我的模型中显示这些条目。

当对话框打开时,我将QStringList从C++项复制到Qml属性中。 然后,用户使用提供的控件(添加、修改、删除(修改数组。

遗憾的是,当我修改属性时,列表视图不会更新。属性已正确修改(如调试输出所示(。

如何使用数据绑定自动更新列表视图?

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property var things
Component.onCompleted: things = [] // normally retrieved from C++ QStringList
ColumnLayout {
anchors.fill: parent
RowLayout {
Layout.fillWidth: true
TextField {
Layout.fillWidth: true
id: theTextField
}
Button {
Layout.fillWidth: true
text: qsTr("Append")
onPressed: {
things.push(theTextField.text)
console.log(things)
}
}
Button {
Layout.fillWidth: true
text: qsTr("Remove")
onPressed: {
var index = things.indexOf(theTextField.text)
if(index == -1)
console.warn('Not found!')
else
things.splice(index, 1)
console.log(things)
}
}
Button {
Layout.fillWidth: true
text: qsTr("Clear");
onPressed: {
things = [];
console.log(things)
}
}
}
ListView {
id: listView
Layout.fillWidth: true
Layout.fillHeight: true
model: things
delegate: Label {
text: modelData
}
}
}
}

原因是,使用函数修改things时没有thingsChanged信号。无论您做什么,存储在things中的引用都将保持不变。

对于数据模型(如ListModel(,这是相同的,但存在特殊信号,其中许多信号用于向任何视图指示它应该更新其内容。

如果您迫切需要使用数组,则需要在更改数组内容时手动调用thingsChanged()。但是,由于这仅表明整个数组已更改,因此View的主要优势之一是无效 - 仅更改已更改内容的能力。

ViewthingsChanged信号做出反应时,它将销毁所有当前委托,然后再次重新创建它们,无论是否有任何不同。

如果使用ListModelQAbstractItemModel后代,则View可以插入新委托的单个实例,删除或更改它们。

将数组替换为真正的 ListModel。使用函数追加!

Button {
Layout.fillWidth: true
text: qsTr("Clear");
onPressed: {
model.append({"data": theTextField.text})
}
}

和在主块的 和 列表模型 { id :model }

最新更新