QRubberBand move on QGraphicsView after resizing

可紊 提交于 2019-12-02 07:02:47

The problem is caused because the coordinate system of the image is not the same as that of the QRubberBand. So the solution is that you both share the same coordinate system and for this we add the QRubberBand to the scene.

from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.setScene(QtWidgets.QGraphicsScene(self))
        self.m_rubberBand = QtWidgets.QRubberBand(
            QtWidgets.QRubberBand.Rectangle
        )
        self.m_rubberBand.setGeometry(QtCore.QRect(-1, -1, 2, 2))
        self.m_rubberBand.hide()
        item = self.scene().addWidget(self.m_rubberBand)
        item.setZValue(1)
        self.m_draggable = False

        self.m_origin = QtCore.QPoint()

    def mousePressEvent(self, event):
        self.m_origin = self.mapToScene(event.pos()).toPoint()

        self.m_rubberBand.setGeometry(
            QtCore.QRect(self.m_origin, QtCore.QSize())
        )
        self.m_rubberBand.show()

        self.m_draggable = True
        super(GraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.m_draggable:
            end_pos = self.mapToScene(event.pos()).toPoint()
            self.m_rubberBand.setGeometry(
                QtCore.QRect(self.m_origin, end_pos).normalized()
            )
            self.m_rubberBand.show()

    def mouseReleaseEvent(self, event):
        end_pos = self.mapToScene(event.pos()).toPoint()
        self.m_rubberBand.setGeometry(
            QtCore.QRect(self.m_origin, end_pos).normalized()
        )
        self.m_draggable = False


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    photo = QtGui.QPixmap("image.jpg")
    w.scene().addPixmap(photo)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!