pyqt的绘图问题

一、matplotlib如何嵌入PyQt5中?

通过matplotlib.backends.backend_qt5agg类连接PyQt5。在实际代码中,我们需要在引用部分加入内容:

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

1
2
3
4
5

二、如何使用FigureCanvas和Figure类

在使用FigureCanvas和Figure类创建plot绘制窗口时设计的相关内容可参考:
【matplotlib.figure类】https://matplotlib.org/api/figure_api.html
【backend类】https://matplotlib.org/api/index_backend_api.html
其中构造函数Figure()用来创建一个类似Matlab的figure()或matplotlib.pyplot的figure()。

class matplotlib.figure.Figure(figsize=None, dpi=None,
facecolor=None, edgecolor=None, linewidth=0.0,
tight_layout=None, constrained_layout=None)
例如:
width=5, height=4, dpi=100
self.fig = Figure(figsize=(width, height), dpi=dpi)
其中:width,height,为窗口尺寸,5英寸*4英寸,分辨率为dpi=100

1
2
3
4
5
6
7

另外一个函数是:add_subplot(221)
它是用来创建子图,如图matlab的subplot(2,2,1),表示共有4个子图,当前为第一个子图。具体应用如下:

sefl.axes = self.fig.add_subplot(221)

1

然后在self.axes中绘制图形如下:

t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)

1
2
3

=============================================
上述介绍的是使用Figure和subplot如何绘制图形,图形是可以绘制了,但是怎么将其在Gui界面控件中显示呢?
三、如何将图形显示在Gui控件上?

图形:正弦曲线,使用Figure实现的self.axes.plot(t, s)
GUi:Widget、Dialog和MainWindow三种窗口类型
控件(部件):
1)QTabWidget()部件的页面上
2)QGraphicsView图形视图
3)QgroupBox组框控件
4)还有其他可以作为Ui容器的控件都可以
【因为创建的Figure本身是一个部件,它也是PyQt中的Widget,所以我们只需要将创建的图形添加到GUI界面中的容器控件中即可显示图形。】
例1 在对话框中添加一个Widget中心部件,然后再在中心部件中添加一个GroupBox部件,保存ui文件(使用Qt designer)。并将其转为.py文件,代码如下:

-- coding: utf-8 --

Form implementation generated from reading ui file ‘testplot2pyqt5.ui’

Created by: PyQt5 UI code generator 5.10

WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(“Dialog”)
Dialog.resize(718, 515)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(370, 470, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(“buttonBox”)
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(10, 10, 691, 451))
self.widget.setObjectName(“widget”)
self.groupBox = QtWidgets.QGroupBox(self.widget)
self.groupBox.setGeometry(QtCore.QRect(0, 0, 691, 451))
self.groupBox.setObjectName(“groupBox”)

    self.retranslateUi(Dialog)
    self.buttonBox.accepted.connect(Dialog.accept)
    self.buttonBox.rejected.connect(Dialog.reject)
    QtCore.QMetaObject.connectSlotsByName(Dialog)

def retranslateUi(self, Dialog):
    _translate = QtCore.QCoreApplication.translate
    Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
    self.groupBox.setTitle(_translate("Dialog", "GroupBox_Matplotlib的图形显示:"))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

下面另新建一个python文件用于写主函数部分,具体代码如下:

#--coding:utf-8--
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import numpy as np
from testplot2pyqt5 import Ui_Dialog

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

#创建一个matplotlib图形绘制类
class MyFigure(FigureCanvas):
def init(self,width=5, height=4, dpi=100):
#第一步:创建一个创建Figure
self.fig = Figure(figsize=(width, height), dpi=dpi)
#第二步:在父类中激活Figure窗口
super(MyFigure,self).init(self.fig) #此句必不可少,否则不能显示图形
#第三步:创建一个子图,用于绘制图形用,111表示子图编号,如matlab的subplot(1,1,1)
self.axes = self.fig.add_subplot(111)
#第四步:就是画图,【可以在此类中画,也可以在其它类中画】
def plotsin(self):
self.axes0 = self.fig.add_subplot(111)
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes0.plot(t, s)
def plotcos(self):
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)

class MainDialogImgBW(QDialog,Ui_Dialog):
def init(self):
super(MainDialogImgBW,self).init()
self.setupUi(self)
self.setWindowTitle(“显示matplotlib绘制图形”)
self.setMinimumSize(0,0)

    #第五步:定义MyFigure类的一个实例
    self.F = MyFigure(width=3, height=2, dpi=100)
    #self.F.plotsin()
    self.plotcos()
    #第六步:在GUI的groupBox中创建一个布局,用于添加MyFigure类的实例(即图形)后其他部件。
    self.gridlayout = QGridLayout(self.groupBox)  # 继承容器groupBox
    self.gridlayout.addWidget(self.F,0,1)

    #补充:另创建一个实例绘图并显示
    self.plotother()

def plotcos(self):
    t = np.arange(0.0, 5.0, 0.01)
    s = np.cos(2 * np.pi * t)
    self.F.axes.plot(t, s)
    self.F.fig.suptitle("cos")
def plotother(self):
    F1 = MyFigure(width=5, height=4, dpi=100)
    F1.fig.suptitle("Figuer_4")
    F1.axes1 = F1.fig.add_subplot(221)
    x = np.arange(0, 50)
    y = np.random.rand(50)
    F1.axes1.hist(y, bins=50)
    F1.axes1.plot(x, y)
    F1.axes1.bar(x, y)
    F1.axes1.set_title("hist")
    F1.axes2 = F1.fig.add_subplot(222)

    ## 调用figure下面的add_subplot方法,类似于matplotlib.pyplot下面的subplot方法
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    y = [23, 21, 32, 13, 3, 132, 13, 3, 1]
    F1.axes2.plot(x, y)
    F1.axes2.set_title("line")
    # 散点图
    F1.axes3 = F1.fig.add_subplot(223)
    F1.axes3.scatter(np.random.rand(20), np.random.rand(20))
    F1.axes3.set_title("scatter")
    # 折线图
    F1.axes4 = F1.fig.add_subplot(224)
    x = np.arange(0, 5, 0.1)
    F1.axes4.plot(x, np.sin(x), x, np.cos(x))
    F1.axes4.set_title("sincos")
    self.gridlayout.addWidget(F1, 0, 2)

if name == “main”:
app = QApplication(sys.argv)
main = MainDialogImgBW()
main.show()
#app.installEventFilter(main)
sys.exit(app.exec_())

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

结果如下图:
这里写图片描述
例2,在上例基础上,添加一个TabWidget控件,将绘制的图形显示在Tabwidget控件中。【主要修改第六步即可】

#第五步:定义MyFigure类的一个实例
self.F = MyFigure(width=3, height=2, dpi=100)
#self.F.plotsin()
self.plotcos()
#修改第六步:在GUI的groupBox中创建一个布局,用于添加MyFigure类的实例(即图形)后其他部件。
# self.gridlayout = QGridLayout(self.groupBox) # 继承容器groupBox
# self.gridlayout.addWidget(self.F,0,1)

    vlayout = QVBoxLayout(self.widget)   #在中心部件上创建一个布局添加TabWidget控件
    self.tabwidget = QTabWidget()  # 添加一个Tab控件用于存放显示图像的部件
    #下面这些属性设置可不要
    self.tabwidget.setTabsClosable(True)
    self.tabwidget.setUsesScrollButtons(True)
    self.tabwidget.setTabPosition(0)
    self.tabwidget.setElideMode(2)
    self.tabwidget.setMovable(True)
    self.tabwidget.resize(300, 500)

    vlayout.addWidget(self.tabwidget)

    self.gridlayout1 = QGridLayout(self.tabwidget)
    self.gridlayout1.addWidget(self.F,0,0)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

结果:
这里写图片描述
例3 同样在例1基础上修改第六步,在GroupBox框中添加QGraphicsView视图窗口显示图形,具体修改如下:

“”“修改第六步:在groupBox框中使用QGraphicsView控件来显示”""
self.gridlayout = QGridLayout(self.groupBox) # 继承容器groupBox
self.graphicsview = QGraphicsView(self.groupBox)
self.gridlayout.addWidget(self.graphicsview, 1, 0)

    self.scene = QGraphicsScene()  #创建一个场景
    self.scene.addWidget(self.F)   #将图形元素添加到场景中
    self.graphicsview.setScene(self.scene) #将创建添加到图形视图显示窗口
    self.graphicsview.show()       #显示

1
2
3
4
5
6
7
8
9

结果:
这里写图片描述

从3个结果图我们可以看出,例3使用GraphicsView显示比较浪费空间,显示不够饱满,例1和例2显示效果较好些。

============================================
在Widget和MainWindow中显示也是一样,在这里不一一举例。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
PyQt,可以使用PyQt Designer来进行绘图。首先,需要导入相关的库。可以使用以下命令来安装PyQt5及其插件和工具: ``` pip install PyQt5==5.15.4 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install pyqt5-plugins==5.15.4.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install PyQt5-Qt5==5.15.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install PyQt5-sip==12.9.1 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install PyQt5-stubs==5.15.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install pyqt5-tools==5.15.4.3.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install python-dotenv==0.20.0 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install qt5-applications==5.15.2.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install qt5-tools==5.15.2.1.2 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install numpy==1.21.6 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install PyQtChart==5.15.5 -i https://pypi.tuna.tsinghua.edu.cn/simple ``` 然后,可以使用Qt Designer来设计UI界面。在界面添加一个自定义控件(例如QGraphicsView),并在代码导入相关的模块。可以使用FigureCanvasQTAgg来创建画布对象,并将其作为控件添加到UI上。绘图操作可以在画布对象上进行。最后,将UI显示出来,即可看到绘制的图像。 需要注意的是,在使用PyQt Designer进行绘图时,需要注意与默认的paintEvent()方法的配套使用,以确保绘图内容的显示。如果遇到问题无法解决,可以检查代码绘图相关的部分,确保设置正确。 总结起来,使用PyQt Designer绘图的步骤如下: 1. 导入必要的库和模块; 2. 使用Qt Designer设计UI界面,添加自定义控件; 3. 在代码导入相关模块,并创建画布对象; 4. 在画布对象上进行绘图操作; 5. 显示UI界面,即可看到绘制的图像。 希望以上信息对您有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值