个人原创,未经允许,不可转载!!!
层次如下:From----->Widget------>GroupBox
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1035, 810)
self.widget = QtWidgets.QWidget(Form)
self.widget.setGeometry(QtCore.QRect(70, 60, 931, 711))
self.widget.setObjectName("widget")
self.groupBox = QtWidgets.QGroupBox(self.widget)
self.groupBox.setGeometry(QtCore.QRect(30, 20, 871, 661))
self.groupBox.setObjectName("groupBox")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.groupBox.setTitle(_translate("Form", "GroupBox"))
(1)Pyqt5与matplotlib的连接
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from untitled import Ui_Form #导入界面文件
import numpy as np
import matplotlib
matplotlib.use("Qt5Agg") # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
(2)创建一个matplotlib图形绘制类,通过继承FigureCanvas类,使得该类既是一个PyQt5的Qwidget,又是一个matplotlib的FigureCanvas,这是连接pyqt5与matplotlib的关键
class MyFigure(FigureCanvas):
def __init__(self,width, height, dpi):
# 创建一个Figure,该Figure为matplotlib下的Figure,不是matplotlib.pyplot下面的Figure
self.fig = plt.figure(figsize=(width, height), dpi=dpi)
# 在父类中激活Figure窗口,此句必不可少,否则不能显示图形
super(MyFigure,self).__init__(self.fig)
# 调用Figure下面的add_subplot方法,类似于matplotlib.pyplot下面的subplot(1,1,1)方法
(3)新建一个Mainwindow类,继承QWidget, 和 Ui_Form,用于实现绘图或者显示图片功能
class Mainwindow(QWidget, Ui_Form):
def __init__(self):
super(Mainwindow,self).__init__()
self.setupUi(self)
self.F = MyFigure(width=3, height=2, dpi=100)
# 在GUI的groupBox中创建一个布局,用于添加MyFigure类的实例(即图形)
paths = ['D:/DataSet/test1/image.orig/102.jpg',
'D:/DataSet/test1/image.orig/132.jpg',
'D:/DataSet/test1/image.orig/135.jpg',
'D:/DataSet/test1/image.orig/130.jpg',
'D:/DataSet/test1/image.orig/189.jpg',
'D:/DataSet/test1/image.orig/179.jpg',
'D:/DataSet/test1/image.orig/111.jpg',
'D:/DataSet/test1/image.orig/155.jpg',
'D:/DataSet/test1/image.orig/147.jpg',
'D:/DataSet/test1/image.orig/163.jpg']
i = 1
for index, im in enumerate(paths):
image = mpimg.imread(im)
self.axes = self.F.fig.add_subplot(3,4,i)
# 子图的标题
self.axes.set_title(str(im).split('/')[-1].encode("utf-8"))
plt.imshow(image)
# 调整subplot之间的间隙大小
plt.subplots_adjust(wspace=0.4, hspace=0.5)
i += 1
# 在布局容器中添加groupBox
# 把MyFigure实例添加到布局容器中
self.gridlayout = QGridLayout(self.groupBox)
self.gridlayout.addWidget(self.F,0,1)
# 显示大标题
self.F.fig.suptitle("实现pyqt5+matplotlib")