QGraphicsScene 中 Qrubberband 的错误渲染

Bad rendering of Qrubberband in QGraphicsScene

我的 q qrubberband 显示不正确,我认为想要的坐标没问题:

class Viewer(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphicsView = QtWidgets.QGraphicsView()
        self.hbox = QtWidgets.QVBoxLayout()
        self.scene = Scene(self)
        self.splitter = QtWidgets.QSplitter()
        self.splitter.addWidget(self.graphicsView)
        self.widget.setLayout(self.hbox)
        self.setCentralWidget(self.widget)

我在场景中加载了一个像素图:

def open_picture(self):
        self.scene.setSceneRect(0, 0, self.pixmap.width(), self.pixmap.height())
        self.scene.addPixmap(self.pixmap)                  
        self.graphicsView.setScene(self.scene)              
        self.graphicsView.show()

我有从 QGraphicsScene 继承的场景,主要是在场景中处理一个 qrubberband

class Scene(QtWidgets.QGraphicsScene):

    def __init__(self, parent=None):
        super(Scene, self).__init__(parent)

    def mousePressEvent(self, event):
        self.originQPoint = event.scenePos()
        self.originQPoint = self.originQPoint.toPoint()
        self.currentQRubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle)

    def mouseMoveEvent(self, event):
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, event.scenePos().toPoint()).normalized())
        self.currentQRubberBand.show()

    def mouseReleaseEvent(self, event):
        print(self.items)
        self.currentQRubberBand.hide()
        self.currentQRect = self.currentQRubberBand.geometry()
        print(self.currentQRect)

我的问题是我的笔记本电脑屏幕上显示的是矩形,但坐标没问题(场景坐标) 如何在不更改 self.currentQRect 值的情况下正确绘制场景中的橡皮筋?

根据 docs:

QPointF QGraphicsSceneMouseEvent::scenePos() const

Returns the mouse cursor position in scene coordinates.

从上面我们可以得出结论,我们得到的点是相对于场景的,而不是相对于屏幕的,所以这不是我们想要的。

使用方法是screenPos():

QPoint QGraphicsSceneMouseEvent::screenPos() const

Returns the mouse cursor position in screen coordinates.

通过以上我们得到如下代码:

class Scene(QtWidgets.QGraphicsScene):
    def __init__(self, parent=None):
        super(Scene, self).__init__(parent)

    def mousePressEvent(self, event):
        self.originQPoint = event.screenPos()
        self.currentQRubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle)
        self.originCropPoint = event.scenePos()

    def mouseMoveEvent(self, event):
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, event.screenPos()))
        self.currentQRubberBand.show()

    def mouseReleaseEvent(self, event):
        self.currentQRubberBand.hide()
        currentQRect = self.currentQRubberBand.geometry()
        self.currentQRect = QtCore.QRect(self.originCropPoint.toPoint(), event.scenePos().toPoint())
        print(self.currentQRect)