I’m trying to select the reference to the image for this I am trying to drag my mouse on to my image But when I am doing it the image is shifting according to how i am dragging my mouse for selecting the refernce. For this, I used AI to correct it and it still did not solve the problem if not added one.
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
New contributor
nothingspecial is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.