考虑以下 QML 原型代码:
import QtQuick 2.15
import QtQuick.Layouts
Item {
id: test
anchors.fill: parent
Rectangle {
anchors.fill: parent
anchors.margins: 5
color: "#FDFDFD"
ListView {
id: listView
width: parent.width
height: parent.height
model: ListModel {
ListElement {
name: "Loading..."
}
}
delegate: Item {
width: parent.width
height: 50
Row {
spacing: 10
Text {
text: code
}
Text {
text: name
}
}
}
Component.onCompleted: {
listView.model = [{"id":"1","code":"Code 1", "name":"Name 1",}]
}
}
}
}
运行时出现以下错误:
qrc:/components/Test.qml:1308371392: ReferenceError: code is not defined
qrc:/components/Test.qml:38:25: Unable to assign [undefined] to QString
qrc:/components/Test.qml:35: ReferenceError: code is not defined
qrc:/components/Test.qml:38:25: Unable to assign [undefined] to QString
qrc:/components/Test.qml:35: ReferenceError: code is not defined
qrc:/components/Test.qml:35: ReferenceError: code is not defined
code
和 name
在 JSON 中的 Component.onCompleted
处定义 - 它是一个占位符 - 稍后我将在此处注入数据库数据。
ListView 上没有显示数据 - 我做错了什么?
您正在 ListModel 和 JavaScript 数组之间切换,这意味着您的委托需要在
model.name
到 modelData.name
之间切换。您可以让您的代表支持两者:
import QtQuick
import QtQuick.Controls
Page {
ListView {
id: listView
anchors.fill: parent
model: ListModel {
ListElement { name: "Loading..." }
}
delegate: Row {
spacing: 10
Text {
text: model.code || modelData.code
}
Text {
text: model.name || modelData.name
}
}
}
Timer {
interval: 1000
running: true
onTriggered: {
listView.model = [{"id":"1","code":"Code 1", "name":"Name 1",}]
}
}
}