Qt Quick 3D - 动态模型创建示例
演示动态模型创建。
本示例演示了如何在应用程序中动态创建模型。应用程序启动时会动态创建10个模型,并可通过“+”和“-”按钮添加或删除更多模型。

设置
生成器节点
我们需要一个Node 来容纳动态创建的模型。
启动
我们在Component.onCompleted 处创建了10个模型,以便示例在启动时就能显示内容。
Component.onCompleted: {
for (var i = 0; i < 10; ++i)
shapeSpawner.addShape()
}动态模型
添加模型
为了将新项目添加到场景中,我们首先使用Qt.createComponent 函数为模型创建一个Component 。然后,我们使用该组件的createObject 函数来实例化该项目,并将位置和缩放比例作为参数传递进去。
function addShape()
{
var xPos = (2 * Math.random() * range) - range;
var yPos = (2 * Math.random() * range) - range;
var zPos = (2 * Math.random() * range) - range;
var shapeComponent = Qt.createComponent("WeirdShape.qml");
let instance = shapeComponent.createObject(shapeSpawner,
{ "x": xPos, "y": yPos, "z": zPos, "scale": Qt.vector3d(0.25, 0.25, 0.25)});
instances.push(instance);
count = instances.length
}移除模型
动态创建的模型只需从实例堆栈中弹出并销毁即可移除。
function removeShape()
{
if (instances.length > 0) {
let instance = instances.pop();
instance.destroy();
count = instances.length
}
}© 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.