Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw on top of image

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_())
like image 570
Johan Avatar asked Mar 13 '17 17:03

Johan


People also ask

What app lets you draw over pictures?

You Doodle is the best app on Android to create art and draw on photos and draw on pictures. Doodling on a friend, or marking up a picture or adding text has never been easier. With it's powerful text tool and simple brush tool, you can draw on photos and add text quickly and easily.


1 Answers

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

like image 163
eyllanesc Avatar answered Oct 19 '22 18:10

eyllanesc