Pro*_*mer 26
我将用一个例子来解释.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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的按钮,点击它时会发出点击信号.现在我们可以动态创建一些按钮.
//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();
}
}
Run Code Online (Sandbox Code Playgroud)
完成Main.qml组件创建后,将创建按钮.创建了4个按钮,在创建每个按钮后,javascript函数buttonClicked作为事件处理程序连接到' Button.qml '的单击信号.每当用户点击按钮时,将使用buttonId作为参数调用buttonClicked函数.从这里开始,您可以在事件处理程序中执行任何操作.
归档时间: |
|
查看次数: |
7872 次 |
最近记录: |