用Qt for python编写一个获取数据并绘制实时动态折线图的程序
时间: 2024-02-11 09:05:58 浏览: 95
微信小程序使用echarts获取数据并生成折线图
5星 · 资源好评率100%
好的,以下是一个使用Qt for Python(PySide2)的示例代码,实现获取数据并绘制实时动态折线图:
```python
import sys
import random
import time
from PySide2.QtCore import Qt, QThread, Signal
from PySide2.QtGui import QPainter, QPen, QBrush
from PySide2.QtWidgets import QApplication, QWidget
class DataThread(QThread):
dataChanged = Signal(float)
def run(self):
while True:
# 模拟数据源,每隔1秒生成一组随机数据
data = random.randint(0, 100)
self.dataChanged.emit(data)
time.sleep(1)
class DynamicLineChart(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Dynamic Line Chart')
self.setGeometry(100, 100, 800, 600)
self.data = []
self.dataThread = DataThread()
self.dataThread.dataChanged.connect(self.addData)
self.dataThread.start()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
painter.setPen(QPen(Qt.black, 2, Qt.SolidLine))
painter.setBrush(QBrush(Qt.NoBrush))
# 绘制坐标轴
painter.drawLine(50, 550, 750, 550)
painter.drawLine(50, 550, 50, 50)
# 绘制折线图
if len(self.data) > 1:
painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
for i in range(len(self.data) - 1):
x1 = 50 + i * 10
y1 = 550 - self.data[i] * 5
x2 = 50 + (i + 1) * 10
y2 = 550 - self.data[i + 1] * 5
painter.drawLine(x1, y1, x2, y2)
def addData(self, data):
self.data.append(data)
if len(self.data) > 70:
self.data.pop(0)
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
chart = DynamicLineChart()
chart.show()
sys.exit(app.exec_())
```
这个示例程序会每隔1秒生成一组随机数据,并实时绘制折线图。你可以将数据源替换为你自己的数据源,然后运行这个程序即可实现实时动态折线图的绘制。
阅读全文