)
Qt是目前最先进、最完整的跨平台C开发工具。它不仅完全实现了一次编写所有平台无差别运行更提供了几乎所有开发过程中需要用到的工具。如今Qt已被运用于超过70个行业、数千家企业支持数百万设备及应用。本教程介绍了在使用Qt 6作为最低Qt版本并使用CMake作为构建系统时如何使用Qt Creator开发适用于Android和iOS设备的Qt Quick应用程序。添加图像作为资源当您倾斜设备时应用程序的主视图会显示一个 SVG 气泡图像该图像会在屏幕上移动。我们在本教程中使用 Bluebubble.svg但您可以使用任何其他图像或组件来代替。要在运行应用程序时显示图像您必须在向导为您创建的 CMakeLists.txt 文件的 RESOURCES 部分中将其指定为资源qt_add_qml_module(appaccelbubble URI accelbubble VERSION 1.0 QML_FILES main.qml RESOURCES Bluebubble.svg )创建 Accelbubble 主视图我们通过添加一个以 Bluebubble.svg 作为源的 Image 组件在 main.qml 文件中创建主视图Image { id: bubble source: Bluebubble.svg smooth: true接下来我们添加自定义属性以根据主窗口的宽度和高度定位图像property real centerX: mainWindow.width / 2 property real centerY: mainWindow.height / 2 property real bubbleCenter: bubble.width / 2 x: centerX - bubbleCenter y: centerY - bubbleCenter我们现在要添加代码以根据加速度计传感器值移动气泡。 首先我们添加以下导入语句import QtSensors接下来我们添加具有必要属性的 Accelerometer 组件Accelerometer { id: accel dataRate: 100 active:true然后我们添加以下 JavaScript 函数这些函数根据当前的 Accelerometer 值计算气泡的 x 和 y 位置function calcPitch(x,y,z) { return -Math.atan2(y, Math.hypot(x, z)) * mainWindow.radians_to_degrees; } function calcRoll(x,y,z) { return -Math.atan2(x, Math.hypot(y, z)) * mainWindow.radians_to_degrees; }我们为 Accelerometer 组件的 onReadingChanged 信号添加以下 JavaScript 代码以使气泡在 Accelerometer 值发生变化时移动onReadingChanged: { var newX (bubble.x calcRoll(accel.reading.x, accel.reading.y, accel.reading.z) * .1) var newY (bubble.y - calcPitch(accel.reading.x, accel.reading.y, accel.reading.z) * .1) if (isNaN(newX) || isNaN(newY)) return; if (newX 0) newX 0 if (newX mainWindow.width - bubble.width) newX mainWindow.width - bubble.width if (newY 18) newY 18 if (newY mainWindow.height - bubble.height) newY mainWindow.height - bubble.height bubble.x newX bubble.y newY }我们要确保气泡的位置始终在屏幕范围内如果加速度计返回的不是数字 (NaN)则忽略该值并且不更新气泡位置。我们在气泡的 x 和 y 属性上添加 SmoothedAnimation 操作使其运动看起来更平滑。Behavior on y { SmoothedAnimation { easing.type: Easing.Linear duration: 100 } } Behavior on x { SmoothedAnimation { easing.type: Easing.Linear duration: 100 } }