Example of the perfect combination of pyqt5 and matplotlib
- 2021-06-29 11:27:12
- OfStack
matplotlib.backends.backend_is used specificallyqt5agg.FigureCanvasQTAgg
Go directly to the code (here's just a simple framework that tells you how to write):
# -*- coding: utf-8 -*-
'''
TODO:LQD
'''
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC
from PyQt5.QtWidgets import QApplication, QPushButton, QMainWindow, QVBoxLayout, QWidget
class QtDraw(QMainWindow):
flag_btn_start = True
def __init__(self):
super(QtDraw, self).__init__()
self.init_ui()
def init_ui(self):
self.resize(800, 600)
self.setWindowTitle('PyQt5 Draw')
# TODO: Here's the key to combining
self.fig = plt.Figure()
self.canvas = FC(self.fig)
self.btn_start = QPushButton(self)
self.btn_start.setText('draw')
self.btn_start.clicked.connect(self.slot_btn_start)
widget = QWidget()
layout = QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(self.btn_start)
widget.setLayout(layout)
self.setCentralWidget(widget)
def slot_btn_start(self):
try:
ax = self.fig.add_subplot(111)
x = np.linspace(0, 100, 100)
y = np.random.random(100)
ax.cla() # TODO: Delete the original so that only new ones are on the canvas 1 Secondary Chart
ax.plot(x, y)
self.canvas.draw() # TODO: Start drawing here
except Exception as e:
print(e)
def ui_main():
app = QApplication(sys.argv)
w = QtDraw()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
ui_main()