画在图像上

时间:2017-03-13 17:02:32

标签: python pyqt pyqt5 qpixmap qlabel

我是PyQt5的新手,我找不到任何有关如何在加载的图像上绘制QPainter的答案(QPixmap(“myPic.png”))。我尝试在paintEvent方法中执行它,但它不起作用。如果我想在下面的片段中加载图像的顶部画一条线,我该怎么做呢?

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 个答案:

答案 0 :(得分:8)

使用paintEventQPainter

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

输出:

enter image description here