pyqt5已有一个self.graphicsView控件,怎问怎样为其加上加载显示图片,并可以在图片上框选红色矩形返回矩形在图片的坐标
时间: 2024-02-01 18:13:06 浏览: 105
你可以使用QGraphicsScene和QGraphicsView来显示图片,并在场景上绘制矩形。下面是一个简单的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView
from PyQt5.QtGui import QPixmap, QPen, QColor
from PyQt5.QtCore import Qt
class ImageViewer(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.image_item = None
self.rect_item = None
self.start_pos = None
self.end_pos = None
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
def load_image(self, filename):
pixmap = QPixmap(filename)
self.scene.clear()
self.image_item = self.scene.addPixmap(pixmap)
self.setSceneRect(pixmap.rect())
self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
def mousePressEvent(self, event):
if not self.rect_item:
self.start_pos = event.pos()
self.rect_item = self.scene.addRect(0, 0, 0, 0, QPen(QColor(255, 0, 0)))
self.rect_item.setZValue(1)
self.rect_item.setFlag(self.rect_item.ItemIsMovable, False)
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.rect_item:
self.end_pos = event.pos()
rect = self.get_rect_from_points(self.start_pos, self.end_pos)
self.rect_item.setRect(rect)
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.rect_item:
self.end_pos = event.pos()
rect = self.get_rect_from_points(self.start_pos, self.end_pos)
self.rect_item.setRect(rect)
self.rect_item = None
print("Selected Rect:", rect)
super().mouseReleaseEvent(event)
def get_rect_from_points(self, pt1, pt2):
x1, y1 = pt1.x(), pt1.y()
x2, y2 = pt2.x(), pt2.y()
return QtCore.QRectF(min(x1, x2), min(y1, y2), abs(x2 - x1), abs(y2 - y1))
if __name__ == '__main__':
app = QApplication(sys.argv)
viewer = ImageViewer()
viewer.load_image("image.jpg")
viewer.show()
sys.exit(app.exec_())
```
这个示例代码实现了以下功能:
1. 加载显示图片
2. 在图片上框选红色矩形
3. 返回矩形在图片的坐标
你可以根据自己的需求进行修改和扩展。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)