【发布时间】:2021-09-07 23:40:12
【问题描述】:
我一直在尝试用我拥有的列表中的数据填充 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" }
}
}
【问题讨论】: