是否可以實作 3 個ListModels(一個在另一個內部),如果是,我該怎么做?3 ListModels 相應地用于小時日和月。換句話說,我想要一個模型內的小時模型內的模型內的天數為月,我將在嵌套的ListViews(其中 3 個)中使用它們來顯示小時日歷中的日期和月份。我在下面做了一個嘗試:
ListModel{
id:monthlistModel
ListElement {
monthName:0
daylistModel:[
ListElement {
day:0
hourlistModel: [
ListElement{ hour:0;notes:"" }
]
}
]
}
ListElement {
monthName:1
daylistModel:[
ListElement {
day:1
hourlistModel: [
ListElement{ hour:1;notes:"" }
]
}
]
}
但我無法完成它。此外,當我運行我的代碼時,我有一些型別錯誤問題。hourlistModel 堅持為我的嵌套串列視圖未定義,我不知道為什么。無論如何回到我的問題,我怎樣才能繼續上面 listmodel的顯示 24 小時、31 天和 12 個月?
uj5u.com熱心網友回復:
我建議使用 javascript 命令性地執行此操作,而不是在 QML 中宣告性地執行此操作,因為它可以更加動態和簡短。一個缺點是,根據我的經驗,這沒有得到很好的記錄。
如果將陣列附加到 ListModel,則所有陣列元素都將轉換為 ListElements。除此之外,如果附加了一個陣列,并且該陣列內部有嵌套陣列,則嵌套陣列會自動轉換為內部嵌套的 ListModels。
這是一個完整的例子:
import QtQuick 2.15
import QtQuick.Window 2.0
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.12
Window {
visible: true
width: 1000
height: 600
ListModel {
id: monthsModel
Component.onCompleted: {
let months = [
{
name: "January",
days: createDays(31) // returns an array, nested arrays become nested ListModels when appended
},
{
name: "February",
days: createDays(28)
},
// add more months etc.
]
append(months) // appending a whole array makes each index into a ListElement at the top level
}
function createDays(dayCount) {
let days = []
for (let i = 0; i < dayCount; i ) {
days.push({
day: i 1,
hours: createHours()
}
)
}
return days
}
function createHours() {
let hours = []
for (let i = 0; i < 24; i ) {
hours.push({
hour: i,
notes: ""
}
)
}
return hours
}
}
// Visual example code starts here ///////////////
ColumnLayout {
id: monthsColumn
Repeater {
model: monthsModel
delegate: Rectangle {
id: month
color: "pink"
implicitWidth: daysRow.implicitWidth 10
implicitHeight: daysRow.implicitHeight 10
RowLayout {
id: daysRow
anchors {
centerIn: parent
}
Text {
text: model.name
}
Repeater {
model: days // refers to the "days" entry in monthsModel.get(<monthIndex>)
delegate: Rectangle {
id: day
color: "orange"
implicitWidth: hoursColumn.implicitWidth 10
implicitHeight: hoursColumn.implicitHeight 10
ColumnLayout {
id: hoursColumn
anchors {
centerIn: parent
}
Text {
text: model.day
}
Repeater {
model: hours // refers to the "hours" entry in monthsModel.get(<monthIndex>).get(<dayIndex>)
delegate: Rectangle {
id: hour
color: "yellow"
implicitHeight: 5
implicitWidth: 5
// do something here with model.notes for each hour
}
}
}
}
}
}
}
}
}
}
此輸出以粉紅色顯示月份,以橙色顯示天數,以黃色顯示小時數:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313873.html
上一篇:告訴函式等待用戶按下Qt按鈕
下一篇:QtAndroid目錄
