QML MouseArea,触发和传播事件

QML MouseArea, trigger and propagate events

我有一个带按钮的 QML 组件,...在里面。我放了一个 MouseArea 来覆盖整个组件,因为我需要在我点击该组件的任何地方执行一个动作。但是,我也想执行MouseArea后面的动作。

例如,如果我点击组件中的按钮,我想执行 MouseArea 动作,然后执行按钮动作。

Item {

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

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

如果propagateComposedEvents: true,则不执行MouseArea onClicked,但执行Button onClicked。如果为 false,则执行 MouseArea 但不执行 Button onClicked。

我希望同时执行 MouseArea(第一个)和 Button(第二个)信号 onClicked。

只需要将鼠标的接受属性设为false即可

Item {

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

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

来自 MouseArea 文档:

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.

如果你想专门捕获其中之一的鼠标点击,只需将 MouseArea 移动到 Button 下的 z 级别。或者,只需将其定义移到 Button 之前。

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

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

或:

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

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