pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的坐标 完整代码
时间: 2023-12-22 14:05:56 浏览: 72
好的,下面是一个完整的示例代码,可以实现你的需求:
```python
import sys
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView
class GraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.setSceneRect(0, 0, 800, 600)
self.image_item = None
self.rect_item = None
self.start_pos = None
self.end_pos = None
def load_image(self, filename):
self.scene.clear()
pixmap = QPixmap(filename)
self.image_item = self.scene.addPixmap(pixmap)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.start_pos = self.mapToScene(event.pos())
def mouseMoveEvent(self, event):
if self.start_pos is not None:
self.end_pos = self.mapToScene(event.pos())
self.draw_rect()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.end_pos = self.mapToScene(event.pos())
self.draw_rect()
self.start_pos = None
self.end_pos = None
def draw_rect(self):
if self.rect_item is not None:
self.scene.removeItem(self.rect_item)
x = min(self.start_pos.x(), self.end_pos.x())
y = min(self.start_pos.y(), self.end_pos.y())
w = abs(self.start_pos.x() - self.end_pos.x())
h = abs(self.start_pos.y() - self.end_pos.y())
self.rect_item = self.scene.addRect(QRectF(x, y, w, h), QPen(QColor("red"), 2, Qt.SolidLine))
def get_rect_coordinates(self):
if self.rect_item is not None:
rect = self.rect_item.rect()
x = rect.x()
y = rect.y()
w = rect.width()
h = rect.height()
return x, y, w, h
else:
return None
if __name__ == "__main__":
app = QApplication(sys.argv)
view = GraphicsView()
view.load_image("test.jpg")
view.show()
sys.exit(app.exec_())
```
在这个示例代码中,我们创建了一个继承自 `QGraphicsView` 的类 `GraphicsView`,并重写了其鼠标事件。其中,`load_image` 方法用于加载图片,`draw_rect` 方法用于绘制红色矩形,`get_rect_coordinates` 方法用于获取矩形的坐标信息。
你只需要在 `load_image` 方法中传入你要加载的图片路径,然后运行程序即可。在程序运行时,你可以使用鼠标在图片上框选红色矩形,矩形的坐标信息可以通过 `get_rect_coordinates` 方法获取。
阅读全文