我根据以下内容动态添加了一些 qml 组件到我的 gui 中这篇博文 http://kunalmaemo.blogspot.kr/2011/04/creating-qml-element-dynamically-on.html。如何为这些新创建的组件添加事件处理程序?
我将用一个例子来解释。
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 作为事件处理程序连接到 '按钮.qml''s clicked信号。每当用户单击按钮时,按钮被点击函数将被调用buttonId作为论证。从现在开始,您可以在事件处理程序中执行任何您想要的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)