首页 > 解决方案 > QGraphicsProxyWidget 搞乱了鼠标光标的变化

问题描述

我有一个QGraphicsView我做各种鼠标操作的地方,在做鼠标操作时我改变鼠标光标给用户视觉线索。

我最近将一些 QWidgets 放到我的场景中,它会自动创建QGraphicsProxyWidget对象。在放置这些小部件后,我的鼠标光标变化开始出现问题。我可以更改鼠标光标,直到将鼠标悬停在某个QGraphicsProxyWidget项目上。之后,我的鼠标光标更改停止生效。

我在 PySide2 中创建了一个最小的示例:

import sys

from PySide2.QtGui import QMouseEvent, Qt
from PySide2.QtWidgets import QApplication, QLabel, QGraphicsView, QGraphicsScene


class CustomGraphicsView(QGraphicsView):
    def mousePressEvent(self, event: QMouseEvent):
        super().mousePressEvent(event)

        self.setCursor(Qt.ClosedHandCursor)
        event.accept()

    def mouseReleaseEvent(self, event: QMouseEvent):
        super().mouseReleaseEvent(event)

        self.setCursor(Qt.ArrowCursor)
        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    graphics_view = CustomGraphicsView()
    scene = QGraphicsScene(0, 0, 1000, 1000)
    graphics_view.setScene(scene)

    label = QLabel("Hello World")
    label_font = label.font()
    label_font.setPointSize(50)
    label.setFont(label_font)

    label_proxy = scene.addWidget(label)
    label_proxy.setPos(400, 450)

    graphics_view.show()
    app.exec_()

要重现:首先,单击场景中的任意位置,但不要将鼠标悬停在“Hello World”文本上。您将看到鼠标光标变为闭合的手。然后将鼠标悬停在“Hello World”文本上并再次尝试单击场景中的任意位置。您将看到光标不再变化。

我不确定这是预期的行为还是错误。这种行为的原因可能是什么?

系统

操作系统:Windows 10 20H2

Python 3.8.6 64 位

PySide2 5.15.2

标签: pythonqtpyside2qgraphicsview

解决方案


免责声明:仍在调查该行为的原因,因此在撰写此答案时,我只会给出解决方案。但似乎 QGraphicsProxyWidget 没有正确处理事件的传播。有关更多信息,请参阅此错误

与其在 QGraphicsView 中设置光标,不如在视口中设置。

class CustomGraphicsView(QGraphicsView):
    def mousePressEvent(self, event: QMouseEvent):
        super().mousePressEvent(event)
        self.viewport().setCursor(Qt.ClosedHandCursor)
        event.accept()

    def mouseReleaseEvent(self, event: QMouseEvent):
        super().mouseReleaseEvent(event)
        self.viewport().unsetCursor()
        event.accept()

推荐阅读