pyQT5在QGraphicsView中通过鼠标交互式绘制长方形

pyQT5在QGraphicsView中通过鼠标交互式绘制长方形

代码如下

from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen, QColor, QPixmap

class MyGraphicsView(QGraphicsView):
    def __init__(self, parent=None):
        super(MyGraphicsView, self).__init__(parent)
        self.setScene(MyGraphicsScene())  # 设置场景

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.scene().startDrawingRect(event.pos())

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            self.scene().updateDrawingRect(event.pos())

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.scene().finishDrawingRect()

class MyGraphicsScene(QGraphicsScene):
    def __init__(self):
        super().__init__()
        self.addImage("img/entrance1.png")  # 添加图像
        self.drawing_rect = None

    def addImage(self, image_path):
        pixmap = QPixmap(image_path)
        if not pixmap.isNull():
            item = self.addPixmap(pixmap)
            item.setPos(0, 0)  # 设置图像的位置

    def startDrawingRect(self, pos):
        self.drawing_rect = QGraphicsRectItem(pos.x(), pos.y(), 1, 1)
        self.addItem(self.drawing_rect)

    def updateDrawingRect(self, pos):
        if self.drawing_rect:
            rect = self.drawing_rect.rect()
            rect.setWidth(pos.x() - rect.x())
            rect.setHeight(pos.y() - rect.y())
            self.drawing_rect.setRect(rect)

    def finishDrawingRect(self):
        self.drawing_rect = None

if __name__ == '__main__':
    app = QApplication([])
    window = MyGraphicsView()
    window.show()
    app.exec()

绘制结果

你可能感兴趣的:(pyQT开发,qt,python,开发语言)