使用graphicsView的完善的画图及保存方案

之前出现GraphicsView画图会出现的问题做了改进,去掉边框以及对位置进行了判断

from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
from PyQt5 import QtGui


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.wid = 1100
        self.heit = 600
        self.setFixedSize(self.wid,self.heit)
        self.setScene(QtWidgets.QGraphicsScene(self))
        self.pixmapItem = (
            QtWidgets.QGraphicsPixmapItem()
        )  # check if everytime you open a new image the old image is still an item
        self.scene().addItem(self.pixmapItem)
        # self.scene().setSceneRect()
        self._path_item = None
        self.img = None
        self.filename = ""
        self.setFrameStyle(QFrame.NoFrame)

    def initial_path(self):
        self._path = QtGui.QPainterPath()
        pen = QtGui.QPen(
            QtGui.QColor("red"), 1.5, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap
        )
        self._path_item = self.scene().addPath(self._path, pen)

    @QtCore.pyqtSlot()
    def setImage(self):
        self.filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, "select Image", "", "Image Files (*.png *.jpg *jpg *.bmp)"
        )
        if self.filename:
            pixmap1 = QtGui.QPixmap(self.filename)
            self.pixmapItem.setPixmap(pixmap1)

    def mousePressEvent(self, event):
        start = event.pos()
        if (
                not self.pixmapItem.pixmap().isNull()
                and event.buttons() & QtCore.Qt.LeftButton
        ):
            self.initial_path()
            self._path.moveTo(self.mapToScene(start))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if (
                not self.pixmapItem.pixmap().isNull()
                and event.buttons() & QtCore.Qt.LeftButton
                and self._path_item is not None
        ):

            x = event.x()
            if x < 1:
                x = 1
            if x > self.wid-1:
                x = self.wid-1
            y=event.y()
            if y<1:
                y=1
            if y > self.heit-1:
                y = self.heit-1
            pos = QPoint(x,y)
            # self._path.lineTo(self.mapToScene(event.pos()))
            self._path.lineTo(self.mapToScene(pos))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        x = event.x()
        if x < 1:
            x = 1
        if x > self.wid - 1:
            x = self.wid - 1
        y = event.y()
        if y < 1:
            y = 1
        if y > self.heit - 1:
            y = self.heit - 1
        end = QPoint(x, y)
        if (
                not self.pixmapItem.pixmap().isNull()
                and self._path_item is not None
        ):
            self._path.lineTo(self.mapToScene(end))
            self._path.closeSubpath()
            self._path_item.setPath(self._path)
            self._path_item.setBrush(QtGui.QBrush(QtGui.QColor("red")))
            # self._path_item.setFlag(
            #     QtWidgets.QGraphicsItem.ItemIsSelectable, True
            # )
            self._path_item = None

        super(GraphicsView, self).mouseReleaseEvent(event)

    def save(self):
        rect = self.scene().sceneRect()
        self.img = QtGui.QImage(rect.width(), rect.height(), QtGui.QImage.Format_RGB666)
        painter = QtGui.QPainter(self.img)
        rectf = QRectF(0, 0, self.img.rect().width(), self.img.rect().height())
        self.scene().render(painter, rectf, rect)
        filename, _ = QtWidgets.QFileDialog.getSaveFileName(
            None,"save Image", self.filename,"Image Files (*.png)"
        )
        if filename:
            self.img.save(filename)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = QWidget()
    btnSave = QPushButton("Save image")
    view = GraphicsView()
    view.setImage()
    w.setLayout(QVBoxLayout())
    w.layout().addWidget(btnSave)
    w.layout().addWidget(view)
    btnSave.clicked.connect(lambda: view.save())
    w.show()
    sys.exit(app.exec_())


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将PyQt中GraphicsView中的图像保存为文件,可以使用以下步骤: 1. 使用QPixmap将GraphicsView中的视图转换为图像: ```python pixmap = QPixmap.grabWidget(graphicsView) ``` 2. 将图像保存到文件中: ```python pixmap.save("image.png") ``` 完整的代码示例: ```python from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QMainWindow, QApplication from PyQt5.QtGui import QPixmap import sys class MyWindow(QMainWindow): def __init__(self): super().__init__() # 创建GraphicsView和场景 self.graphicsView = QGraphicsView() self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) # 添加一些元素到场景中 self.scene.addEllipse(0, 0, 100, 100) self.scene.addRect(50, 50, 100, 100) # 设置窗口大小和标题 self.setCentralWidget(self.graphicsView) self.setGeometry(100, 100, 500, 500) self.setWindowTitle("GraphicsView保存图像") # 添加保存按钮 self.saveButton = QPushButton("保存") self.saveButton.clicked.connect(self.saveImage) self.statusBar().addWidget(self.saveButton) def saveImage(self): # 使用QPixmap将GraphicsView中的视图转换为图像 pixmap = QPixmap.grabWidget(self.graphicsView) # 将图像保存到文件中 pixmap.save("image.png") self.statusBar().showMessage("图像已保存") if __name__ == '__main__': app = QApplication(sys.argv) window = MyWindow() window.show() sys.exit(app.exec_()) ``` 该程序将创建一个带有一些形状的GraphicsView窗口,并在窗口底部添加了一个保存按钮。单击该按钮将保存GraphicsView中的图像。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值