pyqtchart动态绘制曲线
时间: 2023-09-04 16:06:54 浏览: 71
PyQtChart是PyQt5的一个模块,可以用于绘制各种图表,包括曲线图。下面是一个使用PyQtChart动态绘制曲线的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtChart import QChart, QChartView, QLineSeries
from PyQt5.QtCore import Qt, QThread, QTimer, pyqtSignal
import random
class DataGenerator(QThread):
update_data = pyqtSignal(float, float)
def run(self):
x = 0
y = 50
while True:
x += 1
y = y + random.randint(-5, 5)
self.update_data.emit(x, y)
self.msleep(1000)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Dynamic Chart')
self.setGeometry(100, 100, 800, 600)
self.chart = QChart()
self.chart.setTitle('Dynamic Chart')
self.chart.setAnimationOptions(QChart.SeriesAnimations)
self.series = QLineSeries()
self.chart.addSeries(self.series)
self.axis_x = self.chart.createDefaultAxes()
self.axis_x.setRange(0, 100)
self.axis_y = self.chart.createDefaultAxes()
self.axis_y.setRange(0, 100)
self.chart_view = QChartView(self.chart)
self.setCentralWidget(self.chart_view)
self.data_generator = DataGenerator()
self.data_generator.update_data.connect(self.update_chart_data)
self.data_generator.start()
def update_chart_data(self, x, y):
if len(self.series) > 100:
self.series.removePoints(0, 1)
self.series.append(x, y)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
```
在这个示例代码中,我们使用了一个`DataGenerator`线程来生成随机数据,并通过`update_data`信号将数据发送给主线程。主线程收到数据后,调用`update_chart_data`方法更新曲线图。曲线图使用了`QLineSeries`类来表示,数据更新时通过`append`方法添加新的数据点,如果数据点已经超过100个,则通过`removePoints`方法删除最早的数据点。`QChartView`类用于显示曲线图。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)