qt - 如何为动态创建的 QML 元素添加事件处理程序?

标签 qt qml

我根据 this blog post 动态地将一些 qml 组件添加到我的 gui 中。如何为这些新创建的组件添加事件处理程序?

最佳答案

我会用一个例子来解释。 1)创建自定义按钮组件如下

//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)
    }
}

这是一个简单的按钮,点击它会发出点击信号。 现在让我们动态创建一些按钮。

//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 作为参数。从现在开始,您可以在事件处理程序中执行任何您想要的操作。

关于qt - 如何为动态创建的 QML 元素添加事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603170/

相关文章:

qt - 如何改变 "Qt Quick - Control 2 RoundButton"的颜色

python - QML:设置图像的 "source"属性会导致其消失

c++ - Qt 连接语句

c++ - 如何将Window放入QWidget布局(Qt5)

QtCreator : a big lot of stray errors

c++ - 无法从 QQmlPropertyMap 的子类中的 QML 调用插槽或 Q_INVOKABLE

c++ - 为什么我从我的 QTouchPoint 获得无效数据?

qt - 如何在Qt Creator 中设置Qdialog 的固定高度尽可能小和扩展的宽度?

c++ - Horizo​​ntalHeaderView 不调用 QAbstractTableModel 的 child 的 headerData()