0

我是 matplotlib 的新手,很长一段时间以来我一直在努力实现一个功能。基本上我有一个嵌入到小部件中的图,我想(在按下按钮时)创建一个新的小部件,上面有完全相同的图。是否有捷径可寻?[假设我已经实现了所有的动作处理程序]

4

1 回答 1

0

以下是从embedding_in_qt4matplotlib的例子中屠宰出来的

import sys
from PyQt4 import QtGui, QtCore

from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.fig = fig
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)


class ApplicationWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.main_widget = QtGui.QWidget(self)
        l = QtGui.QVBoxLayout(self)
        sc = MyStaticMplCanvas(self, width=5, height=4, dpi=100)
        self.sc = sc
        l.addWidget(sc)
        but = QtGui.QPushButton("make_new", self)
        but.clicked.connect(self.again)
        l.addWidget(but)

    def again(self):
        win = MyMplCanvas()
        win.fig = self.sc.fig
        FigureCanvas.__init__(win, win.fig)
        self.win = win
        win.show()

qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())

请注意画布如何保持对其图形对象的引用以及应用程序如何保持对新画布的引用。

于 2015-07-14T23:10:12.157 回答