簡體   English   中英

為什么mouseMoveEvent在PyQt5中什么都不做

[英]Why mouseMoveEvent does nothing in PyQt5

我嘗試在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_())

首先,您必須啟用鼠標跟蹤

        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內部處理的。 您必須閱讀有關事件傳播的更多信息。 嘗試一下,不要在Window頂部添加任何其他小部件。 而且不要忘記abt MouseTracking屬性,該屬性默認情況下為false,並且根本沒有發生沒有按鈕的鼠標移動事件。

我建議閱讀這篇文章。 它已經很老了,但是仍然很重要。 此外, QGraphicsView中的鼠標事件以不同的方式處理,請閱讀文檔以獲取更多詳細信息。

Sory沒有代碼示例,因為我是C ++開發人員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM