PyQT5之PyQtGraph实时数据显示
实例1:CPU使用率实时展示
from PyQt5 import QtWidgets,QtCore,QtGui
import pyqtgraph as pg
import sys
import traceback
import psutil
class MainUi(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("CPU使用率监控")
self.main_widget = QtWidgets.QWidget() # 创建一个主部件
self.main_layout = QtWidgets.QGridLayout() # 创建一个网格布局
self.main_widget.setLayout(self.main_layout) # 设置主部件的布局为网格
self.setCentralWidget(self.main_widget) # 设置窗口默认部件
self.plot_widget = QtWidgets.QWidget() # 实例化一个widget部件作为K线图部件
self.plot_layout = QtWidgets.QGridLayout() # 实例化一个网格布局层
self.plot_widget.setLayout(self.plot_layout) # 设置K线图部件的布局层
self.plot_plt = pg.PlotWidget() # 实例化一个绘图部件
self.plot_plt.showGrid(x=True,y=True) # 显示图形网格
self.plot_layout.addWidget(self.plot_plt) # 添加绘图部件到K线图部件的网格布局层
# 将上述部件添加到布局层中
self.main_layout.addWidget(self.plot_widget, 1, 0, 3, 3)
self.setCentralWidget(self.main_widget)
self.plot_plt.setYRange(max=100,min=0)
self.data_list = []
self.timer_start()
# 启动定时器 时间间隔秒
def timer_start(self):
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.get_cpu_info)
self.timer.start(1000)
# 获取CPU使用率
def get_cpu_info(self):
try:
cpu = "%0.2f" % psutil.cpu_percent(interval=1)
self.data_list.append(float(cpu))
print(float(cpu))
self.plot_plt.plot().setData(self.data_list,pen='g')
except Exception as e:
print(traceback.print_exc())
def main():
app = QtWidgets.QApplication(sys.argv)
gui = MainUi()
gui.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
实例2:气温数据实时展示
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import pyqtgraph as pg
import sys
from random import randint
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('pyqtgraph作图')
# 创建 PlotWidget 对象
self.pw = pg.PlotWidget()
# 设置图表标题
self.pw.setTitle("气温趋势",
color='#008080',
size='12pt')
# 设置上下左右的label
self.pw.setLabel("left","气温(摄氏度)")
self.pw.setLabel("bottom","时间")
# 设置Y轴 刻度 范围
self.pw.setYRange(min=-10, # 最小值
max=50) # 最大值
# 显示表格线
self.pw.showGrid(x=True, y=True)
# 背景色改为白色
self.pw.setBackground('w')
# 设置Y轴 刻度 范围
self.pw.setYRange(min=-10, # 最小值
max=50) # 最大值
# 居中显示 PlotWidget
self.setCentralWidget(self.pw)
# 实时显示应该获取 PlotDataItem对象, 调用其setData方法,
# 这样只重新plot该曲线,性能更高
self.curve = self.pw.plot(
pen=pg.mkPen('r', width=1)
)
self.i = 0
self.x = [] # x轴的值
self.y = [] # y轴的值
# 启动定时器,每隔1秒通知刷新一次数据
self.timer = QTimer() # QtCore
self.timer.timeout.connect(self.updateData)
self.timer.start(1000)
def updateData(self):
self.i += 1
self.x.append(self.i)
# 创建随机温度值
self.y.append(randint(10, 30))
# plot data: x, y values
self.curve.setData(self.x, self.y)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
app.exec_()