Qt 3D:简单的自定义材质 QML 示例
演示如何在Qt 3D 中创建自定义材质。

本示例演示了如何创建一个简单的自定义材质。
运行示例
您可以通过以下方式运行该示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在Command Palette 中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关详细信息,请参阅Qt Extension for Visual Studio Code :教程:构建与运行。
指定场景
该示例使用Scene3D 渲染一个将使用自定义材质的场景。该场景包含一个平面模型,该模型使用自定义材质。
Entity {
id: root
components: [transform, mesh, material]
SimpleMaterial {
id: material
maincolor: "red"
}
Transform {
id: transform
rotationX: 45
}
PlaneMesh {
id: mesh
width: 1.0
height: 1.0
meshResolution: Qt.size(2, 2)
}
}指定材质
该材质在simplecustommaterial/SimpleMaterial.qml 中通过Material 类型进行指定。首先,材质指定了参数,这些参数会被映射到着色器中的相应uniform变量,以便可以通过qml进行修改。
property color maincolor: Qt.rgba(0.0, 0.0, 0.0, 1.0)
parameters: [
Parameter {
name: "maincolor"
value: Qt.vector3d(root.maincolor.r, root.maincolor.g, root.maincolor.b)
}
]接下来,我们指定要加载的着色器。针对 OpenGL ES 2 和 OpenGL 渲染器,分别提供了不同的着色器版本。
property string vertex: "qrc:/shaders/gl3/simpleColor.vert"
property string fragment: "qrc:/shaders/gl3/simpleColor.frag"
property string vertexRHI: "qrc:/shaders/gl45/simpleColor.vert"
property string fragmentRHI: "qrc:/shaders/gl45/simpleColor.frag"
property string vertexES: "qrc:/shaders/es2/simpleColor.vert"
property string fragmentES: "qrc:/shaders/es2/simpleColor.frag"在顶点着色器中,我们仅需使用变换矩阵对位置进行变换。
void main()
{
// Transform position, normal, and tangent to world coords
worldPosition = vec3(modelMatrix * vec4(vertexPosition, 1.0));
// Calculate vertex position in clip coordinates
gl_Position = mvp * vec4(worldPosition, 1.0);
}在片段着色器中,我们仅将片段颜色设置为材质中指定的主色。
uniform vec3 maincolor;
void main()
{
//output color from material
fragColor = vec4(maincolor,1.0);
}接下来,我们根据着色器创建ShaderPrograms 。
ShaderProgram {
id: gl3Shader
vertexShaderCode: loadSource(parent.vertex)
fragmentShaderCode: loadSource(parent.fragment)
}
ShaderProgram {
id: es2Shader
vertexShaderCode: loadSource(parent.vertexES)
fragmentShaderCode: loadSource(parent.fragmentES)
}
ShaderProgram {
id: rhiShader
vertexShaderCode: loadSource(parent.vertexRHI)
fragmentShaderCode: loadSource(parent.fragmentRHI)
}最后,这些着色器程序将在对应于特定 API 配置文件的“技术”中使用。
// OpenGL 3.1
Technique {
filterKeys: [forward]
graphicsApiFilter {
api: GraphicsApiFilter.OpenGL
profile: GraphicsApiFilter.CoreProfile
majorVersion: 3
minorVersion: 1
}
renderPasses: RenderPass {
shaderProgram: gl3Shader
}
},© 2026 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.