我是 QML 的新手,需要一些幫助。
我正在通過 python 代碼填充串列視圖。
每個串列元素由一個復選框和相關文本組成。此外,我想使用 2 個按鈕一次選擇/取消選擇所有復選框。在按鈕的 onClicked 函式中,我可以訪問 itemName,但無法訪問選中狀態。
我該如何解決這個問題?
Rectangle{
ListModel {
id: sportItems
}
Component{
id:sportRow
CheckBox{
text: "<font color=\"white\">" itemName "</font>"
checked: true
onClicked : {
console.log(itemName " :::: " checked);
}
}
}
ListView{
id: sports
objectName: "sports"
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.topMargin: 10
anchors.leftMargin: 10
model: sportItems
delegate: sportRow
function addItem(entry){
sportItems.append({itemName: entry})
sports.height = sports.height 20
}
}
Row{
anchors.top: sports.bottom
anchors.left: parent.left
anchors.right: parent.right
Button{
anchors.left: parent.left
anchors.leftMargin: 10
text: "All"
onClicked: {
for(var x =0; x< sports.model.get(0).count; x ){
sports.model.get(x).checked = true
}
}
}
Button{
anchors.right: parent.right
anchors.rightMargin: 10
text: "Nothing"
onClicked: {
for(var x =0; x< sports.model.get(0).count; x ){
sports.model.get(x).checked = false
}
}
}
}
}
uj5u.com熱心網友回復:
如果您打算在您的委托之外修改選中狀態(即從 Check All 按鈕),那么選中狀態應該是您模型的一部分。因此,您可以添加一個名為“isChecked”的角色(因此它不會與 CheckBox 的內置checked屬性沖突):
function addItem(entry) {
sportItems.append({
itemName: entry,
isChecked: true // Keep the checked state
})
sports.height = sports.height 20
}
然后確保代表實際從模型中讀取/寫入該資料:
Component {
id:sportRow
CheckBox {
text: "<font color=\"white\">" itemName "</font>"
checked: isChecked // Read from the model
onClicked : {
// Write back to the model
sportItems.setProperty(index, "isChecked", !isChecked)
}
}
}
在 Check All 按鈕中,您只需要設定模型值:
Button {
anchors.left: parent.left
anchors.leftMargin: 10
text: "All"
onClicked: {
for(var i = 0; i < sports.model.count; i ) {
sports.model.setProperty(i, "isChecked", true)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473892.html
上一篇:如何使用相同的ListView移動組的ListViewItem部分來代替另一個ListViewItem?
下一篇:如何顯示某些影像雙寬的影像串列
