[Python_Matplotlib study notes (2)] Matplotlib drawing embedded in PySide2 graphical interface

Preface

This article mainly introduces how to embed Matplotlib drawing into the PySide2 graphical interface based on the FigureCanvasQTAgg class.

text

1. Introduction to FigureCanvasQTAgg class

Matplotlib provides a FigureCanvasQTAgg class to embed Matplotlib drawing into QT (PyQT5, PySide2). The 'Figure object' must be passed as a parameter to the Qt base class. Its main function is to copy the image from the Agg canvas to qt.drawable. In QT, when a widget is displayed on the screen, all drawing should be done here.

2. Implement Matplotlib drawing embedded into PySide2 graphical interface based on FigureCanvasQTAgg class

The steps are as follows :

  1. Create the main form based on PySide2 ;

    central_widget = QWidget(self) # 创建一个主窗口
    
  2. Create Figure objects and Axes objects ;

    fig = Figure() # 创建Figure对象
    ax = fig.add_subplot(1,1,1) #  创建Axes对象
    ax.plot([1, 2, 3, 4], [10, 20, 30, 40]) # 绘图
    
  3. Create a FigureCanvasQTAgg object and bind the Figure object to the FigureCanvasQTAgg object ;

    self.canvas = FigureCanvas(fig) # 创建FigureCanvasQTAgg对象
    
  4. Create layout based on PySide2 ;

    layout = QVBoxLayout(central_widget) # 创建一个垂直布局
    
  5. Add the FigureCanvasQTAgg object to the layout .

    layout.addWidget(self.canvas) # 将FigureCanvasQTAgg对象添加到布局中
    

3. Sample code and implementation effects

import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # 创建一个主窗口,并设置居中显示
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        # 创建一个垂直布局
        layout = QVBoxLayout(central_widget)

        # 创建Figure对象和FigureCanvas对象,绑定Figure对象到canvas上,并添加到布局中
        fig = Figure()
        self.canvas = FigureCanvas(fig)
        layout.addWidget(self.canvas)

        # 绘制matplotlib图形,设置标题
        ax = fig.add_subplot(1,1,1)
        ax.plot([1, 2, 3, 4], [10, 20, 30, 40])
        ax.set_title('matplotlib plot')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

Insert image description here

Guess you like

Origin blog.csdn.net/sallyyellow/article/details/130325866