Qt Quick 3D - ダイナミックモデルの作成例

動的モデル作成の例

この例では、アプリケーション内で動的にモデルを作成するデモンストレーションを行います。アプリケーションの開始時に10個のモデルが動的に作成され、ボタンと-ボタンを使ってさらに追加したり削除したりすることができます。

設定

スポナーノード

動的に作成されたモデルを保持するために、Node

Node {
    id: shapeSpawner
    property real range: 300
    property var instances: []
    property int count
    ...
スタートアップ

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
    }
}

プロジェクト例 @ code.qt.io

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