I dynamically added some qml components to my gui according to this blog post. How can I add event handlers for those newly created components?
Creating a Component Dynamically To dynamically load a component defined in a QML file, call the Qt. createComponent() function in the Qt object. This function takes the URL of the QML file as its only argument and creates a Component object from this URL.
This can be used to execute script code at startup, once the full QML environment has been established. The onCompleted signal handler can be declared on any object. The order of running the handlers is undefined. Rectangle { Component. onCompleted: console.
A Connections object creates a connection to a QML signal. However, it is not possible to connect to a signal in this way in some cases, such as when: Multiple connections to the same signal are required. Creating connections outside the scope of the signal sender.
Adding signals to custom QML types Signals can be added to custom QML types through the signal keyword. The syntax for defining a new signal is: signal <name>[([<type> <parameter name>[, ...]])] A signal is emitted by invoking the signal as a method.
I'll explain with an example. 1)Create a custom button component as follows
//Button.qml ... This component's objects will be dynamically
// created
import QtQuick 2.1
Rectangle {
width: 100
height: 50
color:"blue"
//Since the buttons are created on the fly,
//we need to identify the button on which the user
// has clicked. The id must be unique
property string buttonId;
signal clicked(string buttonId);
MouseArea {
anchors.fill: parent
onClicked:parent.clicked(parent.buttonId)
}
}
This is a simple button which emits clicked signal on clicking on it.. Now lets create some buttons on the fly.
//Main.qml ... creates some buttons on the 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 the clicked signal of the newly created button
//to the event handler buttonClicked.
button.clicked.connect(buttonClicked)
}
}
Component.onCompleted: {
createSomeButtons();
}
}
Here when the Main.qml component creation has been completed, buttons are created. 4 buttons are created and after creation of each button, the javascript function buttonClicked is connected as event handler to the 'Button.qml''s clicked signal. Whenever the user clicks on the button, buttonClicked function will be called with buttonId as argument. You can do whatever you want in the event handler from here on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With