pyqt5 graphicview 加载图片后点击图片后,在周围框选一个100*100的红色透明矩形,并返回矩形坐标 完整代码
时间: 2024-02-24 09:00:03 浏览: 190
以下是一个使用 PyQt5 的 QGraphicsView 控件加载图片,并在点击图片后绘制一个红色透明矩形的示例代码。当用户点击矩形时,程序会将矩形的坐标打印出来。
```python
import sys
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPixmap, QColor, QPainter, QPen, QBrush
from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView
class ImageViewer(QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.setSceneRect(0, 0, self.width(), self.height())
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.image_item = None
self.rect_item = None
self.rect_start_pos = None
def load_image(self, filename):
pixmap = QPixmap(filename)
self.scene.clear()
self.image_item = self.scene.addPixmap(pixmap)
self.setSceneRect(QRectF(pixmap.rect()))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton and self.image_item is not None:
self.rect_start_pos = event.pos()
self.rect_item = self.scene.addRect(0, 0, 0, 0, QPen(Qt.red), QBrush(QColor(255, 0, 0, 50)))
def mouseMoveEvent(self, event):
if self.rect_item is not None and self.rect_start_pos is not None:
rect = QRectF(self.rect_start_pos, event.pos()).normalized()
self.rect_item.setRect(rect)
def mouseReleaseEvent(self, event):
if self.rect_item is not None and self.rect_start_pos is not None:
rect = QRectF(self.rect_start_pos, event.pos()).normalized()
if rect.width() > 100 and rect.height() > 100:
print(rect.x(), rect.y(), rect.width(), rect.height())
self.rect_item = None
self.rect_start_pos = None
if __name__ == '__main__':
app = QApplication(sys.argv)
viewer = ImageViewer()
viewer.load_image('test.jpg')
viewer.show()
sys.exit(app.exec_())
```
在这个例子中,我们使用了 QGraphicsView 控件来显示图片,并使用 QGraphicsScene 控件来管理所有的图形项。当用户点击鼠标左键时,程序会创建一个矩形图形项,并使用鼠标移动事件来更新矩形的大小和位置。当用户释放鼠标左键时,程序会检查矩形是否符合要求(宽度和高度都大于 100),并打印矩形的坐标。
阅读全文