2016-08-09 120 views
2

我想一個C++ QEntity添加到QML Scene3D,像這樣:使用Qt3D QEntity在QML Scene3D

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

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

這可能嗎?如果是的話,該怎麼做?

或者也許可以創建C++場景(例如Qt3DExtras :: Qt3DWindow)並在QML中使用?

回答

3

是的,可以在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 
     } 
    } 
} 
+1

這是有點接近鏈接只回答:HTTP ://stackoverflow.com/help/how-to-answer你可以做一個最小的,完整的例子作爲答案(C++和QML片段)。 – Mitch

+0

@ kamil請你分享一個合適的例子嗎? –