【问题标题】:Setting Checked property of a Button in QML在 QML 中设置按钮的 Checked 属性
【发布时间】:2020-10-03 10:33:17
【问题描述】:

我在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"
        }
    }
}

【问题讨论】:

    标签: qt qml qtquick2


    【解决方案1】:

    有一种方法可以使用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获得检查按钮。

    【讨论】:

      【解决方案2】:
      color: button2.checked ? "red" : "white"
      

      【讨论】:

      • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。这个提供的答案可以从解释中受益。仅代码答案不被视为“好”答案。来自Review
      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2011-03-08
      • 2017-02-27
      相关资源
      最近更新 更多