pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的坐标,滑动滚轮可根据鼠标位置进行放大缩小
时间: 2024-02-23 14:01:43 浏览: 215
好的,这是一个比较复杂的问题,需要分几个步骤来实现。
第一步是加载图片到 GraphicsView 中。可以使用 QGraphicsScene 和 QGraphicsPixmapItem 来实现。代码如下:
```python
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsPixmapItem
from PyQt5.QtGui import QPixmap
class ImageView(QGraphicsView):
def __init__(self):
super().__init__()
self.setScene(QGraphicsScene(self))
self.image_item = QGraphicsPixmapItem()
self.scene().addItem(self.image_item)
def load_image(self, image_path):
pixmap = QPixmap(image_path)
self.image_item.setPixmap(pixmap)
self.setSceneRect(pixmap.rect())
```
第二步是实现鼠标框选红色矩形。可以在 GraphicsView 上监听鼠标按下和鼠标释放事件,计算出矩形的坐标,并绘制出来。代码如下:
```python
from PyQt5.QtCore import QPointF, QRectF, Qt
from PyQt5.QtGui import QPen, QBrush, QColor
from PyQt5.QtWidgets import QGraphicsSceneMouseEvent
class ImageView(ImageView):
def __init__(self):
super().__init__()
self.setDragMode(QGraphicsView.RubberBandDrag)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.setRenderHint(QPainter.HighQualityAntialiasing)
self.setRenderHint(QPainter.NonCosmeticDefaultPen)
self.pen = QPen(Qt.red)
self.pen.setWidth(2)
self.brush = QBrush(QColor(255, 0, 0, 50))
self.rect_item = None
def mousePressEvent(self, event: QGraphicsSceneMouseEvent) -> None:
if event.button() == Qt.LeftButton:
self.start_point = event.scenePos()
def mouseReleaseEvent(self, event: QGraphicsSceneMouseEvent) -> None:
if event.button() == Qt.LeftButton:
end_point = event.scenePos()
rect = QRectF(self.start_point, end_point).normalized()
if self.rect_item is not None:
self.scene().removeItem(self.rect_item)
self.rect_item = self.scene().addRect(rect, self.pen, self.brush)
x, y, w, h = rect.getRect()
print(f"Rectangle position: ({x}, {y}), size: ({w}, {h})")
```
第三步是根据鼠标位置进行放大缩小。可以在 GraphicsView 上监听鼠标滚轮事件,计算出缩放比例,并进行缩放。代码如下:
```python
class ImageView(ImageView):
def __init__(self):
super().__init__()
# ...
def wheelEvent(self, event) -> None:
zoom_in_factor = 1.25
zoom_out_factor = 1 / zoom_in_factor
zoom = zoom_in_factor if event.angleDelta().y() > 0 else zoom_out_factor
self.scale(zoom, zoom)
pos = event.pos()
center_point = self.mapToScene(pos)
self.centerOn(center_point)
```
这样,就实现了在 GraphicsView 中加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的坐标,滑动滚轮可根据鼠标位置进行放大缩小的功能。
阅读全文