【问题标题】:Uncheck button when buttons are exclusive in Qt Quick Controls 2当 Qt Quick Controls 2 中的按钮独占时取消选中按钮
【发布时间】:2018-06-29 08:30:03
【问题描述】:

我需要列出应该是排他的可检查AbstractButton,但默认情况下我不能取消选中已选中的按钮而没有选中任何一个按钮。

现在我必须做这样的事情来模仿这样的逻辑:

Item {
    AbstractButton {
        id: oneButton
        checkable: true
        onCheckedChanged: {
            if(checked) {
                if(twoButton.checked || threeButton.checked || ...) {
                    twoButton.checked = threeButton.checked = ... = false
                }
            }
        }
    }

    AbstractButton {
        id: twoButton
        checkable: true
        onCheckedChanged: {
            if(checked) {
                if(oneButton.checked || threeButton.checked || ...) {
                    oneButton.checked = threeButton.checked = ... = false
                }
            }
        }
    }
    ...
}

这很难看,如果能找到更好的解决方案就好了。

【问题讨论】:

  • 只是好奇,这个的预期用途是什么?也就是说,用户界面会是什么样子?
  • @Mitch 是否有任何允许“别无选择”的专有组 GUI 元素?
  • @dtech 我认为您可以从不选择按钮开始,但是一旦选择了一个按钮,就必须选择一个。
  • 所以有一些使用利基。虽然我猜你可以很容易地有一个“无选择”按钮,虽然这会占用额外的屏幕空间。
  • 是的,这就是为什么我要询问 UI 的外观 - 我认为带有“无”或“请选择一个选项”项目的 ComboBox 可能是一种替代方案。

标签: qt qml qtquick2 qtquickcontrols2


【解决方案1】:

您可以通过在发布时强制取消选中一个不可选中的独占按钮:

Button {
    checkable: true
    autoExclusive: true
    property bool wasChecked
    onPressed: wasChecked = checked
    onReleased: {
        if (wasChecked) {
            checked = false;
            toggled(); // emit the toggled signal manually, since we changed the checked value programmatically but it still originated as an user interaction.
        }
    }
}

【讨论】:

  • 如果用户通过键盘取消选中它怎么办?我觉得它行不通。
  • 确实,您还需要处理Key.onPressedonReleased 空间。
  • 我的代码中包含checked: model.checked,我觉得会更合适。
【解决方案2】:

这个怎么样:

Column {
  id: col
  spacing: 2
  property int choice: -1
  Repeater {
    model: 5
    delegate: Button {
      checkable: true
      checked: col.choice === index
      onClicked: col.choice = (col.choice === index ? -1 : index)
      text: "Button " + index
    }
  }
  Text {
    text:  "Choice is " + (col.choice > -1 ? col.choice : "undefined")
  }
}

请注意,即使 choice 是从其他位置设置的,或者如果您在 GUI 中的多个位置有该按钮组,GUI 也会更新属性,只要它们都共享相同的 choice

【讨论】:

  • 按钮不能由Repeater 创建,因为它们每个都有自己的contentItem 和一些不同的附加属性。
  • @KamilZaripov 转发器只是为了获得一个简短的工作示例代码。您不必在代码中使用中继器。而不是使用索引 int 你可以手动指定使用任何你想要的。
猜你喜欢
  • 2019-02-08
  • 2017-12-27
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多