如何为动态创建的 QML 元素添加事件处理程序? [英] How to add an event handler for dynamically created QML elements?

查看:28
本文介绍了如何为动态创建的 QML 元素添加事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据这篇博文.如何为这些新创建的组件添加事件处理程序?

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();
    }
}

这里当 Main.qml 组件创建完成后,按钮就被创建了.创建了 4 个按钮,在创建每个按钮后,javascript 函数 buttonClicked 作为事件处理程序连接到 'Button.qml' 的 clicked 信号.每当用户点击按钮时,buttonClicked 函数将被调用,并以 buttonId 作为参数.从这里开始,您可以在事件处理程序中做任何您想做的事情.

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.

这篇关于如何为动态创建的 QML 元素添加事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆