Draw on top of image

2019-03-28 16:47发布

问题:

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_())

回答1:

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

Output: