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

前端 未结 1 580
我在风中等你
我在风中等你 2021-01-23 21:03

I have written a code to draw a rectangle on an image in a QGraphicsView but if I resize the image, for example full screen, the position of the rectangle becom

相关标签:
1条回答
  • 2021-01-23 21:48

    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)
    
    0 讨论(0)
提交回复
热议问题