matloltlib图表在Pyqt5界面内显示

  • 先导入要使用的模块
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5 import QtCore, QtWidgets
  • 在qt designer里,创建一个界面,加入一个GroupBox,加入两个PushButton,如图:

 

 

  •  用pycharm转换成py文件。这个文件可以导入,代码界面分离,也可以直接放在主py文件内,本文是界面代码放在一起的。
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(807, 619)
        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(60, 100, 611, 451))
        self.groupBox.setObjectName("groupBox")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(120, 40, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(220, 40, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
  • 接着上面界面代码,创建一个图表的类
class MyFigure(FigureCanvas):
    def __init__(self, width=10, height=8, dpi=100):  # dpi 越大图的线条越粗,颜色越深,有放大作用
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        super(MyFigure, self).__init__(self.fig)
        self.axes = self.fig.add_subplot(111)
  • 继续创建正常的界面函数类,画图,清图功能函数
class ImgMain(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.plotcos) #槽函数画图
        self.ui.pushButton_2.clicked.connect(self.clean) #槽函数清图

    def plotcos(self):
        self.ui.groupBox.show()  # 显示groupBox的控件,因为后面有个关闭
        self.F = MyFigure(1, 1, 80)

        self.gridlayout = QGridLayout(self.ui.groupBox)
        self.gridlayout.addWidget(self.F, 0, 1)

        x = [1, 2, 3, 4, 5, 6, 7, 8]
        s = [2, 8, 6, 12, 10, 11, 8, 5]
        self.F.axes.plot(x, s)
        self.F.fig.suptitle('line')

    def clean(self):
        self.ui.groupBox.close()
  • 最后,main函数启动
if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = ImgMain()
    form.show()
    sys.exit(app.exec_())
  • 效果:

 

posted @ 2022-10-04 11:42  再次路过之  阅读(425)  评论(0编辑  收藏  举报