[英]How to add an event handler for dynamically created QML elements?
我將用一個例子來解釋。 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 '的單擊信號。 每當用戶點擊按鈕時,將使用buttonId作為參數調用buttonClicked函數。 從這里開始,您可以在事件處理程序中執行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.