关于qt:QML Button ExclusiveGroup属性?

QML Button exclusiveGroup property?

我无法将ExclusiveGroup分配给我的可检查按钮。

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
ExclusiveGroup {
    id: group

    onCurrentChanged: {
        if(current != null) {
            console.info("button checked...no!")
            current = null
            //current.checked = false    <--- also this
        }
    }
}


            Column {
                width: parent.width
                spacing: 0

                Button {
                    id: btnScan
                    flat: true
                    text: qsTr("But1")
                    width: parent.width
                    checkable: true
                    exclusiveGroup: group
                }
                Button {
                    id: btnWhiteList
                    flat: true
                    text: qsTr("But2")
                    width: parent.width
                    checkable: true
                    exclusiveGroup: group
                }
}

该文档明确指出Button确实具有ExclusiveGroup属性http://doc.qt.io/qt-5/qml-qtquick-controls-button.html#exclusiveGroup-prop。 但是,当我运行示例时,出现此错误:

1
qrc:/main.qml:48 Cannot assign to non-existent property"exclusiveGroup"

将鼠标悬停在" exclusiveGroup"上会显示一个工具提示:"无效的属性名称ExclusiveGroup"。

我已经安装了Qt 5.9.1。 这是我的导入语句:

1
2
3
4
5
import QtQuick 2.7
import QtQuick.Controls 1.4
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2

我究竟做错了什么?

谢谢


您出现问题的原因是:

1
2
import QtQuick.Controls 1.4
import QtQuick.Controls 2.0

两者都具有Button,但是它们具有不同的API。
因此,首先从QtQuick.Controls 1.4导入Button。 然后从QtQuick.Controls 2.0导入Button。 由于QML不知道,您要使用哪一个,您将导入最后一个。 如果要更具体地指定要使用的Button,可以使用命名导入

1
2
import QtQuick.Controls 1.4 as OldCtrl
import QtQuick.Controls 2.0 as NewCtrl

然后,您可以根据需要在两个版本中使用Button

1
2
OldCtrl.Button { // from the QtQuick.Controls 1.4 }
NewCtrl.Button { // from the QtQuick.Controls 2.0 }

您引用的文档是针对QtQuick.Controls 1.x的,并且从此处导入的ExclusiveGroup。 因此,您正在尝试混合使用两个库中的内容,而这两个库将无法一起工作。

有关QtQuick.Controls 2.x的类似解决方案,请参见ButtonGroup

有关这两组控件的区别和用例的更多信息,请阅读:

  • http://blog.qt.io/blog/2016/06/10/qt-quick-controls-2-0-a-new-beginning/
  • https://doc.qt.io/qt-5/qtquickcontrols2-differences.html