qt-Quick3D笔记之官方例程Runtimeloader Example运行笔记

embedded/2025/2/2 14:15:44/

qtQuick3DRuntimeloader_Example_0">qt-Quick3D笔记之官方例程Runtimeloader Example运行笔记

文章目录

  • qt-Quick3D笔记之官方例程Runtimeloader Example运行笔记
    • 1.例程运行效果
    • 2.例程缩略图
    • 3.项目文件列表
    • 4.main.qml
    • 5.main.cpp
    • 6.CMakeLists.txt

1.例程运行效果

在这里插入图片描述

运行该项目需要自己准备一个模型文件

2.例程缩略图

3ddb68dc.png#pic_center" alt="在这里插入图片描述" width="300" />

3.项目文件列表

runtimeloader/
├── CMakeLists.txt
├── main.cpp
├── main.qml
├── qml.qrc
└── runtimeloader.pro1 directory, 5 files

4.main.qml

// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clauseimport QtQuick
import QtQuick.Window
import QtQuick.Controls
import QtQuick.Layoutsimport Qt.labs.platform
import QtCoreimport QtQuick3D
import QtQuick3D.Helpers
import QtQuick3D.AssetUtils// 创建一个窗口根节点,设置窗口大小和显示状态
Window {id: windowRootvisible: truewidth: 1280height: 720property url importUrl; // 用于导入模型的URL//! [base scene] 基础场景View3D {id: view3Danchors.fill: parent // 填充父窗口environment: SceneEnvironment {id: envbackgroundMode: SceneEnvironment.SkyBox // 背景模式为天空盒lightProbe: Texture {textureData: ProceduralSkyTextureData{} // 使用程序化天空纹理}InfiniteGrid {visible: helper.gridEnabled // 是否显示网格gridInterval: helper.gridInterval // 网格间隔}}camera: helper.orbitControllerEnabled ? orbitCamera : wasdCamera // 根据控制器选择相机// 设置方向光源DirectionalLight {eulerRotation.x: -35eulerRotation.y: -90castsShadow: true // 启用阴影}Node {id: orbitCameraNodePerspectiveCamera {id: orbitCamera // 轨道相机}}// 第一人称相机(WASD控制)PerspectiveCamera {id: wasdCameraonPositionChanged: {// 更新相机的近远裁剪面let distance = position.length()if (distance < 1) {clipNear = 0.01clipFar = 100} else if (distance < 100) {clipNear = 0.1clipFar = 1000} else {clipNear = 1clipFar = 10000}}}//! [base scene]// 重置视图的函数function resetView() {if (importNode.status === RuntimeLoader.Success) {helper.resetController()}}//! [instancing] 实例化RandomInstancing {id: instancinginstanceCount: 30 // 设置实例数量position: InstanceRange {property alias boundsDiameter: helper.boundsDiameterfrom: Qt.vector3d(-3*boundsDiameter, -3*boundsDiameter, -3*boundsDiameter); // 位置范围to: Qt.vector3d(3*boundsDiameter, 3*boundsDiameter, 3*boundsDiameter)}color: InstanceRange { from: "black"; to: "white" } // 颜色范围}//! [instancing]QtObject {id: helperproperty real boundsDiameter: 0 // 场景边界的直径property vector3d boundsCenter // 场景中心property vector3d boundsSize // 场景大小property bool orbitControllerEnabled: true // 是否启用轨道控制器property bool gridEnabled: gridButton.checked // 是否启用网格property real cameraDistance: orbitControllerEnabled ? orbitCamera.z : wasdCamera.position.length() // 相机与中心的距离property real gridInterval: Math.pow(10, Math.round(Math.log10(cameraDistance)) - 1) // 网格间隔计算// 更新场景边界信息function updateBounds(bounds) {boundsSize = Qt.vector3d(bounds.maximum.x - bounds.minimum.x,bounds.maximum.y - bounds.minimum.y,bounds.maximum.z - bounds.minimum.z)boundsDiameter = Math.max(boundsSize.x, boundsSize.y, boundsSize.z)boundsCenter = Qt.vector3d((bounds.maximum.x + bounds.minimum.x) / 2,(bounds.maximum.y + bounds.minimum.y) / 2,(bounds.maximum.z + bounds.minimum.z) / 2 )wasdController.speed = boundsDiameter / 1000.0 // 更新控制器速度wasdController.shiftSpeed = 3 * wasdController.speedwasdCamera.clipNear = boundsDiameter / 100wasdCamera.clipFar = boundsDiameter * 10view3D.resetView() // 重置视图}// 重置控制器function resetController() {orbitCameraNode.eulerRotation = Qt.vector3d(0, 0, 0)orbitCameraNode.position = boundsCenterorbitCamera.position = Qt.vector3d(0, 0, 2 * helper.boundsDiameter)orbitCamera.eulerRotation = Qt.vector3d(0, 0, 0)orbitControllerEnabled = true}// 切换控制器function switchController(useOrbitController) {if (useOrbitController) {let wasdOffset = wasdCamera.position.minus(boundsCenter)let wasdDistance = wasdOffset.length()let wasdDistanceInPlane = Qt.vector3d(wasdOffset.x, 0, wasdOffset.z).length()let yAngle = Math.atan2(wasdOffset.x, wasdOffset.z) * 180 / Math.PIlet xAngle = -Math.atan2(wasdOffset.y, wasdDistanceInPlane) * 180 / Math.PIorbitCameraNode.position = boundsCenterorbitCameraNode.eulerRotation = Qt.vector3d(xAngle, yAngle, 0)orbitCamera.position = Qt.vector3d(0, 0, wasdDistance)orbitCamera.eulerRotation = Qt.vector3d(0, 0, 0)} else {wasdCamera.position = orbitCamera.scenePositionwasdCamera.rotation = orbitCamera.sceneRotationwasdController.focus = true}orbitControllerEnabled = useOrbitController}}//! [runtimeloader] 运行时加载器RuntimeLoader {id: importNodesource: windowRoot.importUrl // 导入模型的URLinstancing: instancingButton.checked ? instancing : null // 实例化开关onBoundsChanged: helper.updateBounds(bounds) // 更新场景边界}//! [runtimeloader]//! [bounds] 场景边界Model {parent: importNodesource: "#Cube" // 默认使用立方体模型materials: PrincipledMaterial {baseColor: "red" // 设置基础颜色为红色}opacity: 0.2 // 设置模型透明度visible: visualizeButton.checked && importNode.status === RuntimeLoader.Success // 根据条件显示模型position: helper.boundsCenterscale: Qt.vector3d(helper.boundsSize.x / 100,helper.boundsSize.y / 100,helper.boundsSize.z / 100)}//! [bounds]//! [status report] 状态报告Rectangle {id: messageBoxvisible: importNode.status !== RuntimeLoader.Success // 如果导入失败,显示错误消息color: "red"width: parent.width * 0.8height: parent.height * 0.8anchors.centerIn: parentradius: Math.min(width, height) / 10opacity: 0.6Text {anchors.fill: parentfont.pixelSize: 36text: "Status: " + importNode.errorString + "\nPress \"Import...\" to import a model" // 显示错误信息color: "white"wrapMode: Text.WraphorizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter}}//! [status report]}//! [camera control] 相机控制OrbitCameraController {id: orbitControllerorigin: orbitCameraNodecamera: orbitCameraenabled: helper.orbitControllerEnabled // 根据状态启用或禁用轨道控制器}WasdController {id: wasdControllercontrolledObject: wasdCameraenabled: !helper.orbitControllerEnabled // 根据状态启用或禁用WASD控制器}//! [camera control]// 界面控制面板Pane {width: parent.widthcontentHeight: controlsLayout.implicitHeightRowLayout {id: controlsLayoutButton {id: importButtontext: "Import..."onClicked: fileDialog.open() // 打开文件对话框focusPolicy: Qt.NoFocus}Button {id: resetButtontext: "Reset view"onClicked: view3D.resetView() // 重置视图focusPolicy: Qt.NoFocus}Button {id: visualizeButtoncheckable: truetext: "Visualize bounds" // 显示场景边界focusPolicy: Qt.NoFocus}Button {id: instancingButtoncheckable: truetext: "Instancing" // 开启实例化focusPolicy: Qt.NoFocus}Button {id: gridButtontext: "Show grid" // 显示网格focusPolicy: Qt.NoFocuscheckable: truechecked: false}Button {id: controllerButtontext: helper.orbitControllerEnabled ? "Orbit" : "WASD" // 切换控制器onClicked: helper.switchController(!helper.orbitControllerEnabled)focusPolicy: Qt.NoFocus}RowLayout {Label {text: "Material Override"}ComboBox {id: materialOverrideComboBoxtextRole: "text"valueRole: "value"implicitContentWidthPolicy: ComboBox.WidestTextonActivated: env.debugSettings.materialOverride = currentValue // 选择材质覆盖model: [{ value: DebugSettings.None, text: "None"},{ value: DebugSettings.BaseColor, text: "Base Color"},{ value: DebugSettings.Roughness, text: "Roughness"},{ value: DebugSettings.Metalness, text: "Metalness"},{ value: DebugSettings.Diffuse, text: "Diffuse"},{ value: DebugSettings.Specular, text: "Specular"},{ value: DebugSettings.ShadowOcclusion, text: "Shadow Occlusion"},{ value: DebugSettings.Emission, text: "Emission"},{ value: DebugSettings.AmbientOcclusion, text: "Ambient Occlusion"},{ value: DebugSettings.Normals, text: "Normals"},{ value: DebugSettings.Tangents, text: "Tangents"},{ value: DebugSettings.Binormals, text: "Binormals"},{ value: DebugSettings.F0, text: "F0"}]}}CheckBox {text: "Wireframe" // 启用或禁用线框模式checked: env.debugSettings.wireframeEnabledonCheckedChanged: {env.debugSettings.wireframeEnabled = checked}}}}// 文件对话框,允许用户选择glTF模型文件FileDialog {id: fileDialognameFilters: ["glTF files (*.gltf *.glb)", "All files (*)"]onAccepted: importUrl = file // 选择文件后导入Settings {id: fileDialogSettingscategory: "QtQuick3D.Examples.RuntimeLoader"property alias folder: fileDialog.folder}}// 调试视图切换按钮Item {width: debugViewToggleText.implicitWidthheight: debugViewToggleText.implicitHeightanchors.right: parent.rightLabel {id: debugViewToggleTexttext: "Click here " + (dbg.visible ? "to hide DebugView" : "for DebugView")anchors.right: parent.rightanchors.top: parent.top}MouseArea {anchors.fill: parentonClicked: dbg.visible = !dbg.visible // 切换调试视图可见性DebugView {y: debugViewToggleText.height * 2anchors.right: parent.rightsource: view3Did: dbgvisible: false}}}
}

5.main.cpp

// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#ifdef HAS_MODULE_QT_WIDGETS
# include <QApplication>
#endif
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include <QtQuick3D/qquick3d.h>int main(int argc, char *argv[])
{
#ifdef HAS_MODULE_QT_WIDGETSQApplication app(argc, argv);
#elseQGuiApplication app(argc, argv);
#endifapp.setOrganizationName("The Qt Company");app.setOrganizationDomain("qt.io");app.setApplicationName("Runtime Asset Loading Example");const auto importUrl = argc > 1 ? QUrl::fromLocalFile(argv[1]) : QUrl{};if (importUrl.isValid())qDebug() << "Importing" << importUrl;QSurfaceFormat::setDefaultFormat(QQuick3D::idealSurfaceFormat(4));QQmlApplicationEngine engine;const QUrl url(QStringLiteral("qrc:/main.qml"));engine.load(url);if (engine.rootObjects().isEmpty()) {qWarning() << "Could not find root object in" << url;return -1;}QObject *topLevel = engine.rootObjects().value(0);QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);if (window)window->setProperty("importUrl", importUrl);return app.exec();
}

6.CMakeLists.txt

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clausecmake_minimum_required(VERSION 3.16)
project(runtimeloader LANGUAGES CXX)set(CMAKE_AUTOMOC ON)find_package(Qt6 REQUIRED COMPONENTS Core Gui Quick Quick3D Widgets)qt_add_executable(runtimeloadermain.cpp
)set_target_properties(runtimeloader PROPERTIESWIN32_EXECUTABLE TRUEMACOSX_BUNDLE TRUE
)target_link_libraries(runtimeloader PUBLICQt::CoreQt::GuiQt::QuickQt::Quick3D
)if(TARGET Qt::Widgets)target_compile_definitions(runtimeloader PUBLICHAS_MODULE_QT_WIDGETS)target_link_libraries(runtimeloader PUBLICQt::Widgets)
endif()qt_add_qml_module(runtimeloaderURI ExampleVERSION 1.0QML_FILES main.qmlNO_RESOURCE_TARGET_PATH
)install(TARGETS runtimeloaderBUNDLE  DESTINATION .RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)qt_generate_deploy_qml_app_script(TARGET runtimeloaderOUTPUT_SCRIPT deploy_scriptMACOS_BUNDLE_POST_BUILDNO_UNSUPPORTED_PLATFORM_ERRORDEPLOY_USER_QML_MODULES_ON_UNSUPPORTED_PLATFORM
)
install(SCRIPT ${deploy_script})

http://www.ppmy.cn/embedded/158918.html

相关文章

《苍穹外卖》项目学习记录-Day10Spring Task

1.超时订单如何处理&#xff1f; 如果用户下单后一直不支付&#xff0c;那这个订单就会超时&#xff0c;因为我们这里限制了用户必须在15分钟之内完成支付。如果他下单之后超过15分钟还不支付&#xff0c;那这个订单我们就会给它判定成超时订单。我们的业务规则就是&#xff0…

浅析DNS污染及防范

DNS污染&#xff08;DNS Cache Poisoning&#xff09;是一种网络攻击手段&#xff0c;通过篡改DNS服务器的缓存数据&#xff0c;将域名解析结果指向错误的IP地址&#xff0c;从而误导用户访问恶意网站或无法访问目标网站。这种攻击利用了DNS协议的特性&#xff0c;例如“只认第…

谈谈你所了解的AR技术吧!

深入探讨 AR 技术的原理与应用 在科技飞速发展的今天&#xff0c;AR&#xff08;增强现实&#xff09;技术已经悄然改变了我们与周围世界互动的方式。你是否曾想象过如何能够通过手机屏幕与虚拟物体进行实时互动&#xff1f;在这篇文章中&#xff0c;我们将深入探讨AR技术的原…

Shell特殊状态变量以及常用内置变量总结

目录 1. 特殊的状态变量 1.1 $?&#xff08;上一个命令的退出状态&#xff09; 1.2 $$&#xff08;当前进程的 PID&#xff09; 1.3 $!&#xff08;后台进程的 PID&#xff09; 1.4 $_&#xff08;上一条命令的最后一个参数&#xff09; 2.常用shell内置变量 2.1 echo&…

Sui 年度展望:2025 是走向主流的一年,将 Sui 打造成体验最友好的平台

作者&#xff1a;Adeniyi.sui 编译&#xff1a;深潮 TechFlow Mysten Labs 正与 CarnegieMellon &#xff08;卡内基梅隆大学&#xff09;的研究人员紧密合作&#xff0c;共同开发和优化可编程的点对点 (P2P) 隧道。这项技术将为区块链的应用场景带来更多可能性。 展望 2025…

【BQ3568HM开发板】智能家居中控屏界面设计:打造便捷的家居控制体验

目录 引言 一、界面布局与组件设计 1. 整体布局 2. 温度和湿度信息展示 3. 灯光和窗帘控制按钮 二、界面交互设计 1. 按钮点击事件 2. 按钮状态变化 三、界面样式设计 1. 文字样式 2. 按钮样式 结语 本文首发于电子发烧友论坛&#xff1a;https://bbs.elecfans.com/…

Hive:窗口函数[ntile, first_value,row_number() ,rank(),dens_rank()]和自定义函数

ntile 分组 它把有序的数据集合 平均分配 到 指定的数量&#xff08;num &#xff09;个桶中 , 将桶号分配给每一行。如果不能平均分配&#xff0c;则优先分配较小编号的桶&#xff0c;并且各个桶中能放的行数最多相差1。 被称作窗口函数、序列函数或分析函数, 本质上是一种…

SSM开发(六) SSM整合下的CURD增删改查操作(IDEA版)

目录 一、Mybatis实现增删改查操作(注解版) 1、User实体 2、Mybatis实现增删改查操作(注解版) ①增加 ②删除 ③修改 ④查询 ⑤查询操作where语句中含like 3、service层调用 二、Mybatis实现增删改查操作(XML版) 1、实体定义 2、Mybatis实现增删改查操作(XML版) ①…