Set onClicked function based upon state



  • What I would like is that if the object is in a certain state it should call func1 when onClicked is called and in a different state should call a different function. So instead of something like this:

    @Rectangle {
    anchors.fill: parent
    anchors.margins: 20

    MouseArea {
    id: area
    anchors.fill: parent
    onClicked:{
    if state == "one":
    ... do somethone for one...
    else:
    ... do somethone for two...
    }
    }
    }@

    I want something like this.

    @states [
    State {
    name = "one"
    "somehow set area.onclicked to handleOne"
    },
    State {
    name = "two"
    "somehow set area.onclicked to handleTwo"
    },
    ]

    function handleOne() {
    }

    function handleTwo() {
    }

    Rectangle {
    anchors.fill: parent
    anchors.margins: 20

    MouseArea {
    id: area
    anchors.fill: parent
    }
    }@



  • There are various ways to do this. The first is to use a control variable and "trampoline" a function call in the onClicked handler.

    eg: onClicked: if (shouldCallFunctionOne) functionOne(); else functionTwo();

    The second is to use "var" properties and store a reference to the function you wish to call in it - but this is a Qt5-only solution.

    Cheers,
    Chris.



  • You should be able to modify the signal handler from JS like this:

    @
    State {
    name: "one"
    StateChangeScript {
    script: {
    area.clicked.disconnect( handleOne );
    area.clicked.connect( handleTwo );
    }
    }
    @

    But note: if you add a handler to clicked while this event is currently handled, the newly added handler will be called immediatly.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.