创建动态ListModel是QML



我一直在尝试用列表中的数据填充QML中的ListView,但在文档中没有显示如何动态填充ListModel或ListView。列表中的数据不断变化,我打算实时更新列表,这就是为什么我不需要硬编码模型的原因。

基于教程,这是有效的:

Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"
height: 500
width: 0.95 * parent.width
ListView {
anchors.fill: parent
model: fruitModel
delegate: fruitDelegate
}
}
ListModel {
id: fruitModel
ListElement {
name: "Apple"
cost: 2.45
}
ListElement {
name: "Orange"
cost: 3.25
}
ListElement {
name: "Banana"
cost: 1.95
}
}
Component {
id: fruitDelegate
Row {
spacing: 10
Text { text: name; color: "white" }
Text { text: '$' + cost; color: "white" }
}
}

但这不是:

userModel : ["Tony", "Stark"] //list containing names of users
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"
height: 500
width: 0.95 * parent.width
ListView {
anchors.fill: parent
model: userModel // a list containing all users
delegate: fruitDelegate
}
}
Component {
id: fruitDelegate
Row {
spacing: 10
Text { text: name; color: "white" }
}
}

角色定义了如何访问信息,例如fruitModel有两个角色:name和cost。但是当使用列表作为模型时,您必须使用modelData作为角色来访问信息:

Component {
id: fruitDelegate
Row {
spacing: 10
Text { text: modelData; color: "white" }
}
}

ListModel可以通过append函数更新:

Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"
height: 500
width: 0.95 * parent.width
ListView {
anchors.fill: parent
model: fruitModel
delegate: fruitDelegate
}
}
ListModel {
id: fruitModel
Component.onCompleted: {
fruitModel.append({"name": "Tony"})
fruitModel.append({"name": "Stark"})
}
}
Component {
id: fruitDelegate
Row {
spacing: 10
Text { text: name; color: "white" }
}
}

最新更新