如何拦截和传播来自重叠小部件的事件 [英] How to intercept and propagate an event from overlapping widgets

查看:51
本文介绍了如何拦截和传播来自重叠小部件的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拦截来自放置在另一个小部件顶部的小部件的事件,而不消耗它.

I'd like to intercept an event from a widget placed on-top of another widget, without consuming it.

这是我到目前为止所得到的.单击重叠部分时,我希望它打印Hello World",但我得到的只是Hello".

Here's what I've got so far. When clicking the overlapping part, I'd like it to print "Hello World", but all I'm getting is "Hello".

import sys
from PyQt5 import QtWidgets


class Button(QtWidgets.QPushButton):
    def mousePressEvent(self, event):
        print self.text()
        return super(Button, self).mousePressEvent(event)


app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setFixedSize(200, 100)

button1 = Button("World", window)
button1.move(10, 10)
button2 = Button("Hello", window)
button2.move(50, 15)

window.show()
app.exec_()

这是 QML 中的一个示例,它可以满足我的要求.

Here's an example in QML that does what I'm looking for.

import QtQuick 2.0


Item {
    id: root
    width: 200; height: 100

    MouseArea {
        anchors.fill: parent
        onPressed: console.log("World")
    }

    Rectangle {
        color: "green"
        width: 100; height: 50
        x: 10; y: 10

        MouseArea {
            anchors.fill: parent
            propagateComposedEvents: true
            onPressed: {
                console.log("Hello");
                mouse.accepted = false;
            }
        }
    }
}

点击窗口会产生World",而点击绿色矩形会产生Hello",然后是World".这里的关键是 propagateComposedEvents

Clicking the window yields "World" whereas clicking the green rectangle yields "Hello" followed by "World". The key here is the propagateComposedEvents

推荐答案

有一个 window 属性 可以满足您的需求:

There's a window attribute which does what you want:

button = Button("Hello", window)
button.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)

这篇关于如何拦截和传播来自重叠小部件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆