Question

I have a QML element "Button" which has a MouseArea element inside. What I want to do is to send a function to the item and then pass it to MouseArea:

Example:

Button{
    id: smth
    ... 
    ...
   onClicked: console.log("Someone Clicked Me!")

}

And my element could be something like this:

Rectangle{
    property var onClicked
    ...
    MouseArea{
       onClicked : parent.onClicked
    }
}

I found out that I can pass the function like in native js without parentheses, but I think there is a way to implement it like MouseArea element does.

Was it helpful?

Solution

The usual way to handle this situation in QML is to let the Button emit a signal, which is then handled by the user of Button.

Button.qml:

Rectangle {
    id: root
    signal clicked

    MouseArea {
        anchors.fill: parent
        onClicked: root.clicked();
    }
}

Usage:

Button {
    onClicked: console.log("Button was clicked!");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top