本文介绍了在图像上绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PyQt5 的新手,我找不到任何关于如何在加载的图像 (QPixmap("myPic.png")) 上使用 QPainter 进行绘制的答案.我尝试在paintEvent 方法中执行此操作,但没有奏效.如果我想在下面的片段中加载的图像上画一条线,我该怎么做?

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

推荐答案

使用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

输出:

这篇关于在图像上绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:40