Qt Quick 3D - XR 简单触摸示例
演示了在Qt Quick 3D Xr 中使用手部追踪输入。

本示例展示了如何使用Qt Quick 3D Xr 中的手部追踪 API 与场景中的 2D 和 3D 对象进行交互。它遵循xr_simple示例的基本结构。
首先,我们创建一个可重用的组件TouchHand ,该组件封装了每只手所需的所有逻辑。
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
import QtQuick
import QtQuick3D
import QtQuick3D.Xr
Node {
id: root
property color color: "#ddaa88"
required property int touchId
required property int hand
required property XrView view
property alias touchPosition: handController.scenePos
property bool touchActive: false
XrController {
id: handController
controller: root.hand
property vector3d scenePos: view.xrOrigin.mapPositionToScene(pokePosition)
onScenePosChanged: {
const touchOffset = view.processTouch(scenePos, root.touchId)
handModel.position = touchOffset
const touchState = view.touchpointState(root.touchId)
const gadget = touchState.model as XrGadget
if (gadget) {
gadget.handleTouch(touchState.uvPosition, root.touchId, touchState.pressed)
}
}
}
XrHandModel {
id: handModel
hand: root.hand
materials: PrincipledMaterial {
baseColor: root.color
roughness: 0.5
}
}
}该组件包含一个 `XrController`,用于获取食指的 3D 位置,以及一个 `XrHandModel ` 来显示手的位置。`onTouchPositionChanged ` 处理程序正是实现核心功能的关键。我们调用 `XrView.processTouch()` 方法,该方法承担了主要工作:它尝试将 3D 触摸位置映射到 `XrItem ` 上的 2D 位置,并在找到对象时发送触摸事件。 随后,它会返回从 3D 位置到 2D 表面触点之间的偏移量。接着,我们利用该偏移量来调整 `XrHandModel` 的位置,从而营造出手被表面阻挡的视觉效果。
注意:此 效果在 Apple Vision Pro 上无法实现,因为该系统会显示用户的真实双手,而不会显示“XrHandModel ”。
我们在“XrOrigin ”内部创建两个“TouchHand”组件的实例,分别对应左右手:
XrOrigin {
id: theOrigin
z: 50
TouchHand {
id: rightHandModel
hand: XrHandModel.RightHand
view: xrView
touchId: 0
onTouchPositionChanged: buttons.handleTouch(touchPosition)
}
TouchHand {
id: leftHandModel
hand: XrHandModel.LeftHand
view: xrView
touchId: 1
onTouchPositionChanged: buttons.handleTouch(touchPosition)
}
}
xrOrigin: theOrigin此处的buttons 是一组带有handleTouch 函数的3D按钮。(该实现并非XR专属,因此此处不作详细说明。)
我们将XrOrigin 定位在距离场景原点50厘米处,这应是一个舒适的触摸距离。
场景的其余部分包含一些 3D 模型以及一个可响应触摸事件的XrItem 。
© 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.