1

我正在用 python 学习 matplotlib。任务是在 UI 中嵌入绘图。情节将在收到某些事件后重新绘制。

UI 应用程序采用 QtDesigner 生成的类,基本上是 4000 行

self.BRIGHTNESS = QtGui.QSlider(ZenMainForm)
self.BRIGHTNESS.setGeometry(QtCore.QRect(463, 73, 32, 131))

等等,在绘制之前生成一些其他对象并将它们附加到生成的类中。

我已经确定了这个过程,并且能够添加滑块、单选按钮和其他标准的 QWidget 派生对象。

但是,现在我需要嵌入上述图形。有很多教程,但他们在画布上创建图片,然后向其中添加轴。不幸的是,我不明白这个过程,最重要的是,不明白如何创建一个 QWidget,包含一个 mutable plot。从那里开始,将它集成到应用程序中是一条线。

4

1 回答 1

2

我删除了与教程无关的所有内容。然后我开始将我的代码集成到教程代码中,直到它崩溃。这突出了我的错误。感谢大家的宝贵意见!

下面是修改后的最小版本的教程。只需将 DynamicMplCanvas 用作普通的 QWidget。

# Copyright (C) 2005 Florent Rougon
#               2006 Darren Dale
#
# This file is an example program for matplotlib. It may be used and
# modified with no restriction; raw copies as well as modified versions
# may be distributed without limitation.

from __future__ import unicode_literals
import sys, os, random
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 MplCanvas(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.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)


class DynamicMplCanvas(MplCanvas):
    """A canvas that updates itself every second with a new plot."""
    def __init__(self, *args, **kwargs):
        MplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        QtCore.QObject.connect(timer,
                               QtCore.SIGNAL("timeout()"),
                               self.update_figure)
        timer.start(1000)

    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')

    def update_figure(self):
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [ random.randint(0, 10) for i in range(4) ]
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.draw()
于 2013-06-18T08:08:18.220 回答