2015-08-08 66 views
1

如何从C++中动态添加更多Rectangle到ID为root的那个?例如,两个Rectangle有色red和​​?从C++向QML布局添加对象

main.qml:

Rectangle { color: "red"; width: 200; height: 200 } 
Rectangle { color: "green"; width: 200; height: 200 } 

Qt创建者生成main.cpp

int main(int argc, char *argv[]) { 
    QGuiApplication app(argc, argv); 
    QtQuick2ApplicationViewer viewer; 
    viewer.setMainQmlFile(QStringLiteral("qml/gui/main.qml")); 
    viewer.showExpanded();  
    return app.exec() 
} 

回答

3

的最佳方式来创建动态

Rectangle { 
    id: root 
} 

典型QML对象下 '根' 添加项目是QML本身。但是如果你仍然想用C++来做到这一点,那也是可能的。例如:

main.cpp中:

int main(int argc, char *argv[]) 
{ 
    QGuiApplication app(argc, argv); 
    QQuickView view; 
    view.setSource(QUrl("qrc:/main.qml")); 
    view.show(); 
    QObject *root = view.rootObject(); 
    QQuickItem * myRect = root->findChild<QQuickItem *>("myRect"); 
    if(myRect) { 
     QQmlComponent rect1(view.engine(),myRect); 
     rect1.setData("import QtQuick 2.4; Rectangle { width:100; height: 100; color: \"orange\"; anchors.centerIn:parent; }",view.source()); 
     QQuickItem *rect1Instance = qobject_cast<QQuickItem *>(rect1.create()); 
     view.engine()->setObjectOwnership(rect1Instance,QQmlEngine::JavaScriptOwnership); 
     if(rect1Instance) 
      rect1Instance->setParentItem(myRect); 
    } 
    return app.exec(); 
} 

main.qml

import QtQuick 2.4 

Item { 
    width: 600 
    height: 600 

    Rectangle { 
     objectName: "myRect" 
     width: 200 
     height: 200 
     anchors.centerIn: parent 
     color: "green" 
    } 
} 

因为所有的QML项目都有相应的С++类,它可以直接创建QQuickRectangle但标题是私人的,这不是建议的方式。

此外,请注意,我使用objectName访问C++项目,而不是id,因为它在C++端不可见。