Within QML, I can dynamically create a component (rather than loading it from a file) by calling Qt.createQmlObject
. Example:
Qt.createQmlObject('import QtQuick 1.0; Rectangle {color: "red"; width: 20; height: 20}', parent, "dynamicPath");
Is there way to do the same from C++ code? It doesn't necessarily have to involve parsing QML—I'm just looking for a way to, for example, dynamically create and attach a Rectangle
or TextField
to a QML document from C++.
Are you using the deprecated Qt Quick 1? Given that you have:
QDeclarativeView *view = ...;
QDeclarativeItem *parent = ...;
You can do:
QDeclarativeEngine *engine = view->engine();
QDeclarativeComponent component(engine);
component.setData("import QtQuick 1.0; Rectangle {color: \"red\"; width: 20; height: 20}", QUrl("dynamicPath"));
QDeclarativeItem *item = qobject_cast<QDeclarativeItem *>(component.create());
Q_ASSERT(item);
item->setParentItem(parent);
If you are actually using Qt Quick 2 instead, you'd replace QDeclarative*
with QQml*
and QQuick*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With