在 QML 中设置选中按钮 属性

Setting Checked property of a Button in QML

我在 Column 中有一组按钮,我已经设置了 autoExclusive : true。现在只能按预期检查一个按钮。但是,如果我点击已经选中的按钮,如何禁用选中状态?以下是代码:

Column {
    id: column

    Button {
        checked: true
        text: qsTr("button 1")
        autoExclusive : true
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }

    Button {
        checked: true
        text: qsTr("button 2")
        autoExclusive : true
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }

    Button {
        checked: true
        text: qsTr("button 3")
        autoExclusive : true
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }
}

有一种方法可以使用 ButtonGroup :

Column {
    id: column

    Button {
        checked: true
        text: qsTr("button 1")
        ButtonGroup.group: btnGrp //assign buttongroup
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }

    Button {
        checked: true
        text: qsTr("button 2")
        ButtonGroup.group: btnGrp //assign buttongroup
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }

    Button {
        checked: true
        text: qsTr("button 3")
        ButtonGroup.group: btnGrp //assign buttongroup
        checkable : true
        background: Rectangle {
            color:checked ? "red" : "white"
        }
    }
}

ButtonGroup {
    id:btnGroup
}

现在遍历 btnGrp.buttons 可以检查按钮状态是真还是假,也可以通过访问 btnGrp.checkedButton 来检查按钮。

color: button2.checked ? "red" : "white"