pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并打印矩形在图片上的坐标 完整代码
时间: 2023-12-22 09:05:56 浏览: 59
好的,基于之前的代码,我稍作修改,加入了打印矩形坐标的功能。下面是完整的示例代码:
```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
self.print_rect_coordinates()
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 print_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()
print("Rectangle coordinates: ({}, {}, {}, {})".format(x, y, w, h))
if __name__ == "__main__":
app = QApplication(sys.argv)
view = GraphicsView()
view.load_image("test.jpg")
view.show()
sys.exit(app.exec_())
```
在这个示例代码中,我们在 `mouseReleaseEvent` 方法中调用了新添加的 `print_rect_coordinates` 方法,用于打印矩形坐标。当你在图片上框选红色矩形并松开鼠标时,矩形的坐标信息会被打印出来。
阅读全文