|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +Created on 2019年5月5日 |
| 6 | +@author: Yimelia |
| 7 | +@site: https://github.com/yimelia |
| 8 | +@file: DynamicSpline |
| 9 | +@description: This example shows how to draw dynamic data. https://doc.qt.io/qt-5/qtcharts-dynamicspline-example.html |
| 10 | +""" |
| 11 | +import sys |
| 12 | + |
| 13 | +from PyQt5.QtCore import Qt, QTimer, QRandomGenerator |
| 14 | +from PyQt5.QtChart import QChartView, QLineSeries, QChart, QSplineSeries, QValueAxis |
| 15 | +from PyQt5.QtGui import QPainter, QPen |
| 16 | +from PyQt5.QtWidgets import QApplication |
| 17 | + |
| 18 | + |
| 19 | +__version__ = "0.0.1" |
| 20 | + |
| 21 | + |
| 22 | +class DynamicSpline(QChart): |
| 23 | + def __init__(self): |
| 24 | + super().__init__() |
| 25 | + self.m_step = 0 |
| 26 | + self.m_x = 5 |
| 27 | + self.m_y = 1 |
| 28 | + # 初始化图像 |
| 29 | + self.series = QSplineSeries(self) |
| 30 | + green_pen = QPen(Qt.red) |
| 31 | + green_pen.setWidth(3) |
| 32 | + self.series.setPen(green_pen) |
| 33 | + self.axisX = QValueAxis() |
| 34 | + self.axisY = QValueAxis() |
| 35 | + self.series.append(self.m_x, self.m_y) |
| 36 | + |
| 37 | + self.addSeries(self.series) |
| 38 | + self.addAxis(self.axisX, Qt.AlignBottom) |
| 39 | + self.addAxis(self.axisY, Qt.AlignLeft) |
| 40 | + self.series.attachAxis(self.axisX) |
| 41 | + self.series.attachAxis(self.axisY) |
| 42 | + self.axisX.setTickCount(5) |
| 43 | + self.axisX.setRange(0, 10) |
| 44 | + self.axisY.setRange(-5, 10) |
| 45 | + |
| 46 | + self.timer = QTimer(self) |
| 47 | + self.timer.setInterval(1000) |
| 48 | + self.timer.timeout.connect(self.handleTimeout) |
| 49 | + self.timer.start() |
| 50 | + |
| 51 | + def handleTimeout(self): |
| 52 | + x = self.plotArea().width() / self.axisX.tickCount() |
| 53 | + y = (self.axisX.max() - self.axisX.min()) / self.axisX.tickCount() |
| 54 | + self.m_x += y |
| 55 | + # 在PyQt5.11.3及以上版本中,QRandomGenerator.global()被重命名为global_() |
| 56 | + self.m_y = QRandomGenerator.global_().bounded(5) - 2.5 |
| 57 | + self.series.append(self.m_x, self.m_y) |
| 58 | + self.scroll(x, 0) |
| 59 | + if self.m_x >= 100: |
| 60 | + self.timer.stop() |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + app = QApplication(sys.argv) |
| 65 | + chart = DynamicSpline() |
| 66 | + chart.setTitle("Dynamic spline chart") |
| 67 | + chart.legend().hide() |
| 68 | + chart.setAnimationOptions(QChart.AllAnimations) |
| 69 | + |
| 70 | + view = QChartView(chart) |
| 71 | + view.setRenderHint(QPainter.Antialiasing) # 抗锯齿 |
| 72 | + view.resize(400, 300) |
| 73 | + view.show() |
| 74 | + sys.exit(app.exec_()) |
0 commit comments