qt - How to add an event handler for dynamically created QML elements? -
i dynamically added qml components gui according this blog post. how can add event handlers newly created components?
i'll explain example. 1)create custom button component follows
//button.qml ... component's objects dynamically // created import qtquick 2.1 rectangle { width: 100 height: 50 color:"blue" //since buttons created on fly, //we need identify button on user // has clicked. id must unique property string buttonid; signal clicked(string buttonid); mousearea { anchors.fill: parent onclicked:parent.clicked(parent.buttonid) } }
this simple button emits clicked signal on clicking on it.. lets create buttons on fly.
//main.qml ... creates buttons on fly import qtquick 2.1 rectangle{ id:root width:500 height:500 function buttonclicked(buttonid) { console.debug(buttonid); } function createsomebuttons() { //function creates 4 buttons var component = qt.createcomponent("button.qml"); for(var i=0;i<4;i++) { var buttony = i*55; //button height : 50 + 5 unit margin var button = component.createobject(root,{"x":0,"y":buttony,"buttonid":i+1}); //connect clicked signal of newly created button //to event handler buttonclicked. button.clicked.connect(buttonclicked) } } component.oncompleted: { createsomebuttons(); } }
here when main.qml component creation has been completed, buttons created. 4 buttons created , after creation of each button, javascript function buttonclicked connected event handler 'button.qml''s clicked signal. whenever user clicks on button, buttonclicked function called buttonid argument. can whatever want in event handler here on.
Comments
Post a Comment