使用PyQt5和pyhton,从类MonitoringCPUResources接收参数x和y的列表,要求绘制实时更新的曲线
时间: 2024-03-17 14:43:38 浏览: 106
可以使用PyQtGraph库来实现实时更新的曲线绘制。具体实现步骤如下:
1. 安装PyQtGraph库
可以使用pip安装:
```
pip install pyqtgraph
```
2. 导入库
```python
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
```
3. 创建应用程序对象和主窗口
```python
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Real-time plot")
win.resize(800, 600)
win.setWindowTitle('Real-time plot')
```
4. 创建图形对象和曲线对象
```python
p = win.addPlot(title="Real-time plot")
curve = p.plot(pen='y')
```
5. 定义更新曲线的函数
```python
def update():
global curve, data, ptr
curve.setData(data)
ptr += 1
```
6. 创建定时器并启动
```python
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)
```
7. 在类MonitoringCPUResources中接收参数x和y的列表,并更新data变量
```python
class MonitoringCPUResources:
def __init__(self):
self.x = []
self.y = []
self.data = []
def receive_data(self, x, y):
self.x.append(x)
self.y.append(y)
self.data = np.column_stack((self.x, self.y))
```
完整代码如下:
```python
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
class MonitoringCPUResources:
def __init__(self):
self.x = []
self.y = []
self.data = []
def receive_data(self, x, y):
self.x.append(x)
self.y.append(y)
self.data = np.column_stack((self.x, self.y))
def start_gui():
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Real-time plot")
win.resize(800, 600)
win.setWindowTitle('Real-time plot')
p = win.addPlot(title="Real-time plot")
curve = p.plot(pen='y')
def update():
global curve, data, ptr
curve.setData(data)
ptr += 1
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)
monitor = MonitoringCPUResources()
def receive_data(x, y):
monitor.receive_data(x, y)
return app, win, monitor, receive_data
if __name__ == '__main__':
app, win, monitor, receive_data = start_gui()
# 模拟数据
ptr = 0
data = np.random.normal(size=(10,2))
# 模拟更新数据
for i in range(1000):
x = i
y = np.random.normal()
receive_data(x, y)
app.processEvents()
data = monitor.data
```
阅读全文
相关推荐










