Home > OS >  how to automatically update Listview in qml when ListModel changed
how to automatically update Listview in qml when ListModel changed

Time:06-07

I have a problem that I use ListModel to save information that I read from database. But when the ListModel updated, the ListView did not update. my code as below:

ListModel{ id: selectedTempStationlistModel }

I read my database as below and append records from database:

selectedTempStationlistModel.append({"id": idValue})
                                                       

and my ListView like that :

**ListView{
    id: amr_view_three
    model: selectedTempStationlistModel
    height: 220
    width: 655
    anchors.centerIn: parent
    Layout.columnSpan: 2
    Layout.fillHeight: true
    Layout.fillWidth: true
    clip: true
    delegate: Component  {
        Item{
            width: amr_view_three.width
            height: 80
            Text {
                anchors.centerIn: parent
                text: id
                font.family:"SimSun"
                font.pointSize: 16
            }
        }
    }
}**

My target only need to show id from databse to listview. each time I add one record in database, I checked my ModelList that already changed, however, the ListView does not update new data of the model. Please help me. Thanks

CodePudding user response:

Your view will not update automatically when you update the model, you need to emit the corresponding signals in order for your view to update, generally you would have a update function in your model that looks like something like this:

def update(self, ...){
    self.layoutAboutToBeChanged.emit()
    # update your model
    self.layoutChanged.emit()
}

You need to emit layouAboutToBeChanged before you touch any model data, and after you update emit layoutChanged

CodePudding user response:

Thank TOHO. Perhaps some cases the model can not update automatically, my case my model can update automatically. The reason is Because of my poor typo. Btw, I found something related to forceLayout() in some cases if model can not update automatically. Thank you for your time so much

  • Related