PyQt5 QGraphicsView加载图片后,怎样框选矩形,并返回矩形在·图片上的坐标
时间: 2023-12-16 21:03:34 浏览: 101
Qt中在QLabel上载入图片后在上面画矩形框,并将矩形框选的区域显示
可以通过重写QGraphicsView的mousePressEvent、mouseMoveEvent和mouseReleaseEvent来实现框选矩形的功能,并计算矩形在图片上的坐标。
具体步骤如下:
1. 创建一个继承自QGraphicsView的自定义类,并在构造函数中设置一些必要的属性,如缩放、拖拽等。
2. 重写mousePressEvent,记录下鼠标按下时的坐标点。
3. 重写mouseMoveEvent,根据鼠标移动的坐标点,动态地绘制一个矩形框选区域。
4. 重写mouseReleaseEvent,记录下鼠标松开时的坐标点,并将框选区域的四个顶点的坐标转换为图片坐标系中的坐标。
下面是一个简单的示例代码:
```python
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class ImageView(QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.pixmap_item = QGraphicsPixmapItem()
self.scene.addItem(self.pixmap_item)
self.rect_item = QGraphicsRectItem()
self.rect_item.setPen(QPen(Qt.red, 2, Qt.SolidLine))
self.rect_item.setBrush(QBrush(Qt.transparent))
self.scene.addItem(self.rect_item)
self.start_point = None
self.end_point = None
def set_image(self, image_path):
pixmap = QPixmap(image_path)
self.pixmap_item.setPixmap(pixmap)
self.setSceneRect(QRectF(pixmap.rect()))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.start_point = event.pos()
self.rect_item.setRect(QRectF(self.start_point, QSizeF()))
self.rect_item.setVisible(True)
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.start_point is not None:
self.end_point = event.pos()
rect = QRectF(self.start_point, self.end_point).normalized()
self.rect_item.setRect(rect)
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.start_point is not None and self.end_point is not None:
rect = QRectF(self.start_point, self.end_point).normalized()
rect_mapped = self.mapToScene(rect).boundingRect()
print(f"Selected rect: {rect_mapped}")
self.start_point = None
self.end_point = None
self.rect_item.setVisible(False)
super().mouseReleaseEvent(event)
```
在使用时,可以通过set_image方法设置要显示的图片路径,然后通过鼠标框选矩形,最后在控制台输出矩形在图片上的坐标。
阅读全文