Qt Quick 3D - 运行时加载器示例

演示如何在运行时加载资产。

该示例展示了如何使用RuntimeLoader 实现一个简单的资产查看器。

有关如何设置基本场景的说明,请参阅介绍性示例文档。设置好场景后,我们就可以添加RuntimeLoader 项目:

RuntimeLoader {
    id: importNode
    source: windowRoot.importUrl
    instancing: instancingButton.checked ? instancing : null
    onBoundsChanged: helper.updateBounds(bounds)
}

通过设置RuntimeLoadersource 属性来加载资产。在本例中,sourceimportUrl 绑定,当用户在文件对话框中选择文件时, 将发生变化。

假设资产可以加载,内容将作为RuntimeLoader importNode 的子内容创建。请注意,RuntimeLoaderNode 类型,由于它也是加载资产的根节点,因此应用于importNode 的任何转换也会影响其子节点。

错误处理

如果资产加载失败,RuntimeLoaderstatus 属性将被设置为Error 。然后可以查询RuntimeLoadererrorString ,以获得更详细的错误说明。

在本示例中,我们将在屏幕中间的红色信息框中显示错误信息,就像这样:

Rectangle {
    id: messageBox
    visible: importNode.status !== RuntimeLoader.Success
    color: "red"
    width: parent.width * 0.8
    height: parent.height * 0.8
    anchors.centerIn: parent
    radius: Math.min(width, height) / 10
    opacity: 0.6
    Text {
        anchors.fill: parent
        font.pixelSize: 36
        text: "Status: " + importNode.errorString + "\nPress \"Import...\" to import a model"
        color: "white"
        wrapMode: Text.Wrap
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
    }
}
移动摄像机

为了改变摄像头的位置,我们使用Helpers 模块中的WasdController 并将其绑定到摄像头上,如下图所示:

OrbitCameraController {
    id: orbitController
    origin: orbitCameraNode
    camera: orbitCamera
    enabled: helper.orbitControllerEnabled
}
WasdController {
    id: wasdController
    controlledObject: wasdCamera
    enabled: !helper.orbitControllerEnabled
}

除了WasdController 之外,该示例还使用了WheelHandlerPointerHandler 来缩放和旋转模型。

实例化

RuntimeLoader 项还可以与实例化结合使用,如图所示:

RandomInstancing {
    id: instancing
    instanceCount: 30
    position: InstanceRange {
        property alias boundsDiameter: helper.boundsDiameter
        from: Qt.vector3d(-3*boundsDiameter, -3*boundsDiameter, -3*boundsDiameter);
        to: Qt.vector3d(3*boundsDiameter, 3*boundsDiameter, 3*boundsDiameter)
    }
    color: InstanceRange { from: "black"; to: "white" }
}

RuntimeLoader 虽然它不是从模型继承而来,但它有自己的 属性,这使我们可以将复杂的导入资产实例化,就好像它是一个简单的模型一样。在本例中,我们使用 模块中的 组件在固定区域内以随机颜色随机定位项目。instancing Helpers RandomInstancing

材质重写

在加载资产时,有时可能会出现与预期不符的情况。materialOverride 属性将改变场景中每个材质的渲染方式,以显示对整体渲染的特定贡献。这有助于确定资产的哪些部分不正确,以便在必要时调整原始资产。

示例项目 @ 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.