Qt Quick 提供了强大的 3D 功能支持,主要通过 Qt 3D 模块实现。以下是 QML 中开发 3D 应用的全面指南。
1. 基本配置
环境要求
Qt 5.10 或更高版本(推荐 Qt 6.x)
启用 Qt 3D 模块
支持 OpenGL 的硬件
项目配置
在 .pro
文件中添加:
QT += 3dcore 3drender 3dinput 3dextras 3dquick
2. 核心组件
基本结构
qml
import Qt3D.Core 2.15
import Qt3D.Render 2.15
import Qt3D.Extras 2.15
Entity {
id: sceneRoot
components: [
RenderSettings {
activeFrameGraph: ForwardRenderer {
clearColor: "black"
camera: camera
}
}
]
// 相机配置
Camera {
id: camera
position: Qt.vector3d(0, 0, 10)
viewCenter: Qt.vector3d(0, 0, 0)
}
// 3D内容放在这里
FirstPersonCameraController { camera: camera }
}
常用属性
核心组件属性
Entity (Qt3D.Core)
属性/方法 |
类型 |
说明 |
components |
list<Component3D> |
实体包含的组件列表 |
enabled |
bool |
是否启用实体(默认true) |
parent |
Entity |
父实体(用于构建场景层次) |
Transform (Qt3D.Core)
属性/方法 |
类型 |
说明 |
translation |
vector3d |
位置坐标(x,y,z) |
rotation |
quaternion |
四元数旋转 |
rotationX |
real |
X轴旋转角度(度) |
rotationY |
real |
Y轴旋转角度(度) |
rotationZ |
real |
Z轴旋转角度(度) |
scale |
real |
统一缩放因子 |
scale3D |
vector3d |
各轴独立缩放(x,y,z) |
渲染相关
Camera (Qt3D.Render)
属性/方法 |
类型 |
说明 |
position |
vector3d |
相机位置 |
viewCenter |
vector3d |
观察中心点 |
upVector |
vector3d |
相机的上向量(默认0,1,0) |
fieldOfView |
real |
视野角度(度) |
nearPlane |
real |
近裁剪面距离 |
farPlane |
real |
远裁剪面距离 |
projectionType |
enum |
投影类型(Orthographic/Perspective) |
aspectRatio |
real |
宽高比(自动计算) |
Material (Qt3D.Extras)
属性/方法 |
类型 |
说明 |
ambient |
color |
环境光颜色 |
diffuse |
color |
漫反射颜色 |
specular |
color |
镜面反射颜色 |
shininess |
real |
高光强度(0-100) |
alpha |
real |
透明度(0-1) |
几何体属性
通用Mesh属性 (Qt3D.Extras)
属性/方法 |
类型 |
说明 |
radius |
real |
球体/环体的半径 |
length |
real |
立方体长度 |
width |
real |
立方体宽度 |
height |
real |
立方体高度 |
rings |
int |
球体经线分段数 |
slices |
int |
球体纬线分段数 |
光源属性
通用Light属性 (Qt3D.Render)
属性/方法 |
类型 |
说明 |
color |
color |
光源颜色 |
intensity |
real |
光照强度 |
enabled |
bool |
是否启用光源 |
PointLight特有
属性/方法 |
类型 |
说明 |
constantAttenuation |
real |
恒定衰减 |
linearAttenuation |
real |
线性衰减 |
quadraticAttenuation |
real |
二次衰减 |
常用方法
SceneLoader (Qt3D.Core)
方法 |
参数 |
说明 |
setSource |
url |
加载3D模型文件 |