QML中的ExclusiveGroup

Exclusive这个单词在高中应该都学过,是互斥的意思。如果你没有上过或者还没有上到高中,那你非常棒,计算机领域的大师很多都是这么起步的。

ExclusiveGroup顾名思义就是互斥分组,效果很明显,就是说你选了一个,就不能选另一个。

这个元素提供了两种用法,一种是像做定位器一样的,把那些乱七八糟的元素嵌套进去就可以了,在选择的时候就是互斥的。

但是多层嵌套会让人崩溃,所以我们还可以给它指定一个id,然后设置其它元素的属性就好了。

举个栗子:


import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true

  ExclusiveGroup{
  id:huchi
  }
  RadioButton{
  id:radio1
  text: "我是一号"
  exclusiveGroup: huchi
  }
  RadioButton{
  id:radio2
  anchors.top: radio1.bottom
  anchors.topMargin: 4
  text: "我是二号"
  exclusiveGroup: huchi
  }
  RadioButton{
  id:radio3
  anchors.topMargin: 4
  anchors.top: radio2.bottom
  text: "我是三号"
  exclusiveGroup: huchi
  }
}

效果图:

这个示例并不是很好,因为很多人觉得radio似乎本来就是用来单选的,你可以尝试注释掉其中某个exclusiveGroup:huchi 然后你就会发现不同了。

原文地址:https://www.cnblogs.com/senior-engineer/p/5590455.html