gpt4 book ai didi

python - 为什么 mouseMoveEvent 在 PyQt5 中什么都不做

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:51 27 4
gpt4 key购买 nike

我尝试在PyQt5和Python3.5中使用mouseMoveEvent和mousePressEvent,但是当我点击鼠标时没有任何反应。我的代码如下,有什么问题吗?

from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
widget = QtWidgets.QWidget(self)
layout = QtWidgets.QVBoxLayout(widget)
self.graphicsView = QtWidgets.QGraphicsView()
self.graphicsView.setCursor(QtCore.Qt.CrossCursor)
self.graphicsView.setObjectName("graphicsView")
layout.addWidget(self.graphicsView)
self.setCentralWidget(widget)

def mouseMoveEvent(self, event):
if event.buttons() == QtCore.Qt.NoButton:
print("Simple mouse motion")
elif event.buttons() == QtCore.Qt.LeftButton:
print("Left click drag")
elif event.buttons() == QtCore.Qt.RightButton:
print("Right click drag")

def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
print("Press!")

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())

最佳答案

首先,您必须启用mouse-tracking :

        self.graphicsView.setMouseTracking(True)

然后你可以使用QGraphicsView的子类:

class GraphicsView(QtWidgets.QGraphicsView):   
def mouseMoveEvent(self, event):
if event.buttons() == QtCore.Qt.NoButton:
print("Simple mouse motion")
elif event.buttons() == QtCore.Qt.LeftButton:
print("Left click drag")
elif event.buttons() == QtCore.Qt.RightButton:
print("Right click drag")
super(GraphicsView, self).mouseMoveEvent(event)

def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
print("Press!")
super(GraphicsView, self).mousePressEvent(event)

或者安装一个事件过滤器:

        self.graphicsView.viewport().installEventFilter(self)
...

def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.MouseMove:
if event.buttons() == QtCore.Qt.NoButton:
print("Simple mouse motion")
elif event.buttons() == QtCore.Qt.LeftButton:
print("Left click drag")
elif event.buttons() == QtCore.Qt.RightButton:
print("Right click drag")
elif event.type() == QtCore.QEvent.MouseButtonPress:
if event.button() == QtCore.Qt.LeftButton:
print("Press!")
return super(Window, self).eventFilter(source, event)

关于python - 为什么 mouseMoveEvent 在 PyQt5 中什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992088/

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