I am new to QML and need some help.
I am filling a listview by python code.
Each list element consists of a checkbox and related text. Additionally I want to use 2 Buttons to select/deselect all checkboxes at once. In the onClicked function of the buttons, I can access the itemName, but I am failing to access the checked state.
How can I solve this issue?
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
}
}
}
}
}
CodePudding user response:
If you intend to modify the checked state outside of your delegate (i.e. from the Check All button) then the checked state should really be a part of your model. So you can add a role named something like "isChecked" (so it doesn't conflict with the CheckBox's built-in checked property):
function addItem(entry) {
sportItems.append({
itemName: entry,
isChecked: true // Keep the checked state
})
sports.height = sports.height 20
}
Then make sure the delegates actually read/write that data from the model:
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)
}
}
}
In your Check All button, you just need to set the model values:
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)
}
}
}
