Following code described how we can create QML element at runtime dynamically. In following code I am trying to create Rect QML element on runtime, set some property on element and also connecting signal from Rect element.
function createRect(num) { var component = Qt.createComponent("Rect.qml"); var rect = component.createObject(main,{"x":50,"y":10}); if(rect != null ) { rect.name = "Test"; rect.x = Math.floor(Math.random() * 300 ); rect.y = Math.floor(Math.random() * 100 ); rect.dropped.connect(dropped); } } function dropped(x,y,name) { console.log("################## Dropped:"+name+"::"+ x +":"+ y); }
In above code "dropped" is signal defined in Rect element. And I am calling connect method of signal to connect "dropped" signal to my slot "dropped".
Following is code from "Rect.qml" that define Rect element.
Rectangle { width:100 height:50 color:"lightblue" property string name: ""; signal dropped(int x,int y,string name); }
That's all, Hope this helps.
great. thank you!
ReplyDeleteHi,,
ReplyDeleteI am not getting how to execute it.. i am fresher batch of 2013.. help me
you can call if from button press event or mouse press event or may on when on element construction is done.
Deleteawesome! very helpful.
ReplyDeleteHi, how can i add event handlers for those newly created QML elements ?
ReplyDeleteyou can use, rect.dropped.connect(dropped); for connection signal from created element to parent or any other object.
Deletesimilarly you can also connect parent signal to function of created element
It doesn't work for me as it's said that main argument in createObject
ReplyDeleteis not defined
That argument is supposed to be the "parent" you want the dynamically-generated object to be attached to. It isn't defined in the above code, you have to do it yourself.
Deletehttp://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html
Hey, I am problem of memory leak when switching between tabs which creates dynamic objects of other pages. Do you have any idea on this?
ReplyDelete***Facing
DeleteIntteresting read
ReplyDelete