How do I keep drawing on image after window resize in PyQt?

倖福魔咒の 提交于 2019-12-02 03:47:00

You have the following errors:

  • The coordinates of the scene are different from the coordinates of the view, so you must use the mapToScene() method if you want to establish the right position of the rectangle.

  • Why do you add and remove the items? the best thing is to reuse

  • You want the position of the rectangle to be relative to the QGraphicsPixmapItem, so the rectangle has to be a child of the QGraphicsPixmapItem.

Using the above we obtain the following:

class GraphicsView(QGraphicsView):
    def __init__(self):
        super().__init__()
        self.setScene(QGraphicsScene())
        self.item = QGraphicsPixmapItem(QPixmap('test.jpg'))
        self.scene().addItem(self.item)
        self.rect_item = QGraphicsRectItem(QRectF(), self.item)
        self.rect_item.setPen(QPen(QColor(51, 153, 255), 2, Qt.SolidLine))
        self.rect_item.setBrush(QBrush(QColor(0, 255, 0, 40)))

    def mousePressEvent(self, event):
        self.pi = self.mapToScene(event.pos())
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        pf = self.mapToScene(event.pos())
        if (self.pi - pf).manhattanLength() > QApplication.startDragDistance():
            self.pf = pf
            self.draw_rect()
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        pf = self.mapToScene(event.pos())
        if (self.pi - pf).manhattanLength() > QApplication.startDragDistance():
            self.pf = pf
            self.draw_rect()
        super().mouseReleaseEvent(event)

    def draw_rect(self):
        r = QRectF(self.pi, self.pf).normalized()
        r = self.rect_item.mapFromScene(r).boundingRect()
        self.rect_item.setRect(r)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!