传感器展示
“传感器展示”示例通过可视化示例演示了传感器的使用方法。

概述
启动时,应用程序会显示一个菜单,其中包含各传感器子视图的按钮。传感器视图会实例化指定的传感器,以数字形式显示传感器的数值,并通过简单的图形表示进行可视化展示。
主菜单
主视图显示包含应用程序名称的标题,以及通过ColumnLayout 均匀排列的各个子视图按钮。StackView 负责管理子视图与主菜单之间的导航。应用程序在启动时会检查传感器的可用性,并禁用不可用传感器的按钮。
注意:为 简化示例,传感器可用性仅在启动时检查一次。
加速度计视图
加速度计视图显示设备的当前加速度值,并使图像以与设备加速度方向相反的幅度移动,从而使图像产生一种与设备运动成正比的惯性效果。
图像的平移操作在加速度计的onReadingChanged 方法中实现。
Accelerometer {
id: accelerometer
property real x: 0
property real y: 0
property real z: 0
active: true
dataRate: 25
onReadingChanged: {
x = (reading as AccelerometerReading).x
y = (reading as AccelerometerReading).y
z = (reading as AccelerometerReading).z
imageTranslation.x = -x * 10
imageTranslation.y = y * 10
}
}每当有新的加速度计值时,图像平移坐标就会相应地更新。
接近传感器视图
接近传感器视图显示一张图像,当设备的接近传感器被遮挡时,该图像会放大。
指南针视图
指南针视图显示一张指南针图像,该图像会根据指南针传感器的读数值进行旋转,使指南针指向北方。
磁力计视图
磁强计视图会显示一个磁铁图像,其旋转角度由磁强计 x 和 y 轴的读数所构成的向量旋转角度决定。这通常会产生与指南针相同的旋转效果,展示了磁强计读数的一种应用场景。 由于磁强计提供沿三个轴的读数,因此在这些读数的应用方面具有更大的灵活性。
Magnetometer {
id: magnetometer
active: true
dataRate: 25
onReadingChanged: {
root.magnetometerX = (reading as MagnetometerReading).x
root.magnetometerY = (reading as MagnetometerReading).y
root.magnetometerZ = (reading as MagnetometerReading).z
root.magnetRotation =
((Math.atan2(root.magnetometerX, root.magnetometerY) / Math.PI) * 180)
}
}陀螺仪视图

陀螺仪视图同样显示一张图像,该图像围绕三个轴旋转,旋转幅度由陀螺仪读数计算得出。 由于陀螺仪提供围绕三个空间轴的相对旋转变化,且读数更新之间的时间间隔可能不同,因此会存储读数的时间戳,并根据读数更新之间经过的时间对旋转变化进行归一化处理。
Gyroscope {
id: gyroscope
property var lastTimeStamp: 0
property real x: 0
property real y: 0
property real z: 0
active: true
dataRate: 25
onReadingChanged: {
x = (reading as GyroscopeReading).x
y = (reading as GyroscopeReading).y
z = (reading as GyroscopeReading).z
let firstCall = false
if (lastTimeStamp == 0) {
firstCall = true
}
let timeSinceLast = reading.timestamp - lastTimeStamp
lastTimeStamp = reading.timestamp
//Skipping the initial time jump from 0
if (firstCall === true)
return
let normalizedX = x * (timeSinceLast / 1000000)
imageXRotation.angle += normalizedX
let normalizedY = y * (timeSinceLast / 1000000)
imageYRotation.angle -= normalizedY
let normalizedZ = z * (timeSinceLast / 1000000)
imageZRotation.angle += normalizedZ
}
}按下重置按钮,图像旋转将重置为 0。
© 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.