3

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

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(参见上面的代码)

4

1 回答 1

2

如果您想收听其他小部件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_())
于 2018-11-03T19:04:25.513 回答