如何在QML中动态更新ListView



我有一个ListView,它为用户显示所有通知的列表。现在,由于我使用的是Component.onCompleted,如果列表更新,则不显示新列表,而是显示实例化期间存在的列表。我们如何解决这个问题?使用带有单独组件的Loader会有帮助吗?

property int numNotifications: backend_service.num_notifications
property var notifications: []
onNumNotificationsChanged: {
for(var x=0; x<numNotifications; x++) {
var notif = backend_service.notifications.get(x);
notifications.push(notif)
}
}
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"
height: 500
width: 0.95 * parent.width
ListView {
anchors.fill: parent
model: notifModel
delegate: notifDelegate
}
}
ListModel {
id: notifModel
Component.onCompleted: {
for(var i in notifications) {
notifModel.append({"name": notifications[i]})
}
}
}
Component {
id: notifDelegate
Row {
spacing: 10
Text { text: name; color: "white" }
}
}

组件。onCompleted只在对象构建时运行,不会再运行。因此,使用该方法向模型添加项目是无用的,相反,您应该使用报告新数据的函数:

onNumNotificationsChanged: {
for(var x=0; x<numNotifications; x++) {
var notif = backend_service.notifications.get(x);
notifModel.append({"name": notif})
}
}

最新更新