0

I'm learning PyQt5, and I'd like my GUI to have kind of a drawing surface, on which the user can draw anything, so the app can then get this drawing as an image (the goal is to perform classification on that drawing).

How can I do that ? All I found is Qpainter, which allow me to draw when coding the app, but it won't let the user dynamically draw when using the app.

Haezer
  • 457
  • 5
  • 15

1 Answers1

0

QPainter is a surface for drawing. Here is an example of drawing a rectangular flag:

import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 200, 200)
        self.setWindowTitle('Drawing')
        self.show()

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.drawFlag(qp)
        qp.end()

    def drawFlag(self,qp):
        qp.setBrush(QColor(255, 0, 0))
        qp.drawRect(30, 30, 120, 30)
        qp.setBrush(QColor(0, 255, 0))
        qp.drawRect(30, 60, 120, 30)
        qp.setBrush(QColor(0, 0, 255))
        qp.drawRect(30, 90, 120, 30)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

If you want to draw a line use:

qp.drawLine(x1, y1, x2, y2)

Mouse position:

def mouseMoveEvent(self, event):
    print(event.x, event.y)
Qolorer
  • 1
  • 3