如何在用QT Designer生成的GUI中嵌入matplotlib图?

时间:2019-05-09 06:55:02

标签: matplotlib pyqt5 qt-designer

我试图将matplotlib图形嵌入到QT Designer(PyQT5)生成的GUI中,并实时显示它。

使用pyuic5生成的脚本,我从qt5agg添加了Figure和canvas。我可以在QT窗口中嵌入轴,但是无法动态显示我的图。

这是QT Designer生成的代码的GUI部分。我对其进行了少许编辑,以嵌入一个用于matplotlib的FigureCanvas的小部件-

plotter.py

from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(640, 480)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 1, 0, 1, 1)

        self.fig1 = Figure()

        self.canvas1 = FigureCanvas(self.fig1)
        self.axes1 = self.fig1.add_subplot(111)

        self.gridLayout.addWidget(self.canvas1, 0, 0, 1, 1)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 20))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))

以下是主要脚本-

plotterFunc.py

import matplotlib as plt
from drawnow import *
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QMessageBox
from plotter import Ui_MainWindow
from matplotlib.figure import Figure

class LineGraph(QtWidgets.QMainWindow):

    def __init__(self):
        super(LineGraph, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.pushClicked)

    def pushClicked(self):

        x = time.time()

        for i in range(1000):
            y = i * x

            # print x and y to confirm if the script is running properly
            print(x,y) 

            self.ax1 = self.ui.axes1.plot(x, y)
            self.ui.canvas1.draw()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    application = LineGraph()
    application.show()
    sys.exit(app.exec())

我希望看到该图可以实时更新给定范围内的方程,但是我似乎无法显示它。

请帮助!

0 个答案:

没有答案