Creating QML object dynamically
-
wrote on 13 Jul 2012, 08:56 last edited by
Is there anyway for creating a QML object dynamically from the Qt code, without using the .qml file or JavaScripts?
-
wrote on 13 Jul 2012, 09:37 last edited by
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
-
wrote on 13 Jul 2012, 09:40 last edited by
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.
-
wrote on 19 Jul 2012, 07:05 last edited by
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 snippetint main(int argc, char *argv[])
{QApplication app(argc, argv); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("qml/example_2/main.qml")); QObject *rootObjectA = viewer.rootObject(); rootObjectA->setProperty("text1Text",QVariant("Change you text here...")); viewer.showExpanded(); return app.exec();
}
-
wrote on 19 Jul 2012, 09:35 last edited by
[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 snippetint main(int argc, char *argv[])
{QApplication app(argc, argv); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("qml/example_2/main.qml")); 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...
-
wrote on 20 Jul 2012, 03:03 last edited by
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();
@
1/6