如何在布局中的小部件之间捕获 mousePressEvent?

How to capture mousePressEvent between widgets in a layout?

我正在尝试检测具有多个小部件的区域内任意位置的鼠标点击。为此,我使用以下代码:

custom_widget = CustomWidget()
custom_widget.mouse_pressed_signal.connect(self.on_custom_label_mouse_pressed)
main_layout_vbox.addWidget(custom_widget)

hbox = QtWidgets.QHBoxLayout()
custom_widget.setLayout(hbox)

# Adding several widgets to hbox_l6

class CustomWidget(QtWidgets.QWidget):
    mouse_pressed_signal = QtCore.pyqtSignal(QtGui.QMouseEvent)

    def __init__(self):
        super().__init__()

    def mousePressEvent(self, i_qmouseevent):
        super(CustomWidget, self).mousePressEvent(i_qmouseevent)
        logging.debug("======== CustomWidget - mousePressEvent ========")
        self.mouse_pressed_signal.emit(i_qmouseevent)

问题

这在单击任何子窗口小部件时都有效,但是有一个问题:如果我在窗口小部件之间单击 (所以在 hbox 未被小部件覆盖的布局)未捕获 mousePressEvent

问题

我该如何解决这个问题? (或者您可以推荐另一种方法吗?)重要的是我能够在 custom_widget / hbox 内的任何地方捕获鼠标点击(参见上面的代码)

如果您想收听其他小部件的 mousePressEvent,您可以使用 eventFilter,如下所示:

from PyQt5 import QtCore, QtGui, QtWidgets
import random


class Widget(QtWidgets.QWidget):
    mouse_clicked_signal = QtCore.pyqtSignal(QtGui.QMouseEvent, QtWidgets.QWidget)

    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        hlay = QtWidgets.QHBoxLayout(self)

        for cls in (QtWidgets.QLabel,  QtWidgets.QPushButton, QtWidgets.QFrame, QtWidgets.QWidget):
            widget = cls()
            color = QtGui.QColor(*random.sample(range(255), 3))
            widget.setStyleSheet("background-color: {}".format(color.name()))
            hlay.addWidget(widget)

        for w in self.findChildren(QtWidgets.QWidget) +  [self]:
            w.installEventFilter(self)

        self.resize(640, 480)

    def eventFilter(self, watched, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            self.mouse_clicked_signal.emit(event, watched)
        return super(Widget, self).eventFilter(watched, event)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.mouse_clicked_signal.connect(print)
    w.show()
    sys.exit(app.exec_())