我一直試圖在QML中用我的一個串列中的資料填充一個ListView,但是在檔案中并沒有顯示如何動態填充ListModel或ListView。串列中的資料不斷變化,我打算實時更新串列,這就是為什么我不需要一個硬編碼的模型。
根據教程,這樣做是可行的:
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"。
高度。500
寬度: 0.95 * parent.width
串列視圖 {
anchors.fill: parent
模型:fruitModel
委托:fruitDelegate
}
}
ListModel {
id: fruitModel
ListElement {
name: "Apple"
成本。2.45。
}
ListElement {
name: "Orange"/span>
成本。3.25。
}
ListElement {
name: "Banana" 1.95
}
}
組件 {
id: fruitDelegate
行 {
間隔。10
Text { text: name; color: "white" }
Text { text: '$' cost; color: "white" }
}
}
但這并不是:
userModel : ["Tony"/span>, "Stark"/span>] //包含用戶名稱的串列。
矩形 {
anchors.horizontalCenter: parent.horizontalCenter
顏色: "black"
高度。500
寬度: 0.95 * parent.width
串列視圖 {
anchors.fill: parent
model: userModel //一個包含所有用戶的串列。
委托:fruitDelegate
}
}
組件 {
id: fruitDelegate
行 {
間隔。10
Text { text: name; color: "white" }
}
}
uj5u.com熱心網友回復:
角色定義了如何訪問資訊,例如,fruitModel有2個角色:名稱和成本。但是當使用一個串列作為模型時,你必須使用modelData作為角色來訪問資訊:
Component {
id: fruitDelegate
行 {
間隔。10
Text { text: modelData; color: "white" }
}
ListModel可以通過append函式來更新:
Rectangle {
anchors.horizontalCenter: parent.horizontalCenter
color: "black"。
高度。500
寬度: 0.95 * parent.width
串列視圖 {
anchors.fill: parent
模型:fruitModel
委托:fruitDelegate
}
}
ListModel {
id: fruitModel
Component.onCompleted: {
fruitModel.append({"name"/span>: "Tony"})
fruitModel.append({"name": "Stark"})
}
}
組件 {
id: fruitDelegate
行 {
間隔。10
Text { text: name; color: "white" }
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310186.html
標籤:
