QML 应用程序权限

当今设备和操作系统的许多功能如果被滥用,会对隐私、安全和性能产生重大影响。因此,越来越多的平台在访问这些功能前要求用户明确同意。

Qt Qml Core模块通过一组权限类型将 Qt C++Application Permissions功能暴露给 QML,这些权限类型可用于以跨平台方式检查或请求权限。

BluetoothPermission

访问用户的蓝牙外设

CalendarPermission

访问用户的日历

CameraPermission

访问用户的摄像头

ContactsPermission

访问用户的联系人

LocationPermission

访问用户位置

MicrophonePermission

访问用户的麦克风

使用方法

要在应用程序中检查和请求特定权限,请包含相应权限类型的实例,并根据需要设置其属性:

CalendarPermission {
    id: calendarPermission
    accessMode: CalendarPermission.ReadWrite
}

该类型可用于检查权限的当前状态,例如驱动基于状态的用户界面:

states: [
    State {
        name: "waitingForPermission"
        when: calendarPermission.status == Qt.PermissionStatus.Undetermined
        PropertyChanges { target: permissionRequestItem; visible: true }
    },
    State {
        name: "permissionDenied"
        when: calendarPermission.status == Qt.PermissionStatus.Denied
        PropertyChanges { target: permissionDeniedItem; visible: true }
    }
]

在上面的示例中,如果权限状态为未授予,则会叠加两个权限特定项。请求用户界面可能会如下所示

Rectangle {
    id: permissionRequestItem
    anchors.fill: parent
    visible: false

    Text {
        anchors.centerIn: parent
        text: qsTr("We need your permission to access the calendar."
            + "Please tap this screen to request permission.")

    }

    MouseArea {
        anchors.fill: parent
        onClicked: calendarPermission.request()
    }
}

相应的拒绝用户界面:

Rectangle {
    id: permissionDeniedItem
    anchors.fill: parent
    color: "red"
    visible: false
    Text {
        anchors.centerIn: parent
        text: qsTr("We need your permission to access the calendar,"
            + "but permission was not granted. Please resolve.")
    }
}

更改权限属性

即使在请求启动后,也可以通过调用 `request()`来更改权限的属性。如果新的属性值导致状态发生变化,则会更新状态,但不会导致使用新属性集的自动请求。

例如,如果将访问模式Qt.CalendarPermission.ReadOnly 已授予的日历权限升级为Qt.CalendarPermission.ReadWrite ,平台将以三种方式之一做出响应:

  • 隐式授予扩展权限,例如,由于平台不区分两种访问模式,因此不会导致状态改变。
  • 将状态移回 "未确定",以便再次咨询用户是否可以访问现在的扩展权限。
  • 将状态移至Denied ,例如,如果最初申请的权限无法升级。

所有这些状态都会使应用程序的用户界面进入相应的状态,用户会被告知新的状态,如果可能,可以申请新的权限,或者恢复到范围较小的权限。

权限项目之间的交互

虽然权限状态最终与底层应用程序相关联,但每个权限项目都会独立于所有其他项目报告自己的状态,如有需要,也需要独立申请。

例如,请求一个项目的日历访问权限不会更新另一个CalendarPermission 项目的状态,即使这些项目具有完全相同的属性。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.