我正在用 python 学习 matplotlib。任务是将绘图嵌入到 UI 中。情节将在收到某些事件后重新绘制。
UI 应用程序采用 QtDesigner 生成的类,基本上有 4000 行
self.BRIGHTNESS = QtGui.QSlider(ZenMainForm)
self.BRIGHTNESS.setGeometry(QtCore.QRect(463, 73, 32, 131))
等等,在绘制之前生成一些其他对象并将它们附加到生成的类中。
我已经确定了这个过程,并且能够添加 slider 、单选按钮和其他标准 QWidget 派生对象。
但是,现在我需要嵌入上述图形。有很多 tutorials ,但他们在 Canvas 上创建一个图片,然后向其中添加轴。不幸的是,我不理解这个过程,而且最重要的是,不理解如何创建包含可变图的 QWidget。从那时起,只需一行即可将其集成到应用程序中。
最佳答案
我删除了教程中不相关的所有内容。然后我开始将我的代码集成到教程代码中,直到它崩溃。这凸显了我的错误。感谢大家的宝贵意见!
以下是本教程的修改后的最小版本。只需将 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()
关于python - 我认为 matplotlib 中的所有内容都是 QWidget。显然图不是。我的界面接受 QWidgets。该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17146625/