关于qt:在QML中设置Button的Checked属性

Setting Checked property of a Button in QML

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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,可以将按钮状态检查为true或false,还可以通过访问btnGrp.checkedButton来检查按钮。


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