Use Qt3D QEntity in QML Scene3D
Asked Answered
R

1

6

I want to add an C++ QEntity to the QML Scene3D, like this:

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

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

Is it possible? And if yes, how to do it?

Or maybe it is possible to create C++ scene (Qt3DExtras::Qt3DWindow for example) and use in in QML?

Roughish answered 9/8, 2016 at 9:46 Comment(0)
R
6

Yes, it is possible to define QEntity in C++ code and then use it. The method is described here:

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

First of all you are creating QEntity. Sphere for example:

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() {}
};

Then register it as qml component:

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

And just use it in 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
        }
    }
}
Roughish answered 9/8, 2016 at 10:17 Comment(3)
This is kinda close to a link-only answer: stackoverflow.com/help/how-to-answer You could make a minimal, complete example as the answer (C++ and QML snippets).Voodooism
@kamil can you please share a proper example?Fredericton
Answer is quite good, the entire code is very verbose but the provided solution is the specific code needed. If the OP is not familiar with QML basics then it should read about that and o some examples on that before, otherwise there is no limit and the answer could span and cover up to basics of C++.Ola

© 2022 - 2024 — McMap. All rights reserved.