【问题标题】:Uncheck/Check all checkboxes at once一次取消选中/选中所有复选框
【发布时间】:2026-01-06 15:15:02
【问题描述】:

我想在选中/取消选中另一个复选框时选中/取消选中所有剩余的复选框(All option - 列表视图中的第一个复选框)。

在 QML 中,此类操作是使用 ID 处理的,并且由于我的 Listview 是从 model 动态生成的,因此我无法为其他复选框生成 ID。目前,我的代码仅选中/取消选中列表中的第一个复选框。请指出我做错了什么

import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3

Page {

    id : somepageid

    ListView{

        id: multiSelectCheckList
        model: ["1", "2", "3", "4"]
        height: parent.height
        width: parent.width

        delegate: Column{

            height: 20
            width: parent.width


            // All checkbox option

            Loader{

                id: loaderAll
                height: 15
                active: model.row === 0
                sourceComponent:

                    CheckBox {
                    checked: true
                    text: "All"
                    indicator.width: 15
                    indicator.height: 15

                    onCheckStateChanged: {
                        // Here I want the check/uncheck feature
                        console.log("All", checked)

                        if(checked){
                            modelCheckBoxes.checked = true
                        } else{
                            modelCheckBoxes.checked = false
                        }
                    }
                }
            }

            // These checkboxes need to be check/uncheck
            // on clicking the above checkbox
            CheckBox {

                id: modelCheckBoxes
                anchors.top: loaderAll.bottom
                checked: true
                text: modelData
                indicator.width: 15
                indicator.height: 15

            }

        }
    }


}

【问题讨论】:

    标签: qt checkbox qml


    【解决方案1】:

    您可能想看看这里:https://doc.qt.io/qt-5/qml-qtquick-controls2-checkbox.html#details

    CheckBox 的第二个例子演示了如何在ButtonGroup 的帮助下达到你想要的效果:

    Page {
        id : somepageid
    
        ButtonGroup {
            id: childGroup
            exclusive: false
            checkState: mainCheckBox.checkState
        }
    
        CheckBox {
            id: mainCheckBox
            checked: true
            text: "All"
            indicator.width: 15
            indicator.height: 15
            checkState: childGroup.checkState
        }
    
        ListView {
            id: multiSelectCheckList
            model: ["1", "2", "3", "4"]
            height: parent.height
            width: parent.width
            anchors {
                top: mainCheckBox.bottom
                margins: 10
            }
    
            delegate: CheckBox {
                id: modelCheckBoxes
                checked: true
                text: modelData
                indicator.width: 15
                indicator.height: 15
                ButtonGroup.group: childGroup
            }
        }
    }
    

    【讨论】: