Qt Quick 3D - 挑拣示例

演示拾取模型。

本例演示了拾取。有 3 个不同的动画模型可供选择。当选中一个模型时,动画会停止,模型的颜色也会改变,以显示选中的模型。拾取结果的详细信息将显示在应用程序窗口的顶部。

使模型可拾取

要使模型可拾取,需要将pickable 属性设置为true 。我们还为模型添加了objectName ,以便能够显示被拾取模型的名称。

Model {
    id: cubeModel
    objectName: "Cube"
    source: "#Cube"
    pickable: true
    property bool isPicked: false

添加isPicked 属性可用于切换动画和颜色。

materials: PrincipledMaterial {
    baseColor: cubeModel.isPicked ? "#41cd52" : "#09102b"
    ...
SequentialAnimation on eulerRotation {
    running: !cubeModel.isPicked

获取选取结果

为了进行实际的挑选,我们需要添加一个MouseArea ,以覆盖整个View3D

MouseArea {
    anchors.fill: view

在鼠标区域的onClicked 处理程序中,我们使用pick 方法来获取实际的选取结果。

var result = view.pick(mouse.x, mouse.y);

如果结果是target object ,我们就会查看结果的具体细节,并将其显示在应用程序视图顶部的文本字段中。

if (result.objectHit) {
    var pickedObject = result.objectHit;
    // Toggle the isPicked property for the model
    pickedObject.isPicked = !pickedObject.isPicked;
    // Get picked model name
    pickName.text = pickedObject.objectName;
    // Get other pick specifics
    uvPosition.text = "("
            + result.uvPosition.x.toFixed(2) + ", "
            + result.uvPosition.y.toFixed(2) + ")";
    distance.text = result.distance.toFixed(2);
    scenePosition.text = "("
            + result.scenePosition.x.toFixed(2) + ", "
            + result.scenePosition.y.toFixed(2) + ", "
            + result.scenePosition.z.toFixed(2) + ")";
    localPosition.text = "("
            + result.position.x.toFixed(2) + ", "
            + result.position.y.toFixed(2) + ", "
            + result.position.z.toFixed(2) + ")";
    worldNormal.text = "("
            + result.sceneNormal.x.toFixed(2) + ", "
            + result.sceneNormal.y.toFixed(2) + ", "
            + result.sceneNormal.z.toFixed(2) + ")";
    localNormal.text = "("
            + result.normal.x.toFixed(2) + ", "
            + result.normal.y.toFixed(2) + ", "
            + result.normal.z.toFixed(2) + ")";

示例项目 @ code.qt.io

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