pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的坐标
时间: 2023-12-22 07:05:56 浏览: 76
可以通过以下代码实现pyqt5 graphicsView加载显示图片,并在图片上鼠标框选红色矩形并返回矩形在图片上的坐标。
```python
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPixmap, QColor, QPen
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsRectItem, QApplication, QMainWindow
class GraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setRenderHint(QPainter.Antialiasing)
def setImage(self, image):
self.image = QPixmap(image)
self.scene.clear()
self.scene.setSceneRect(QRectF(self.image.rect()))
self.scene.addPixmap(self.image)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = event.pos()
self.rubberBand = QGraphicsRectItem()
self.rubberBand.setPen(QPen(QColor(Qt.red), 2, Qt.SolidLine))
self.scene.addItem(self.rubberBand)
self.rubberBand.setPos(self.mapToScene(self.origin))
def mouseMoveEvent(self, event):
if hasattr(self, 'rubberBand'):
self.rubberBand.setRect(QRectF(self.origin, event.pos()).normalized())
def mouseReleaseEvent(self, event):
if hasattr(self, 'rubberBand'):
rect = self.rubberBand.rect()
rect = rect.normalized()
rect = QRectF(self.mapToScene(rect.topLeft()), self.mapToScene(rect.bottomRight()))
print(rect.x(), rect.y(), rect.width(), rect.height())
self.scene.removeItem(self.rubberBand)
del self.rubberBand
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.view = GraphicsView(self)
self.setCentralWidget(self.view)
self.view.setImage('image.jpg')
self.show()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
在上面的代码中,我们使用QGraphicsView来显示图片,鼠标按下时在场景中添加了一个QGraphicsRectItem,然后在鼠标移动时更新QGraphicsRectItem的大小,最后在释放鼠标时将QGraphicsRectItem的坐标转换成图片上的坐标并输出。
阅读全文