如何将QProcess子进程生成的matplotlib绘图嵌入PyQt5主进程QGraphicsView
解决方案
核心思路
你遇到的问题本质是两点:
- matplotlib默认使用交互后端,
plt.show()会直接把图输出到系统窗口/PyCharm的SciView面板,不会写入stdout - 直接读取stdout只能拿到print的文本,无法直接获取绘图数据,需要先对绘图脚本做改造,把绘图转成可通过stdout传输的格式,再在主程序中解析
第一步:修改子脚本test_exit.py
# 首先指定非交互后端,禁止弹出独立绘图窗口,必须放在import plt之前 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import base64 import io data = [-0.5, 0.5, 0.5, 0.5,1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2] plt.hist(data, bins=5, range=[-1, 4], histtype='step') print("first output on QPlainTextEdit...............") # 替换plt.show(),把图转成base64编码输出到stdout buf = io.BytesIO() plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') buf.seek(0) img_base64 = base64.b64encode(buf.read()).decode('utf-8') print(f"---PLOT_START---{img_base64}---PLOT_END---") plt.close() # 清空当前画布,避免下次绘图重叠 data = [-0.5, 0.5, 0.5, 0.5,1.5, 2.1, 2.2, 2.3, 2.4, 2.5, 3.1, 3.2] plt.hist(data, bins=5, range=[-1, 4], histtype='step',edgecolor='r',linewidth=3) H, bins = np.histogram(data[:6], bins=5, range=[-1, 4]) H+=np.histogram(data[6:], bins=5,range=[-1, 4])[0] plt.bar(bins[:-1],H,width=1) print("second output on QPlainTextEdit.............") # 同样处理第二张图 buf = io.BytesIO() plt.savefig(buf, format='png', dpi=100, bbox_inches='tight') buf.seek(0) img_base64 = base64.b64encode(buf.read()).decode('utf-8') print(f"---PLOT_START---{img_base64}---PLOT_END---") plt.close()
第二步:修改主程序逻辑
首先在你的主类__init__方法中新增stdout缓存变量:
self.stdout_buffer = ""
然后修改dpret槽函数:
import base64 from PyQt5 import QtGui from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsScene def dpret(self): # 读取新的输出,追加到缓存 new_data = str(self.proc.readAll().data().decode('utf-8')) self.stdout_buffer += new_data # 循环处理缓存中的完整内容 while True: # 先检查有没有完整的图片块 start_tag = "---PLOT_START---" end_tag = "---PLOT_END---" start_idx = self.stdout_buffer.find(start_tag) end_idx = self.stdout_buffer.find(end_tag) if start_idx == -1: # 没有图片块,剩下的都是普通文本,全部追加到文本框 if self.stdout_buffer: cursor = self.plainTextEdit.textCursor() cursor.movePosition(cursor.End) cursor.insertText(self.stdout_buffer) self.plainTextEdit.ensureCursorVisible() self.stdout_buffer = "" break # 有图片块,先把图片前面的普通文本追加到文本框 if start_idx > 0: text_part = self.stdout_buffer[:start_idx] cursor = self.plainTextEdit.textCursor() cursor.movePosition(cursor.End) cursor.insertText(text_part) self.plainTextEdit.ensureCursorVisible() self.stdout_buffer = self.stdout_buffer[start_idx:] # 检查图片块是否完整 if end_idx == -1: # 图片块不完整,等下一次接收 break # 提取图片base64内容 img_base64 = self.stdout_buffer[len(start_tag):end_idx] # 解码成字节 img_bytes = base64.b64decode(img_base64) # 加载到QPixmap pixmap = QtGui.QPixmap() pixmap.loadFromData(img_bytes) # 显示到QGraphicsView self.scene = QGraphicsScene(self) item = QGraphicsPixmapItem(pixmap) self.scene.addItem(item) self.graphicsView.setScene(self.scene) # 删掉缓存中已经处理完的图片块 self.stdout_buffer = self.stdout_buffer[end_idx + len(end_tag):]
注意事项
- 子脚本开头的
matplotlib.use('Agg')必须放在import matplotlib.pyplot之前执行,否则还是会弹出绘图窗口 - 如果需要保留历史绘图,可以修改QGraphicsScene的逻辑,每次新增图片的时候调整位置,不要替换整个scene
- 编码解码用utf-8即可,不需要单独设置CP_console,避免乱码
内容的提问来源于stack exchange,提问作者Nit
相关产品推荐
相关产品推荐

