python - 在图像之上绘制

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

最佳答案

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

我的图片.png

enter image description here

输出:

enter image description here

关于python - 在图像之上绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769354/

相关文章:

python - 获取具有对象或分类数据类型的列名列表

python - 如何将多页 PDF 转换为 Python 中的图像对象列表?

python - 如何使 QPushButton 成为加载按钮?

python - 如何在 Process() 中中断 Queue.get()?

python - QSound 在对象内部的意外行为

python - 如何在 PyQt5 中更改 QButtonGroup 的颜色属性?

python - Elasticsearch:时间范围聚合未按预期工作

java - 卡住/编译和管道 java python 应用程序?

python - 如何在 PyQT5 中为 QPlainTextEdit(或任何其他组件)实现关键监听器

python - 如何更新 Mac 上的 Mercurial 以使用 CAC 身份验证