我正在尝试选择对图像的引用,为此,我尝试将鼠标拖到图像上,但是当我这样做时,图像会根据我拖动鼠标进行选择的方式而移动......
我正在尝试选择图像的引用,我正尝试将鼠标拖到图像上,但当我这样做时,图像会根据我拖动鼠标选择引用的方式而移动。为此,我使用 AI 来纠正它,但如果不添加它,它仍然无法解决问题。
def drawBackground(self, painter: QPainter, rect: QRectF):
display_width = self._parent.width()
display_height = self._parent.height()
image_width = self._image.width()
image_height = self._image.height()
# Maintain aspect ratio
image_aspect_ratio = image_width / image_height
display_aspect_ratio = display_width / display_height
if display_aspect_ratio > image_aspect_ratio:
# Scale based on height
scaled_height = display_height
scaled_width = image_aspect_ratio * scaled_height
else:
# Scale based on width
scaled_width = display_width
scaled_height = scaled_width / image_aspect_ratio
# Center the image in the display area
image_pos_x = (display_width - scaled_width) / 2
image_pos_y = (display_height - scaled_height) / 2
# Save the current state of the painter before transformation
painter.save()
# Apply scaling and translation to the painter
painter.translate(image_pos_x, image_pos_y)
painter.scale(scaled_width / image_width, scaled_height / image_height)
# Draw the image (this ensures the image is scaled and translated properly)
painter.drawImage(QRectF(0, 0, image_width, image_height), self._image)
# Restore painter to its previous state (removes the transformation)
painter.restore()
# Now draw any overlays like crosshairs, ROI, etc., in the same coordinates as the image.
# Ensure any reference elements are drawn relative to the scaled and translated image.
# For example, you can draw a crosshair at the center of the image:
crosshair_x = image_width / 2
crosshair_y = image_height / 2
painter.setPen(QPen(Qt.red, 2)) # Set crosshair color and thickness
painter.drawLine(crosshair_x - 10, crosshair_y, crosshair_x + 10, crosshair_y) # Horizontal line
painter.drawLine(crosshair_x, crosshair_y - 10, crosshair_x, crosshair_y + 10) # Vertical