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

时间:2018-11-03 18:28:22

标签: python pyqt pyqt5 qmouseevent

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

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(请参见上面的代码)内任何地方的鼠标点击。

1 个答案:

答案 0 :(得分:1)

如果您想听其他小部件的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_())