PyQt5 – Create Paint Application

08 Oct, 2021
There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.
In this article we will see how we can create a Paint application using PyQt5. Our Paint application will consist of following
 Features :
User can select different brush sizes User can select different brush color Saving of the canvas Clearing the whole canvas at once  
User can select different brush sizes 
User can select different brush color 
Saving of the canvas 
Clearing the whole canvas at once  
Steps for designing the widgets –1. Create a window sets its geometry and title 2. Create menu bar 3. Inside menu bar add different menus, that are file menu, size menu and color menu 4. Add save and clear action to the file menu  
5. Add different brush sizes action to the brush size menu  
6. Add different brush color action to the brush color menu  
7. Create a white canvas and add it to the window
Back-end steps :1. Create different variable : Drawing flag to check if currently drawing or not and set it to False, brush size variable to set current brush size,     brush color to set current brush color and current position variable to know position of cursor 2. Add action to the clear and save widget 3. Inside clear action fill the canvas with white color 4. Inside the save action save the canvas 5. Add actions(methods) to various brush sizes and color to set size and color 6. Create paint event to draw white canvas on the screen 7. Create method to know when mouse left button is pressed inside that method make drawing flag true and change the current position 8. Create method for mouse movement, inside this method check if drawing flag is true and button is still pressed then draw using painter     object and change the position according. 9. Create a method to know mouse button is released inside this method make drawing flag to false.
Below is the implementation 
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *import sys # window classclass Window(QMainWindow):    def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Paint with PyQt5")         # setting geometry to main window        self.setGeometry(100, 100, 800, 600)         # creating image object        self.image = QImage(self.size(), QImage.Format_RGB32)         # making image color to white        self.image.fill(Qt.white)         # variables        # drawing flag        self.drawing = False        # default brush size        self.brushSize = 2        # default color        self.brushColor = Qt.black         # QPoint object to tract the point        self.lastPoint = QPoint()         # creating menu bar        mainMenu = self.menuBar()         # creating file menu for save and clear action        fileMenu = mainMenu.addMenu("File")         # adding brush size to main menu        b_size = mainMenu.addMenu("Brush Size")         # adding brush color to ain menu        b_color = mainMenu.addMenu("Brush Color")         # creating save action        saveAction = QAction("Save", self)        # adding short cut for save action        saveAction.setShortcut("Ctrl + S")        # adding save to the file menu        fileMenu.addAction(saveAction)        # adding action to the save        saveAction.triggered.connect(self.save)         # creating clear action        clearAction = QAction("Clear", self)        # adding short cut to the clear action        clearAction.setShortcut("Ctrl + C")        # adding clear to the file menu        fileMenu.addAction(clearAction)        # adding action to the clear        clearAction.triggered.connect(self.clear)         # creating options for brush sizes        # creating action for selecting pixel of 4px        pix_4 = QAction("4px", self)        # adding this action to the brush size        b_size.addAction(pix_4)        # adding method to this        pix_4.triggered.connect(self.Pixel_4)         # similarly repeating above steps for different sizes        pix_7 = QAction("7px", self)        b_size.addAction(pix_7)        pix_7.triggered.connect(self.Pixel_7)         pix_9 = QAction("9px", self)        b_size.addAction(pix_9)        pix_9.triggered.connect(self.Pixel_9)         pix_12 = QAction("12px", self)        b_size.addAction(pix_12)        pix_12.triggered.connect(self.Pixel_12)         # creating options for brush color        # creating action for black color        black = QAction("Black", self)        # adding this action to the brush colors        b_color.addAction(black)        # adding methods to the black        black.triggered.connect(self.blackColor)         # similarly repeating above steps for different color        white = QAction("White", self)        b_color.addAction(white)        white.triggered.connect(self.whiteColor)         green = QAction("Green", self)        b_color.addAction(green)        green.triggered.connect(self.greenColor)         yellow = QAction("Yellow", self)        b_color.addAction(yellow)        yellow.triggered.connect(self.yellowColor)         red = QAction("Red", self)        b_color.addAction(red)        red.triggered.connect(self.redColor)      # method for checking mouse cicks    def mousePressEvent(self, event):         # if left mouse button is pressed        if event.button() == Qt.LeftButton:            # make drawing flag true            self.drawing = True            # make last point to the point of cursor            self.lastPoint = event.pos()     # method for tracking mouse activity    def mouseMoveEvent(self, event):                 # checking if left button is pressed and drawing flag is true        if (event.buttons() & Qt.LeftButton) & self.drawing:                         # creating painter object            painter = QPainter(self.image)                         # set the pen of the painter            painter.setPen(QPen(self.brushColor, self.brushSize,                            Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))                         # draw line from the last point of cursor to the current point            # this will draw only one step            painter.drawLine(self.lastPoint, event.pos())                         # change the last point            self.lastPoint = event.pos()            # update            self.update()     # method for mouse left button release    def mouseReleaseEvent(self, event):         if event.button() == Qt.LeftButton:            # make drawing flag false            self.drawing = False     # paint event    def paintEvent(self, event):        # create a canvas        canvasPainter = QPainter(self)                 # draw rectangle  on the canvas        canvasPainter.drawImage(self.rect(), self.image, self.image.rect())     # method for saving canvas    def save(self):        filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "",                          "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")         if filePath == "":            return        self.image.save(filePath)     # method for clearing every thing on canvas    def clear(self):        # make the whole canvas white        self.image.fill(Qt.white)        # update        self.update()     # methods for changing pixel sizes    def Pixel_4(self):        self.brushSize = 4     def Pixel_7(self):        self.brushSize = 7     def Pixel_9(self):        self.brushSize = 9     def Pixel_12(self):        self.brushSize = 12     # methods for changing brush color    def blackColor(self):        self.brushColor = Qt.black     def whiteColor(self):        self.brushColor = Qt.white     def greenColor(self):        self.brushColor = Qt.green     def yellowColor(self):        self.brushColor = Qt.yellow     def redColor(self):        self.brushColor = Qt.red   # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # showing the windowwindow.show() # start the appsys.exit(App.exec())
Output : 
 
simmytarika5
PyQt-exercise
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.