我正在尝试制作ListView
n 个CheckBox
项目,其中顶部项目是“全选/取消全选”项目。CheckBox
在程序启动时检查选择/取消选择所有es 时,它会选择/取消选择所有CheckBox
es,但是一旦我检查/取消选中任何一个CheckBox
es,然后返回按下全选/取消选择,以前选中/取消选中CheckBox
不再切换。我不明白为什么它不能按预期工作。下面提供的代码和调试输出:
看法:
import QtQuick 2.0
import QtQuick.Controls 1.2
Rectangle {
id: view
ScrollView {
id: scrollView
anchors.fill: parent
ListView {
id: listView
anchors.fill: parent
model: myModel
delegate: Delegate { }
}
}
Model {
id: myModel
Component.onCompleted: {
add("C", "Orange", false)
add("D", "Red", false)
}
}
function add(name, color, check)
{
myModel.append({"name":name, "color":color, "check":check})
}
function edit(index, attribute, value)
{
myModel.setProperty(index, attribute, value)
}
function editMultiple(offset, length, attribute, value)
{
for (var i = offset; i < length; i++)
{
edit(i, attribute, value)
}
}
function length()
{
return myModel.count
}
}
代表:
import QtQuick 2.0
import QtQuick.Controls 1.2
Item {
id: delegate
height: 40
width: 100
property bool allCheckBoxChecked: false
CheckBox {
id: checkBox
text: name
anchors {
fill: parent
leftMargin: 20
rightMargin: 20
}
checked: check
onCheckedChanged: {
if (index === 0)
{
allCheckBoxChecked = checkBox.checked
}
else
{
edit(index, "check", checkBox.checked)
}
console.log("Name: " + name + " Color: " + color + " Check: " + check)
}
}
onAllCheckBoxCheckedChanged: {
console.log("All: " + allCheckBoxChecked)
if (allCheckBoxChecked)
{
editMultiple(0, length(), "check", true)
}
else
{
editMultiple(0, length(), "check", false)
}
}
}
模型:
import QtQuick 2.0
ListModel {
id: listModel
ListElement {
name: "All"
color: "Black"
check: false
}
ListElement {
name: "A"
color: "Blue"
check: false
}
ListElement {
name: "B"
color: "Green"
check: false
}
}
调试输出:
//Pressing "All".
qml: All: true
qml: Name: A Color: Blue Check: true
qml: Name: B Color: Green Check: true
qml: Name: C Color: Orange Check: true
qml: Name: D Color: Red Check: true
qml: Name: All Color: Black Check: true
//Pressing "All".
qml: All: false
qml: Name: A Color: Blue Check: false
qml: Name: B Color: Green Check: false
qml: Name: C Color: Orange Check: false
qml: Name: D Color: Red Check: false
qml: Name: All Color: Black Check: false
//Pressing "A".
qml: Name: A Color: Blue Check: true
//Pressing "All".
qml: All: true
//A does not get assigned anymore...
qml: Name: B Color: Green Check: true
qml: Name: C Color: Orange Check: true
qml: Name: D Color: Red Check: true
qml: Name: All Color: Black Check: true
//Pressing "All".
qml: All: false
//A does not get assigned anymore...
qml: Name: B Color: Green Check: false
qml: Name: C Color: Orange Check: false
qml: Name: D Color: Red Check: false
qml: Name: All Color: Black Check: false