写一份QT实时绘制折线图的代码
时间: 2024-05-06 20:19:22 浏览: 109
好的,以下是一份基于QT实时绘制折线图的代码示例:
```cpp
#include <QApplication>
#include <QMainWindow>
#include <QWidget>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QPointF>
#include <QTimer>
#include <QDebug>
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow window;
QLineSeries *series = new QLineSeries();
QChart *chart = new QChart();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Real-time Line Chart");
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
window.setCentralWidget(chartView);
window.resize(800, 600);
window.show();
// Create a timer for updating the chart
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&](){
qreal x = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
qreal y = qrand() % 10;
qDebug() << "Adding data point: (" << x << ", " << y << ")";
series->append(x, y);
// Keep maximum of 10 data points in series
if (series->count() > 10) {
series->removePoints(0, series->count() - 10);
chart->axisX()->setRange(x - 10, x);
}
});
// Start the timer
timer.start(1000);
return a.exec();
}
```
这份代码通过使用QT的QtCharts模块实现了实时绘制折线图的功能。具体来说,它使用了QLineSeries来存储数据,使用QChart来绘制图表,并且使用QTimer每隔1秒钟更新一次图表。在每次更新时,代码会生成一个随机的y数值,并将当前时间戳作为x坐标,通过调用QLineSeries的append方法将数据添加到线性图中,实现实时绘制效果。
阅读全文