Skip to content

Instantly share code, notes, and snippets.

@jdowner
Last active September 25, 2024 17:03
Show Gist options
  • Save jdowner/4697780 to your computer and use it in GitHub Desktop.
Save jdowner/4697780 to your computer and use it in GitHub Desktop.
How to pass a Qml Component as a signal parameter.
import QtQuick 1.0
Rectangle {
height: 300
width: 400
color: "gray"
// This text element is for visual feedback when the signal fires
Text {
text: "(empty)"
font {
family: "Arial"
pixelSize: 24
}
anchors {
verticalCenter: parent.verticalCenter
horizontalCenter: parent.horizontalCenter
}
// Connecting the text element to the 'fire' signal using a
// javascript function to modify the text property
Component.onCompleted: {
mouse.fire.connect(function(item){
text = item.name
})
}
}
MouseArea {
id: mouse
anchors.fill: parent
// IMPORTANT: This is the key -- pass the component as a variant
signal fire(variant item)
onClicked: {
// create an instance of the 'MyItem' component and fire it
var component = Qt.createComponent("MyItem.qml")
var object = component.createObject(parent, {'name':'bob'})
fire(object)
}
onFire: {
// The parameter 'item' is passed with the signal and the following
// demonstrates that the name variable on the item is available
console.log(item.name + " was fired")
}
}
}
import QtQuick 1.0
Item {
property string name
}
MyItem 1.0 my-item.qml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment