Creating QML object dynamically



  • Is there anyway for creating a QML object dynamically from the Qt code, without using the .qml file or JavaScripts?



  • yes it is!

    @
    QDeclarativeItem *item = NULL;
    QDeclarativeComponent component(this->rootContext->engine(), QUrl("qrc:/my.qml"));

    item = qobject_cast<QDeclarativeItem *>(component.create());
    item->setProperty("property", "Hello");
    item->setParentItem(qobject_cast<QDeclarativeItem *>(parent));
    @

    You can safely pass a QML object (parent in the example) from within a QML file as parameter



  • There is a possibility to build QQmlExtensionPlugin to define your qmlfiles and refenrece them.

    Is it the pint you think about ?

    http://doc-snapshot.qt-project.org/5.0/qqmlextensionplugin.html

    There is the an example in the TimeExample in the QT5 sources.



  • I already have a qml file and i want to add this declarative item on that QML file and be able to change the property for that declarative item. How to do that?
    Below is the code snippet

    int main(int argc, char *argv[])
    {

    QApplication app(argc, argv);
    
    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile&#40;QLatin1String("qml/example_2/main.qml"&#41;);
    QObject *rootObjectA = viewer.rootObject();
    rootObjectA->setProperty("text1Text",QVariant("Change you text here..."));
    viewer.showExpanded();
    
    return app.exec();
    

    }



  • [quote author="qtNiks" date="1342681553"]I already have a qml file and i want to add this declarative item on that QML file and be able to change the property for that declarative item. How to do that?
    Below is the code snippet

    int main(int argc, char *argv[])
    {

    QApplication app(argc, argv);
    
    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile&#40;QLatin1String("qml/example_2/main.qml"&#41;&#41;;
    QObject *rootObjectA = viewer.rootObject();
    rootObjectA->setProperty("text1Text",QVariant("Change you text here..."));
    viewer.showExpanded();
    
    return app.exec();
    

    }

    [/quote]

    Maybe I didn't understand what you want to do...if you just want to change a property on rootObjectA, the code above is correct...



  • I'm not sure I understand exactly what you're looking for either. Perhaps you want to create an object from QML defined entirely in C++. QQmlComponent::setData() does this, e.g.

    @
    QDeclarativeComponent component(engine);
    component.setData("import QtQuick 1.0; Rectangle { color: 'red'; width: 20; height: 20 }", QUrl());
    QObject *obj = component.create();
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.