6

我想向 QML Scene3D 添加一个 C++ QEntity,如下所示:

//C++
class MapEntity : public Qt3DCore::QEntity {
    public:
    MapEntity( Qt3DCore::QEntity* parent ) : Qt3DCore::QEntity(parent) {
        ...
    }
}

// QML
Scene3D {
    MapEntity {
        id: map
        ...
    }
}

可能吗?如果是,该怎么做?

或者也许可以创建 C++ 场景(例如 Qt3DExtras::Qt3DWindow)并在 QML 中使用?

4

1 回答 1

6

是的,可以在 C++ 代码中定义 QEntity 然后使用它。该方法在此处描述:

http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html

首先,您正在创建 QEntity。以球体为例:

class MyEntity : public Qt3DCore::QEntity {
    public:
        MyEntity( Qt3DCore::QEntity* parent=0 ) : Qt3DCore::QEntity(parent) {
                Qt3DRender::QMaterial *material = new Qt3DExtras::QPhongMaterial;

                Qt3DExtras::QSphereMesh *sphereMesh = new Qt3DExtras::QSphereMesh;
                sphereMesh->setRadius(8);

                addComponent(sphereMesh);
                addComponent(material);
        }
        virtual         ~MyEntity() {}
};

然后将其注册为 qml 组件:

qmlRegisterType<MyEntity>("com.company.my", 1, 0, "MyEntity");

只需在 QML 中使用它:

Scene3D {
    id: myScene
    anchors.fill: parent
    cameraAspectRatioMode: Scene3D.AutomaticAspectRatio
    focus: true
    enabled: true



    Entity {
        id: sceneRoot

        Quick.Camera {
            id: camera
            projectionType: Quick.CameraLens.PerspectiveProjection
            fieldOfView: 45
            nearPlane : 0.1
            farPlane : 1000.0
            position: Qt.vector3d( 0.0, 0.0, 40.0 )
            upVector: Qt.vector3d( 0.0, 1.0, 0.0 )
            viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
        }

        components: [
            Quick.RenderSettings {
                activeFrameGraph: ForwardRenderer {
                    clearColor: Qt.rgba(0, 0.5, 1, 0)
                    camera: camera
                }
            }
        ]

        MyEntity {
            id: myEnt
        }
    }
}
于 2016-08-09T10:17:36.420 回答