gpt4 book ai didi

python - mousePressEvent 不适用于子部件?

转载 作者:行者123 更新时间:2023-12-01 08:51:34 25 4
gpt4 key购买 nike

所以,我试图每次左键单击时打印鼠标位置,但它只能在布局之外工作,我不知道如何修复它。我的 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"))

最佳答案

只有当小部件要处理该信息时,才会调用 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_())

关于python - mousePressEvent 不适用于子部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53081391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com