pyqt5 graphicsView 加载显示图片,在图片上鼠标框选红色矩形并返回矩形在图片上的实际坐标
时间: 2023-12-22 10:06:08 浏览: 27
要获取在图片上的实际坐标,需要知道图片的缩放比例。可以使用QGraphicsPixmapItem来替代QGraphicsScene.addPixmap()方法,这样可以获取到图片的缩放比例。然后将鼠标事件中的坐标转换为实际坐标。
下面是修改后的代码:
```python
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPixmap, QColor, QPen
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsPixmapItem, 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.pixmap_item = QGraphicsPixmapItem(self.image)
self.scene.addItem(self.pixmap_item)
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()))
x, y = rect.x() / self.pixmap_item.pixmap().width(), rect.y() / self.pixmap_item.pixmap().height()
w, h = rect.width() / self.pixmap_item.pixmap().width(), rect.height() / self.pixmap_item.pixmap().height()
print(x, y, w, h)
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_())
```
在上面的代码中,我们使用QGraphicsPixmapItem来添加图片,并在释放鼠标时将矩形的坐标转换为实际坐标。`x, y, w, h`分别表示矩形左上角的横坐标和纵坐标以及矩形的宽度和高度,都是相对于图片实际的宽度和高度的比例。