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 } }
© 2025 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.