简体   繁体   中英

QML MouseArea, trigger and propagate events

I have a QML component with buttons, ... in it. I put a MouseArea which covers this entire component because I need to execute an action wherever I click on the component. However, I also want to execute the action behind the MouseArea.

For example, if I click on a button in the component, I want to execute the MouseArea action and then the button action.

Item {

  Button{
    anchors: ...
    onClicked: console.info("Button clicked")
  }

  MouseArea{
    anchors.fill: parent
    propagateComposedEvents: true
    onClicked: console.info("MouseArea clicked")
  }
}

If propagateComposedEvents: true, then MouseArea onClicked is not executed, but Button onClicked is. If false, MouseArea is executed but not Button onClicked.

I want to have both MouseArea (first) and Button (second) signal onClicked to be executed.

You just need to set the accepted property of the mouse to false.

Item {

  Button{
    anchors: ...
    onClicked: console.info("Button clicked")
  }

  MouseArea{
    anchors.fill: parent
    propagateComposedEvents: true
    onClicked: {
        console.info("MouseArea clicked");
        mouse.accepted =false;
  }
}

From MouseArea documentation:

If propagateComposedEvents is set to true, then composed events will be automatically propagated to other MouseAreas in the same location in the scene. Each event is propagated to the next enabled MouseArea beneath it in the stacking order, propagating down this visual hierarchy until a MouseArea accepts the event. Unlike pressed events, composed events will not be automatically accepted if no handler is present.

If you want to exclusively catch mouse click on one of them, just move the MouseArea under Button regarding its z level. Or, just move its definition before the Button.

Item {
  MouseArea{
    anchors.fill: parent
    onClicked: console.info("MouseArea clicked")
  }

  Button{
    anchors: ...
    onClicked: console.info("Button clicked")
  }
}

OR:

Item {
  Button{
    anchors: ...
    onClicked: console.info("Button clicked")
    z: 1
  }

  MouseArea{
    anchors.fill: parent
    onClicked: console.info("MouseArea clicked")
    z: 0
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM