为什么mousemovevent在PyQt5中什么都不做

2024-04-25 00:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在PyQt5和Python3.5中使用mouseMoveEvent和mousepresessvent,但是当我单击鼠标时什么也没有。我的代码如下,有什么问题吗?

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_())

Tags: importselfeventifdefsyswidgetqt
2条回答

首先,必须启用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)

我确信您的事件是在QGraphicsView内部处理的。您必须阅读更多关于事件传播的信息。尝试一下,不要在窗口顶部添加任何额外的小部件。并且不要忘记abt MouseTracking属性,默认情况下该属性为false,并且没有按钮的鼠标移动事件根本不会发生。

我建议阅读this文章。它已经很老了,但仍然是相关的。另外,QGraphicsView中的鼠标事件以不同的方式处理,请阅读docs了解更多详细信息。

因为我是C++开发人员,所以没有代码示例。

相关问题 更多 >