PyQt5 - Create Paint Application

PyQt5 - Create Paint Application

Creating a simple paint application using PyQt5 involves leveraging the QPainter, QBrush, and QPen classes. Here's a basic example of a paint application:

  • Install the required package:
pip install pyqt5 
  • Sample code for the paint application:
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog from PyQt5.QtGui import QImage, QPainter, QPen from PyQt5.QtCore import Qt, QPoint class PaintApp(QMainWindow): def __init__(self): super().__init__() self.image = QImage(self.size(), QImage.Format_RGB32) self.image.fill(Qt.white) self.drawing = False self.brushSize = 2 self.brushColor = Qt.black self.last_point = QPoint() self.initUI() def initUI(self): self.setWindowTitle("PyQt5 Paint Application") self.button = QPushButton("Save", self) self.button.clicked.connect(self.save) self.button.move(10, 10) self.setGeometry(100, 100, 800, 600) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.drawing = True self.last_point = event.pos() def mouseMoveEvent(self, event): if (event.buttons() & Qt.LeftButton) & self.drawing: painter = QPainter(self.image) painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.last_point, event.pos()) self.last_point = event.pos() self.update() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.drawing = False def paintEvent(self, event): canvas_painter = QPainter(self) canvas_painter.drawImage(self.rect(), self.image, self.image.rect()) def save(self): file_path, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*)") if file_path == "": return self.image.save(file_path) app = QApplication(sys.argv) window = PaintApp() window.show() app.exec_() 

This code will create a basic PyQt5 application where you can draw with the left mouse button and save your drawing by clicking the "Save" button. The drawing canvas will automatically resize to the window size.

You can expand on this by adding more features like:

  • Different brush sizes.
  • Color pickers.
  • Different brush types (e.g., dotted line, dashed line).
  • Undo and redo functionality.
  • Loading an existing image to edit.

This is a basic demonstration, and a full-featured paint application would require additional tools, options, and a more comprehensive UI.


More Tags

diacritics aws-glue text-align node-modules tls1.2 twitter-bootstrap-3 web-applications transparent editorfor python-asyncio

More Programming Guides

Other Guides

More Programming Examples