Python - matplotlib - PyQT:绘制到 QPixmap

Python - matplotlib - PyQT: plot to QPixmap

我想可视化 matplotlibs 颜色映射(类似于 http://matplotlib.org/examples/color/colormaps_reference.html) and use it as QPixmaps in PyQt widgets. The idea is to create the plots in matplotlib without actually showing it (or saving it to a file) and convert it to a QPixmap. The solution offered here (Python - matplotlib - PyQT: Copy image to clipboard)似乎不起作用,可能是因为我不想显示 matplotlib 图。

我已经尝试了以下并且有效:

def testColourMap(cmap):
    sp = SubplotParams(left=0., bottom=0., right=1., top=1.)
    fig = Figure((2.5,.2), subplotpars = sp)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect=10, cmap=cmap)
    ax.set_axis_off()
    canvas.draw()
    size = canvas.size()
    width, height = size.width(), size.height()
    im = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
    return QPixmap(im)

Matplotlib 通过后端支持 PySide(例如 this tutorial),但还不支持新的 PySide6,所以我 运行 遇到了类似的问题。

部分基于 Michael 的上述回答,我发现以下最小示例可用于 PySide6 6.1.0 和 matplotlib 3.4.2:

from PySide6.QtGui import QImage, QPixmap
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

def get_q_pixmap():
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.plot([1, 2, 4, 3])
    ax.set_title('test plot')
    canvas.draw()
    
    width, height = fig.figbbox.width, fig.figbbox.height
    img = QImage(canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
    pixmap = QPixmap(img)
    return pixmap

对我来说有点违反直觉,显示此 QPixmap 的最简单方法似乎是使用 QLabel.

setPixmap() 方法