Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Qt.createQmlObject in C++

Tags:

c++

qt

qml

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++.

like image 544
spinda Avatar asked Sep 19 '25 02:09

spinda


1 Answers

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*.

like image 132
jpnurmi Avatar answered Sep 20 '25 14:09

jpnurmi