Home > database >  Plotting a chart inside a PyQT GUI
Plotting a chart inside a PyQT GUI

Time:06-11

I would like to plot a chart inside a pyQT GUI. I have already read a lot of tutorials, but those plot the chart in a separeted window. I need it to be ploted in the same window as the other buttons and fields.

In my main.py file, I import the Ui_MainWindow class generated with the QT designer. But I didn't figured out how to plot it inside the MainWindow

Python GUI
Python GUI

Matplotlib canvas class to create figure

class MplCanvas(FigureCanvas):
    def __init__(self):
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def atualizar(self):
        global tempoInicio
        tempoInicio = self.campoTempoInicio.dateTime()
        print(tempoInicio.toPyDateTime())

        x=range(0, 10)
        y=range(0, 20, 2)
        self.FigureCanvas.canvas.ax.plot(x, y)
        self.FigureCanvas.canvas.draw()

I've tried as this, but it didn't worked as well (followed a tutorial)

Thank you in advance for reading this.

CodePudding user response:

Here's a complete example that should help:

import sys
from PyQt5 import QtWidgets, QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt


class PlotViewer(QtWidgets.QWidget):

    doubleClickAction = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(PlotViewer, self).__init__(parent)

        self.figure = plt.figure(figsize=(5, 5))
        self.figureCanvas = FigureCanvas(self.figure)
        self.navigationToolbar = NavigationToolbar(self.figureCanvas, self)

        # create main layout
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.navigationToolbar)
        layout.addWidget(self.figureCanvas)
        self.setLayout(layout)

        # create an axis
        x = range(0, 10)
        y = range(0, 20, 2)
        ax = self.figure.add_subplot(111)
        ax.plot(x, y)

        # show canvas
        self.figureCanvas.show()


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    widget = PlotViewer()
    widget.show()
    app.exec_()

CodePudding user response:

After looking into non-relatated tutorial, I've foud this one: https://www.pythonguis.com/tutorials/embed-pyqtgraph-custom-widgets-qt-app/ that teaches how to do what I need.

Don't now why it didn't appear before. But worked!

  • Related