How to add an event handler for dynamically create

2020-06-01 08:14发布

问题:

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?

回答1:

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.



标签: qt qml