Important: Please read the Qt Code of Conduct -

Saving an image after painting on it

  • What i am trying to do is be able to draw on an image (specifically rectangles) and then save the image. I have found the following code:

    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    import sys
    class Window(QMainWindow):
        def __init__(self):
            self.image = QImage("img.png")
            # self.showFullScreen()
            self.startPos = None
            self.rect = QRect()
            self.drawing = False
        def mousePressEvent(self, event):
            if event.button() == Qt.LeftButton and not self.drawing:
                self.startPos = event.pos()
                self.rect = QRect(self.startPos, self.startPos)
                self.drawing = True
        def mouseMoveEvent(self, event):
            if self.drawing == True:
                self.rect = QRect(self.startPos, event.pos())
        def mouseReleaseEvent(self, event):
            if event.button() == Qt.LeftButton:
                self.drawing = False
        def paintEvent(self, event):
            pen = QPen()
            pen.setColor(QColor(255, 0, 0))
            brush = QBrush()
            brush.setColor(QColor(255, 0, 0))
            painter = QPainter(self)
            painter.drawImage(0, 0, self.image)
            if not self.rect.isNull():
    app = QApplication(sys.argv)
    window = Window()

    From this forum post:

    However when i try and save the image, it just saves the original without the rectangle. Also, it allows for drawing outside the boundaries of the image which i do not want

    How can i fix these issues?

  • Lifetime Qt Champion


    You have to paint on the QImage if you want these changes to be storable.

    You can do that in the method that saves the image. Do the painting on a copy of it and save it after.

  • @SGaist Hi, I'm not really sure how i would do that, can you point me in the right direction?

  • Lifetime Qt Champion


    1. create a copy of the image
    2. create a QPainter on it
    3. draw
    4. call end
    5. save the copy

  • @SGaist Sorry but i have no idea how to call a qpainter on the image as well as creating a copy, can i have some actual code?

    Appeciate the help

    Just to add i understand what you're saying so you don't need to simplify it , just not how to implement it with pyqt

  • Lifetime Qt Champion

    For the copy, please read the class documentation. It's QImage::copy.

    For painting on the QImage:

    painter = QPainter(image)
    # paint what you want

  • Banned

    This post is deleted!

Log in to reply