How to intercept and propagate an event from overlapping widgets

梦想的初衷 提交于 2019-12-11 09:42:35

问题


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

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_()

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;
            }
        }
    }
}

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


回答1:


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

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


来源:https://stackoverflow.com/questions/27331552/how-to-intercept-and-propagate-an-event-from-overlapping-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!