我有一個ListModel和一個DelegateModel,一個ListView和3個按鈕。 DelegateModel有一個組:myGroup 點擊前兩個按鈕,我將元素添加到具有不同屬性的ListModel,然後將用它們添加它們或不將它們添加到myGroup。第三個按鈕用於切換過濾器。如何將元素添加到DelegateModelGroup,具體取決於屬性
ListModel {
id: rootModel
}
DelegateModel {
id: visualModel
model: rootModel
groups: [DelegateModelGroup { name: 'myGroup' }]
delegate: Rectangle {
width: model.width
height: model.height
color: model.color
border.width: 1
Component.onCompleted: DelegateModel.inMyGroup = Qt.binding(function() {return width == 80})
}
}
ListView {
width: 300
height: 480
model: visualModel
}
Rectangle {
id: b1
x: 350
width: 100
height: 50
color: 'lightsteelblue'
Text {
anchors.centerIn: parent
text: 'add 80'
}
MouseArea {
anchors.fill: parent
onClicked: rootModel.append({ width: 80, height: 30, color: 'steelblue' })
}
}
Rectangle {
id: b2
x: 350
y: 70
width: 100
height: 50
color: 'violet'
Text {
anchors.centerIn: parent
text: 'add 50'
}
MouseArea {
anchors.fill: parent
onClicked: rootModel.append({ width: 50, height: 30, color: 'violet' })
}
}
Rectangle {
id: b3
x: 350
y: 140
width: 100
height: 50
color: 'green'
Text {
anchors.centerIn: parent
text: 'filter'
}
MouseArea {
anchors.fill: parent
property bool toggle: false
onClicked: {
visualModel.filterOnGroup = toggle ? '' : 'myGroup'
toggle = !toggle
}
}
}
到目前爲止,只要不設置過濾器,我可以將兩種類型的元素添加到模型中,然後我就可以過濾。 但是,只要設置了過濾器,我就不能將元素添加到模型(組)中。這很明顯,因爲默認情況下不添加元素,所以組件未完成,並且沒有任何內容添加到組中,直到我再次取消設置該過濾器,並且所有待處理元素都被實例化,完成並最終添加爲止。
因此,我尋找另一種方法來根據屬性自動添加元素到組中,或者排除它們。
我知道,我可以設置includeByDefault: true
,然後在實例化一次之後丟棄它們。雖然這解決了這個特定的問題,但它並沒有解決下一個問題,我將在那裏更改屬性,因此將它從組中移出,然後將其更改回來。直到組件重新恢復爲止,它纔會重新出現。
哦,我知道,我可以用C++解決這個問題,但我不想,除非必要。
太棒了!謝謝。我認爲這是我可以建立的基礎。我只需要添加功能,即
setGroups()
將被調用,當一個元素被改變(因此可能被踢出或添加到組),但這是一個好的開始! – derM