gpt4 book ai didi

python - 类型错误 : QPixmap(): argument 1 has unexpected type 'Figure'

转载 作者:行者123 更新时间:2023-12-04 08:27:57 26 4
gpt4 key购买 nike

我正在尝试使用 matplotlib 制作图形并使用 Qpixmap 将其直接绘制在 Qlabel 中。但是,错误 QPixmap () 正在发生:参数 1 具有意外类型“图”。如何在不保存之前显示图形?

import matplotlib.pyplot as plt
import numpy as np

labels = ['Word', 'Excel', 'Chrome','Visual Studio Code']
title = [20,32,22,25]
cores = ['lightblue','green','blue','red']
explode = (0,0.1,0,0)
plt.rcParams['font.size'] = '16'
total=sum(title)
plt.pie(title,explode=explode,labels=labels,colors=cores,autopct=lambda p: '{:.0f}'.format(p*total/100), shadow=True, startangle=90)
plt.axis('equal')
grafic = plt.gcf()
self.ui.grafig_1.setPixmap(QPixmap(grafic))

最佳答案

您不能转换 Figure QPixmap 直接,所以你会得到那个异常(exception)。相反,您必须获取由 savefig() 生成的图像的字节数。 Figure 的方法并用它创建一个 QPixmap :

import io
import sys

import matplotlib.pyplot as plt
import numpy as np

from PyQt5 import QtGui, QtWidgets


labels = ["Word", "Excel", "Chrome", "Visual Studio Code"]
title = [20, 32, 22, 25]
cores = ["lightblue", "green", "blue", "red"]
explode = (0, 0.1, 0, 0)
plt.rcParams["font.size"] = "16"
total = sum(title)
plt.pie(
title,
explode=explode,
labels=labels,
colors=cores,
autopct=lambda p: "{:.0f}".format(p * total / 100),
shadow=True,
startangle=90,
)
plt.axis("equal")
grafic = plt.gcf()

f = io.BytesIO()
grafic.savefig(f)

app = QtWidgets.QApplication(sys.argv)

label = QtWidgets.QLabel()
pixmap = QtGui.QPixmap()
pixmap.loadFromData(f.getvalue())
label.setPixmap(pixmap)
label.show()

sys.exit(app.exec_())
注:没有必要转换为 QPixmap 来显示 matplotlib 图,因为 matplotlib 允许使用 Qt 作为后端,我建议检查以下帖子:
  • How to embed matplotlib in pyqt - for Dummies
  • https://matplotlib.org/3.3.3/gallery/user_interfaces/embedding_in_qt_sgskip.html
  • 关于python - 类型错误 : QPixmap(): argument 1 has unexpected type 'Figure' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65172406/

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