Evan Krause
Evan Krause

Reputation: 187

How to dynamically update a ListView in QML

I have a ListView that displays a list of all notifications for a user. Right now since I'm using Component.onCompleted, if the list updates, the new list is not displayed, but the one which existed during instantiation. How could we solve this? Would using a Loader with a separate component instead help?

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" }
    }
}

Upvotes: 0

Views: 1283

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

Component.onCompleted only runs when the object is built and never again. So using that method to add items to the model is useless, instead you should use the function that reports the new data:

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

Upvotes: 1

Related Questions