2017-09-05 62 views
2

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

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

回答

0

有一种方法,通过使用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

0

我怀疑它会工作。

Item { 
    id: column 

    Button { 
     id: btn1 
     checked: true 
     text: qsTr("button 1") 
     onClicked: 
     { 
      if (checked) 
      { 
       Console.log("Checked") 
       checked = false 
      } 
      else 
      { 
       Console.log("disabled") 
       checked = true 
      } 
     } 
    } 
} 
+0

我不认为它会工作。每次设置检查属性为false将无法正常工作!!! – pra7

+0

是的,我知道,但我告诉你如何禁用检查状态:)) –

+0

我更新的代码,你可以尝试它是否工作。 –