mousePressEvent在子小部件上不起作用?

时间:2018-10-31 10:38:17

标签: python pyqt pyqt5

因此,每次尝试单击鼠标左键时,我都试图打印它的位置,但是它仅在布局之外起作用,我不知道如何解决它。我的GUI如下所示:

enter image description here

import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from untitled import Ui_Dialog


class AppWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.show()

    def mousePressEvent(self, a0: QtGui.QMouseEvent):
        print(a0.pos())


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = AppWindow()
    w.show()
    sys.exit(app.exec_())

这是我的untitled.py文件

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.horizontalLayout = QtWidgets.QHBoxLayout(Dialog)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)
        self.graphicsView = QtWidgets.QGraphicsView(Dialog)
        self.graphicsView.setObjectName("graphicsView")
        self.verticalLayout.addWidget(self.graphicsView)
        self.horizontalLayout.addLayout(self.verticalLayout)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButton.setText(_translate("Dialog", "PushButton"))

1 个答案:

答案 0 :(得分:1)

仅当窗口小部件将要处理该信息时才调用mousePressEvent事件,因此,如果在您单击的区域中还有其他子窗口小部件,则该事件将不会被接收,因此只能在以下位置获得单击:顶部没有其他小部件,因此在这种情况下,解决方案是通过eventFilter监听事件:

import sys
from PyQt5 import QtGui, QtWidgets, QtCore
from untitled import Ui_Dialog


class AppWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()
        for w in self.findChildren(QtWidgets.QWidget)+[self]:
            w.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.MouseButtonPress:
            if event.buttons() & QtCore.Qt.LeftButton:
                print(obj, "global pos:", event.globalPos(), 
                            "local pos", event.pos(),
                            "position with respect to self",
                            self.mapFromGlobal(obj.mapToGlobal(event.pos())))
        return super(AppWindow, self).eventFilter(obj, event)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = AppWindow()
    w.show()
    sys.exit(app.exec_())