本页内容

QML 应用程序权限

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

该 Qt Qml Core 模块通过一组权限类型,将 Qt C++应用程序权限功能提供给 Qml,这些类型可用于以跨平台的方式检查或请求权限。

BluetoothPermission

访问用户的蓝牙外设

CalendarPermission

访问用户的日历

CameraPermission

访问用户的摄像头

ContactsPermission

访问用户的联系人

LocationPermission

访问用户的位置

MicrophonePermission

访问用户的麦克风

注意: 可用的权限类型 涵盖了Qt Multimedia 和Qt Positioning 等Qt模块的核心功能,但并不包含所有平台特有的权限。目前不支持自定义权限类型。

用法

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

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 ”,例如当权限在初次请求后无法升级时。

所有这些状态都应促使应用程序的用户界面(UI)切换至相应的状态,向用户告知新状态,并允许用户在可能的情况下请求新权限,或恢复为范围较小的权限。

权限项之间的交互

尽管权限状态最终与底层应用程序相关联,但每个权限项都会独立于所有其他项报告其自身状态,并在需要时需要独立请求。

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

© 2026 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.