0

Morning guys,

Let me preface this by saying I have spent a few days trying to Google this, and have yet to solve my problem. Maybe my knowledge of Python Classes, and QT are lacking to fully grasp what I'm looking at.

Secondly, I have included the minimal reproducible example in the code below.

Problem

I'm trying to embed a Matplotlib figure into a small Window I created in QT Designer. The window is a small program in which I can select parameters, and when I click a button it updates the graph (figure)

I understand that I must "promote" my widget and create a .h file, which I have done. My widget objectName in QT is MplWidget. I also believe I should create a second .py file, which I have called mplwidget.py, and inside this file is a class called MplWidget to match my objectName.

mplwidget.py

from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure


class MplWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.canvas = FigureCanvas(Figure())
        vertical_layout enter code here= QVBoxLayout()
        vertical_layout.addWidget(self.canvas)
        self.canvas.axes = self.canvas.figure.add_subplot(111)
        self.setLayout(vertical_layout)"""

My main code to drive the function of the window is below.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setupUi(self)

def plot():
    print(' here')
    figure = plt.figure()
    canvas = FigureCanvas(figure)
    # random data
    data = [random.random() for i in range(10)]

    # clearing old figure
    figure.clear()

    # create an axis
    ax = figure.add_subplot(111)

    # plot data
    ax.plot(data, '*-')

    # refresh canvas
    canvas.draw()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.pushButton.clicked.connect(plot)
    sys.exit(app.exec_())

I've tried also moving the plot function into the MainWindow Class, but the "pushButton" doesn't seem to work.

Any help greatly appreciated - I'm sure it's just my lack of understanding with Classes...

Dave Stark
  • 107
  • 6

0 Answers0