PyQt4 - QGraphicsItem position doesn't map into scene properly after drag

前端 未结 1 590
萌比男神i
萌比男神i 2021-02-04 22:18

I\'ve created a ImageView widget based on QWidget that contains a QGraphicsView. This widget shows an image and lets you draw a ROI (regio

1条回答
  •  醉梦人生
    2021-02-04 22:54

    Your issue occurs because of the way you are using the QGraphicsRectItem. While you are setting the rectangle correctly initially, the item is originally placed at coordinates (0,0) of the scene. As such, the QGraphicsRectItem extends from (0,0) to the bottom right coordinate of your rectangle (in scene coordinates).

    When you move the ROI, you are translating the entire item, not just the rectangle within the item. Which means the item is no longer located at (0,0), and so the coordinates you are feeding it are offset because you are using scene coordinates rather than item coordinates.

    There are various methods (such as QGraphicsItem.mapFromScene()) which can translate the coordinates to the correct reference points (note that this should take into account the fact that your ROI is a child of self.image_item as well if that ever gets moved away from (0,0)).

    Another alternative is that you could relocate the ROI to the initial click coordinate, and then size it according to the difference between the initial click coordinate and the current click coordinate. So in the mouseMoveEvent you could do:

    self.ROI_item.setPos(self.event_origin)
    self.ROI_item.setRect(QtCore.QRectF(QtCore.QPointF(0,0), event_pos-self.event_origin).normalized())
    

    However, I suspect this may break if the parent item is moved, or if there is scaling applied to the QGraphicsView. In such cases you would probably need to investigate using the QGraphicsItem.mapFromScene() method (although it is likely to be useful to always relocate the item to the initial click position, if only to reduce the bounding box of the item)

    0 讨论(0)
提交回复
热议问题