Skip to content Skip to sidebar Skip to footer

PyQT5: How To Interactively Paint On Image Within QLabel Widget?

Python 3, latest version of PyQt5 on Mac OS Mojave I want a PyQt5 program in which the user could paint connected dots on an image (click distinctively and the points are automatic

Solution 1:

Try it:

import sys
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui     import *

class MyScribbling(QMainWindow):
    def __init__(self):
        super().__init__()
        self.penOn = QAction(QIcon('Image/ok.png'), 'ON   drawing', self)
        self.penOn.triggered.connect(self.drawingOn)
        self.penOff = QAction(QIcon('Image/exit.png'), 'OFF drawing', self)
        self.penOff.triggered.connect(self.drawingOff)
        toolbar = self.addToolBar('Tools')
        toolbar.addAction(self.penOn)
        toolbar.addAction(self.penOff)

        self.scribbling = False
        self.myPenColor = Qt.red      
        self.myPenWidth = 3           

        self.lastPoint = QPoint()
        self.image     = QPixmap("Image/picture.png")
        self.setFixedSize(600, 600)
        self.resize(self.image.width(), self.image.height())
        self.setWindowTitle("drawing On / Off")

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.image)

    def mousePressEvent(self, event):
        if (event.button() == Qt.LeftButton) and self.scribbling: 
            self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):
        if (event.buttons() & Qt.LeftButton) and self.scribbling:
            painter = QPainter(self.image)
            painter.setPen(QPen(self.myPenColor, self.myPenWidth, 
                                Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.update()

    def drawingOn(self):
        self.scribbling = True

    def drawingOff(self):
        self.scribbling = False

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

enter image description here


Post a Comment for "PyQT5: How To Interactively Paint On Image Within QLabel Widget?"