qt - 创建动态 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 有2 个角色:名称和成本。但是当使用列表作为模型时,您必须使用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" }
}
}
推荐阅读
- excel - 在不同单元格中以任何顺序搜索 3 个单词“文本”的公式
- ruby-on-rails - rails first_or_create 不更新现有记录
- python - Python TensorFlow Lite 解释器崩溃
- javascript - 我对Foundation的源代码有些疑惑
- c# - 如何使用 CrmServiceClient 设置空属性值
- python - 带有三个表的 Flask SQLAlchemy 外连接
- scala - 更新和删除查询在 play-slick 中不起作用
- c# - 无法访问已处置的对象 Asp.net Identity Core
- python - 从源代码安装时,使用 Python 3 和 Windows 安装 Spacy for NLP 会出错
- wordpress - Wordpress 移动菜单插件