首页 > 解决方案 > QML InputHandler 停止传播事件

问题描述

我有两个矩形,每个矩形都有一个TapHandler. 矩形 A 是矩形 B 的父级
如何配置 A 和 B,以便在单击 B 时EventPoint不会传播到onSingleTappedA 的处理程序?

EventPoint文档建议将其accepted属性设置为 true:

将accepted 设置为true 可防止事件传播到PointerHandler 的Item 下面的Item。

但是,与此同时,文档声明这accepted是一个只读属性,这没有多大意义(我猜文档已经过时或完全错误)。

测试代码:

Rectangle {
    id: a

    width: 200
    height: 200
    color: "yellow"
    TapHandler {
        onSingleTapped: console.log("A tapped")
    }

    Rectangle {
        id: b
        color: "blue"
        width: 100
        height: 100
        TapHandler {
            onSingleTapped: function(eventPoint) {
                // Stop propagation.
                eventPoint.accepted = true
                console.log("B tapped")
            }
        }
    }
}

更新:设置gesturePolicyB 以TapHandler.ReleaseWithinBounds防止 A 接收事件。不确定这是否真的是最好的解决方案

标签: qtqmlevent-propagation

解决方案


对于 Handlers,整个event交付给每个 handler;因此 Handlers 接受个体points,而不是整体event。一般来说,接受所有点意味着接受整个事件,但可能是一个处理程序接受一些点,而另一个处理程序接受其他点。直到所有点都完成后,交付才“完成” accepted

看起来grabPermissions没有 a 的设置gesturePolicy不会做预期的事情..抓住事件并防止传播到其他项目

Rectnagle将b (a 的孩子)更改TapHandler为hasgesturePolicy: TapHandler.ReleaseWithinBounds TapHandler.WithinBounds似乎是正确的方法aaccept,换句话说,它接受了这一点,这意味着事件不会传播到父 Rectangle 的 TapHandler!

    Rectangle {
        id: b
        z:2
        color: "blue"
        width: 100
        height: 100
        TapHandler {
            gesturePolicy: TapHandler.ReleaseWithinBounds | TapHandler.WithinBounds
            grabPermissions: PointerHandler.CanTakeOverFromAnything | PointerHandler.CanTakeOverFromHandlersOfSameType | PointerHandler.CanTakeOverFromItems
                             | PointHandler.ApprovesTakeOverByAnything | PointHandler.ApprovesCancellation
            onSingleTapped: function(eventPoint) {
                // Stop propagation.
                eventPoint.accepted = true // this is just a confirmation!
                console.log("B tapped")
            }
        }
    }

远离 .. narkive interset group


推荐阅读