qt - How to create a QQmlComponent from C++ at runtime? -
this question has reply here:
create qml element in c++? 2 answersi need add together qml components @ runtime c++ code. able create applicationwindow 'main.qml' file. window displayed successfully. issue not able add together other qml components window. have button specified in 'button.qml' file. tried create qqmlcomponent , set applicationwindow parent button. output of obj1->children() shows children of type button exists (qquickitem(0xcc08c0) , button_qmltype_12(0xa7e6d0) ). button not displayed. when seek add together button staticaly 'main.qml' works well. missing in creation of qqmlcomponent @ runtime.
qqmlengine engine; qqmlcomponent component1(&engine, qurl("qrc:/main.qml")); qqmlcomponent component2(&engine, qurl("qrc:/button.qml")); qobject* obj1 = component1.create(); qobject* obj2 = component2.create(); obj2->setparent(obj1);
see loading qml objects c++:
qquickview view; view.setsource(qurl("qrc:/main.qml")); view.show(); qquickitem *root = view.rootobject() qqmlcomponent component(view.engine(), qurl("qrc:/button.qml")); qquickitem *object = qobject_cast<qquickitem*>(component.create());
now created instance of custom button
component.
to avoid javascript garbage collector kill it, tell qml c++ takes care of it:
qqmlengine::setobjectownership(object, qqmlengine::cppownership);
you need 2 parents: visual parent show object , qobject parent, create sure object
deleted when view
deleted.
object->setparentitem(root); object->setparent(&view);
feel free set property object
in qml. create sure, qml knows changes, utilize next function:
object->setproperty("color", qvariant(qcolor(255, 255, 255))); object->setproperty("text", qvariant(qstring("foo")));
done.
alternative qqmlengine version:
qqmlapplicationengine engine; engine.load(qurl(qstringliteral("qrc:/main.qml"))); qquickwindow *window = qobject_cast<qquickwindow*>(engine.rootobjects().at(0)); if (!window) { qfatal("error: root item has window."); homecoming -1; } window->show(); qquickitem *root = window->contentitem(); qqmlcomponent component(&engine, qurl("qrc:/button.qml")); qquickitem *object = qobject_cast<qquickitem*>(component.create()); qqmlengine::setobjectownership(object, qqmlengine::cppownership); object->setparentitem(root); object->setparent(&engine); object->setproperty("color", qvariant(qcolor(255, 255, 255))); object->setproperty("text", qvariant(qstring("foo")));
c++ qt object qml
No comments:
Post a Comment