Draw on top of image

Johan picture Johan · Mar 13, 2017 · Viewed 8.5k times · Source

I'm new to PyQt5 and I couldn't find any answers that worked for me about how to draw with QPainter on top of a loaded image (QPixmap("myPic.png")). I tried doing it within a paintEvent method but it didn't work. If I want to draw a line on top of the loaded image in the snippet below, how would I go about doing it?

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

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(30, 30, 500, 300)
        self.initUI()

    def initUI(self):
        self.pixmap = QPixmap("myPic.png")
        lbl = QLabel(self)
        lbl.setPixmap(self.pixmap)

        self.show()

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

Answer

eyllanesc picture eyllanesc · Mar 13, 2017

Use paintEvent and QPainter:

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

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(30, 30, 500, 300)

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap("myPic.png")
        painter.drawPixmap(self.rect(), pixmap)
        pen = QPen(Qt.red, 3)
        painter.setPen(pen)
        painter.drawLine(10, 10, self.rect().width() -10 , 10)

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

myPic.png

enter image description here

Output:

enter image description here