Kinlaw
Kinlaw

Reputation: 11

Qt: Passing a slot to call into a QML Template

I'm trying to do something in Qt, and I'm not sure that it's possible. I can't seem to find any documentation about it, or anyone else trying to do it online, but I hate to give up unless someone can confirm that it isn't possible.

What I'm doing is creating a QML template that will be used for every button in my application. The QML Item has several properties and property aliases that are passed in when another QML file uses the template, that define how the button works. What I want to do is pass into the template a slot to call when the button is pressed.

Here's a simple example of a template and how it might work:

Item {
    property variant onClickedAction
    property alias buttonImageSource: buttonImage.source

    Image {
        id: buttonImage
        MouseArea {
            anchors.fill: parent
            onClicked: onClickedAction()
        }
    }
}

And here's an example of how another QML file might use that button template (which is called ExampleButtonTemplate.qml):

ExampleButtonTemplate {
    onClickedAction: ExampleSlot()
    buttonImageSource: "ExampleImage.png"
}

However, when I try it this way, it just calls the slot as soon as it loads the page that uses the template, instead of when the button is pressed. There must be some way that I can pass a function that I want to call later from one QML file to another through the properties. If anyone can explain a way to do this or confirm that it isn't possible to pass slots around like this, it would be a big help.

Upvotes: 0

Views: 322

Answers (2)

Kevin Krammer
Kevin Krammer

Reputation: 5207

While this is certainly possible why not just "forward" the signal and handle it like at the place of usage?

Basically just add a signal to your outermost item

Item {
    id: button
    signal clicked()

    Image {
        MouseArea {
            onClicked: button.clicked()
        }
    }
}

And then you use it like any built-in signal

ExampleButtonTemplate {
    onClicked: exampleSlot()
}

Upvotes: 1

Kinlaw
Kinlaw

Reputation: 11

Update: I got it working by doing this: Replace:

property variant onClickedAction

With:

property var onClickedAction

And replace:

onClickedAction: ExampleSlot()

With:

onClickedAction: ExampleSlot

Upvotes: 1

Related Questions