gpt4 book ai didi

python - 将 matplotlib 图形 Canvas 图像插入 QTextDocument

转载 作者:行者123 更新时间:2023-12-04 13:16:40 24 4
gpt4 key购买 nike

我正在创建一个计算成绩并自动分配成绩字母的应用程序,在该应用程序中,绘图是使用 Matplotlib 创建的。我想将 QTableView 和数字包含到 QTextDocument 中以进行打印。我知道如何插入QTableView,但我不知道如何在表格后插入数字。

enter image description here

是否可以直接将图像保存在磁盘中?

最佳答案

您必须将 Canvas 转换为 QImage,然后将其作为资源添加到 QTextDocument。

import sys
import time
import uuid

import numpy as np

from matplotlib.backends.qt_compat import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure


class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)

layout = QtWidgets.QVBoxLayout(self._main)

static_canvas = FigureCanvas(Figure(figsize=(5, 3)))
layout.addWidget(static_canvas)
static_canvas.setFixedHeight(200)

self._static_ax = static_canvas.figure.subplots()
t = np.linspace(0, 10, 501)
self._static_ax.plot(t, np.tan(t), "r.")

self.textedit = QtWidgets.QTextEdit()
button = QtWidgets.QPushButton("Add Canvas")
button.clicked.connect(self.add_image)
layout.addWidget(button, stretch=0)
layout.addWidget(self.textedit, stretch=1)

def add_image(self):
document = self.textedit.document()

img = self.canvasToQImage(self._static_ax.figure.canvas)
url = QtCore.QUrl()
url.setScheme("mydata")
url.setHost("image-{uuid}.png".format(uuid=uuid.uuid4()))
document.addResource(QtGui.QTextDocument.ImageResource, url, img)

# add image
cursor = QtGui.QTextCursor(document)
imageFormat = QtGui.QTextImageFormat()
imageFormat.setName(url.toString())
cursor.insertImage(imageFormat)

# or
# self.textedit.append('<img src="{url}" />'.format(url=url.toString()))

@staticmethod
def canvasToQImage(canvas):
data = canvas.buffer_rgba()
ch = 4
w, h = canvas.get_width_height()
bytesPerLine = ch * w
img = QtGui.QImage(data, w, h, bytesPerLine, QtGui.QImage.Format_ARGB32)
return img.rgbSwapped()


if __name__ == "__main__":
qapp = QtWidgets.QApplication(sys.argv)
app = ApplicationWindow()
app.resize(640, 480)
app.show()
qapp.exec_()

关于python - 将 matplotlib 图形 Canvas 图像插入 QTextDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59805347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com