Sunday, April 10, 2011

Creating QML element dynamically on runtime

Often while working with QML we need to create QML element dynamically on runtime depending upon some event like button click or something else.

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.

10 comments:

  1. Hi,,
    I am not getting how to execute it.. i am fresher batch of 2013.. help me

    ReplyDelete
    Replies
    1. you can call if from button press event or mouse press event or may on when on element construction is done.

      Delete
  2. Hi, how can i add event handlers for those newly created QML elements ?

    ReplyDelete
    Replies
    1. you can use, rect.dropped.connect(dropped); for connection signal from created element to parent or any other object.

      similarly you can also connect parent signal to function of created element

      Delete
  3. It doesn't work for me as it's said that main argument in createObject
    is not defined

    ReplyDelete
    Replies
    1. 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.
      http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html

      Delete
  4. 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