Matplotlib不用PyQt绘图

时间:2014-11-18 14:24:39

标签: matplotlib pyqt

我遇到PyQt和Mathplotlib的问题。 在这里你可以找到我正在做的伪代码:我有一个类“MainWindow”,它创建一个带有菜单和空mathplotlib图形的主窗口。当我单击菜单项时,执行“选择”方法,打开一个新的对话框。还有一种方法可以绘制全局变量Data的内容。

import TeraGui
Data = []

class MainWindow(QMainWindow, TeraGui.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.actionSelect.triggered.connect(self.Select)

        # Create the frame with the graphs
        self.create_main_frame()
        #Plot empty graphs
        self.axes.clear()
        self.canvas.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()
        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        #
        self.axes = self.fig.add_subplot(111)
        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        #
        # Layout with box sizers
        #
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def Plotting(self):
        """ Redraws the figure
        """
        print "I am here"
        time = Data[0]
        sig = Data[]

        plot(time, sig)

        # clear the axes and redraw the plot anew
        #
        self.axes.clear()
        self.axes.plot(time, sig)
        self.canvas.draw()

    def Select(self):
        dialog = Dialog(self)
        dialog.exec_()

现在,如果我在MainWindow类的 init 方法中添加这些行:

Global Data
Data = [[1,2,3],[4,5,6]]
self.Plotting()
打印“我在这里”,图表正确显示在图表中,但如果我不添加这些行,我尝试从Dialog类调用Plotting它不起作用。 “我在这里”被绘制,但情节保持空白。在Dialog类中,当按下按钮框的“ok”按钮时,方法“accept”被取消:

class Dialog(QDialog, TeraGui.Ui_SelectFiles):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi(self)

    def accept(self):
        global Data
        Data = [[1,2,3],[4,5,6]]
        MainWindow().Plotting()

绘图方法还通过命令“plot(time,sig)”绘制单独的绘图。无论用于调用Plotting的方式如何,该图总是正确显示。

这是我用PyQt和matplotlib的第一次尝试,我无法识别错误。

1 个答案:

答案 0 :(得分:1)

问题在于

MainWindow().Plotting()

当您编写MainWindow()时,实际上是在创建MainWindow类的新实例并调用其Plotting()函数,而不是您现有的MainWindow实例。此窗口永远不会显示,并且由于您不保存对它的引用,因此在accept()返回时会被删除。它存在的唯一证据是它写入控制台的'i am here'消息。这就是你不能看到情节的原因。

在这种情况下,您将MainWindow实例设置为dialogdialog = Dialog(self)的父级,因此您可以通过调用parent()来访问它。

self.parent().Plotting()

您还应该考虑向Plotting()函数添加另一个参数,这样您就可以直接将数据传递给它,而不必在任何地方声明全局变量。

def Plotting(self, Data):
    ...
相关问题