Important: Please read the Qt Code of Conduct -

How do I get coordinates of painted area ?

  • Hello, suppose I have canvas and I am letting user to paint on it with Qt.Brush.

    How do I get the information, where the paint is ?
    Ideally, I would like to get 2D occupancy matrix.
    For example, everywhere the user has NOT painted would be 0s and where he did
    there would be number (or tuple) associated with the colour.
    This is dream, I can live with any other format, that would convey that information.

    The naive approach would be to track the mouse and keep 2D matrix myself. Then use algebra, to find out where did the brush pixels go. The problem is, when you are using anything else than Qt.RoundCap - there is no simple algebraic way to find out where did the paint go.. When you have square pen, the pen is doing some weird rotations according to the speed of the pen, angle, whatnot.

    I am posting this Minimal-example code, so you will know exactly what I mean:
    Thank you

    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    import sys
    class Window(QMainWindow):
        def __init__(self):
            self.setGeometry(100, 100, 800, 600)
            self.image = QImage(self.size(), QImage.Format_RGB32)
            self.drawing = False
            self.brushSize = 70
            self.brushColor =
            self.lastPoint = QPoint()
        def mousePressEvent(self, event):
            if event.button() == Qt.LeftButton:
                self.drawing = True
                self.lastPoint = 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.SquareCap, Qt.RoundJoin))
                painter.drawLine(self.lastPoint, event.pos())
                self.lastPoint = event.pos()
        def mouseReleaseEvent(self, event):
            if event.button() == Qt.LeftButton:
                self.drawing = False
        def paintEvent(self, event):
            canvasPainter = QPainter(self)
            canvasPainter.drawImage(self.rect(), self.image, self.image.rect())
    App = QApplication(sys.argv)
    window = Window()

Log in to reply