简体   繁体   中英

Draw over image in a QLabel with PyQt5

I want to draw over image with my mouse. I simplified the problem by this code. When i uncomment the line 31 the code doesn't work. My goal is to draw over the image i want to select from my PC and save the image after modify it.

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(QtWidgets.QMainWindow):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(581, 463)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.selectImgeBtn = QtWidgets.QPushButton(self.centralwidget)
        self.selectImgeBtn.setGeometry(QtCore.QRect(50, 80, 121, 61))
        font = QtGui.QFont()
        font.setFamily("Roboto")
        font.setPointSize(11)
        self.selectImgeBtn.setFont(font)
        self.selectImgeBtn.setObjectName("selectImgeBtn")

        self.drawing = False
        self.brushSize = 2
        self.brushColor = QtCore.Qt.black
        self.lastPoint = QtCore.QPoint()

        self.imageLb = QtWidgets.QLabel(self.centralwidget)
        self.imageLb.setGeometry(QtCore.QRect(210, 10, 331, 201))
        self.imageLb.setFrameShape(QtWidgets.QFrame.Box)
        self.imageLb.setText("")
        self.imageLb.setObjectName("imageLb")
        self.imageLb.mousePressEvent = self.mousePressEvent
        self.imageLb.mouseMoveEvent = self.mouseMoveEvent
        self.imageLb.mouseReleaseEvent = self.mouseReleaseEvent
        # self.imageLb.paintEvent = self.paintEvent # When i uncomment this line the program is broken

        self.selectImgeBtn.clicked.connect(self.setImage)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.selectImgeBtn.setText(_translate("MainWindow", "Select Image"))

    def setImage(self):
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select Image", "", "Image Files (*.png *.jpg *.jpeg *.bmp)")
        if fileName:
            pixmap = QtGui.QPixmap(fileName)
            pixmap = pixmap.scaled(self.imageLb.width(), self.imageLb.height(), QtCore.Qt.KeepAspectRatio)
            self.imageLb.setPixmap(pixmap)
            self.imageLb.setAlignment(QtCore.Qt.AlignCenter)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.drawing = True
            self.lastPoint = event.pos()
            print(self.lastPoint)

    def mouseMoveEvent(self, event):
        if (event.buttons() == QtCore.Qt.LeftButton) and self.drawing:
            painter = QtGui.QPainter(self.imageLb)
            painter.setPen(QtGui.QPen(self.brushColor, self.brushSize, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
            painter.drawLine(self.lastPoint, event.pos())
            self.lastPoint = event.pos()
            self.imageLb.update()

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.drawing = False

    def paintEvent(self, event):
        canvasPainter = QtGui.QPainter(self)
        canvasPainter.drawImage(self.rect(), self.imageLb, self.imageLb.rect())


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Do not draw inside a widget outside of the paintEvent() . This is not supported by Qt.

You may draw on a QImage or QPixmap instead, and then in paintEvent() of your widget, draw that image. Images can be initialized with all pixels transparent as well, if you like to composite several images (background+drawing) instead of drawing on the background directly.

I think the way is best for you is using QLabel to view the image and OpenCV to draw over the image by those events. The issue is you will need to refresh the image after each change. I did that in this project project , it is working, but it might be better to if you use QT library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM