Qt 3D 实战|三维场景搭建、三维模型加载与显示
·
一、Qt 3D 简介
Qt 3D 是 Qt 官方三维图形框架,分为 C++ API 和 QML API,基于 OpenGL 渲染,支持:
- 基础 3D 场景、相机、光源、材质
- 加载
.obj、.mtl等通用三维模型 - 模型旋转、平移、缩放、视角交互
- 适合工业仿真、可视化、虚拟展示、嵌入式 3D 界面
模块依赖
- qmake(.pro)
pro
QT += 3dcore 3drender 3dinput 3dextras
- CMake
cmake
find_package(Qt6 REQUIRED COMPONENTS 3DCore 3DRender 3DInput 3DExtras)
target_link_libraries(App PRIVATE Qt6::3DCore Qt6::3DRender Qt6::3DInput Qt6::3DExtras)
推荐优先使用 QML + Qt 3D,开发效率更高、交互更流畅。
二、Qt 3D 核心四大组件
- 场景根节点 (Entity):所有 3D 对象的父容器
- 相机 (Camera):观察者视角,控制视野、远近、位置
- 光源 (Light):环境光、方向光、点光源,决定模型明暗
- 渲染 / 材质 (Material):模型表面颜色、纹理、反光
三、示例 1:基础 3D 几何体(立方体 / 球体)
qml
import QtQuick 2.15
import QtQuick.Window 2.15
import Qt3D.Core 2.15
import Qt3D.Render 2.15
import Qt3D.Input 2.15
import Qt3D.Extras 2.15
Window {
width: 800
height: 600
visible: true
title: "Qt3D 基础几何体"
// 3D 场景视图
View3D {
anchors.fill: parent
// 轨道相机:支持鼠标拖拽旋转、滚轮缩放
OrbitCameraController {
camera: mainCamera
}
// 场景根实体
Entity {
// 相机
PerspectiveCamera {
id: mainCamera
position: Qt.vector3D(0, 0, 10)
fieldOfView: 45
nearPlane: 0.1
farPlane: 1000
}
// 方向光源
DirectionalLight {
worldDirection: Qt.vector3D(-1, -1, -1)
intensity: 1.0
}
// 立方体模型
Entity {
CuboidMesh {}
PhongMaterial { diffuse: "skyblue" }
Transform { translation: Qt.vector3D(-2, 0, 0) }
}
// 球体模型
Entity {
SphereMesh { radius: 1.5 }
PhongMaterial { diffuse: "orange" }
Transform { translation: Qt.vector3D(2, 0, 0) }
}
}
}
}
操作说明
- 鼠标左键拖拽:旋转视角
- 鼠标滚轮:缩放远近
- 鼠标右键拖拽:平移场景
四、示例 2:加载外部 3D 模型(OBJ 格式)
工业 / 可视化常用格式为 OBJ + MTL,Qt 3D 原生支持。
1. 模型文件说明
将 model.obj、model.mtl、贴图文件放入 Qt 资源 qrc。
2. QML 加载模型代码
qml
import QtQuick 2.15
import QtQuick.Window 2.15
import Qt3D.Core 2.15
import Qt3D.Render 2.15
import Qt3D.Input 2.15
import Qt3D.Extras 2.15
Window {
width: 800
height: 600
visible: true
View3D {
anchors.fill: parent
OrbitCameraController { camera: cam }
Entity {
PerspectiveCamera {
id: cam
position: Qt.vector3D(0, 3, 8)
}
DirectionalLight {
worldDirection: Qt.vector3D(0, -1, -1)
intensity: 1.2
}
// 加载外部 OBJ 模型
Entity {
id: objModel
// 模型网格
Mesh {
source: "qrc:/3d/model.obj"
}
// 位置、旋转、缩放
Transform {
translation: Qt.vector3D(0, 0, 0)
scale: 1.0
}
}
}
}
}
五、模型动态控制(旋转 / 平移)
结合属性动画实现模型自动旋转:
qml
// 在模型 Entity 内添加
Transform {
id: modelTrans
rotation: fromAxisAndAngle(Qt.vector3D(0,1,0), 0)
PropertyAnimation on rotation {
loops: Animation.Infinite
duration: 10000
from: fromAxisAndAngle(Qt.vector3D(0,1,0), 0)
to: fromAxisAndAngle(Qt.vector3D(0,1,0), 360)
}
}
六、常见问题与优化
- 模型黑屏 / 看不见
- 相机位置过近 / 过远,调整
camera.position - 缺少光源,必须添加
DirectionalLight/PointLight
- 相机位置过近 / 过远,调整
- 模型加载失败
- 路径错误、OBJ/MTL 文件损坏、贴图路径不匹配
- 卡顿、帧率低
- 简化模型面数,嵌入式设备慎用高精度模型
- 关闭多余光源、降低渲染采样
- 不支持 FBX 格式Qt3D 原生不支持 FBX,先用 3D 建模软件转为 OBJ。
小结
Qt 3D 开发流程:搭建 View3D + 相机 + 光源 → 内置几何体 / 外部 OBJ 模型 → 材质与变换 → 交互与动画。QML 版本上手简单,适合快速做 3D 可视化界面。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)