如何在不使用 QCustomPlot 的情况下在 Qt 中创建实时散点图?

How to create a real-time scatter plot in Qt without using QCustomPlot?

我正在尝试使用 QtCharts 将随机生成的数据实时绘制成散点图。我想使用 QtCharts 来做到这一点,甚至尝试将 Qt Audio Example 重新用于解决方案,但没有成功。关于如何正确执行此操作的任何建议?

我为您更改了 Qt 散点图示例:

您只需要使用 QTimerQRandomGenerator

chartview.h :

#ifndef CHARTVIEW_H
#define CHARTVIEW_H

#include <QtCharts/QChartView>

QT_CHARTS_USE_NAMESPACE

class ChartView: public QChartView
{
    Q_OBJECT

public:
    explicit ChartView(QWidget *parent = 0);

private:
    QTimer *_timer;
    int     _x = 0;
};

#endif // CHARTVIEW_H

chartview.cpp :

#include "chartview.h"
#include <QtCharts/QScatterSeries>
#include <QtCharts/QLegendMarker>
#include <QTimer>
#include <QtMath>
#include <QtCore/QRandomGenerator>

ChartView::ChartView(QWidget *parent):
    QChartView(new QChart(), parent)
{
    QScatterSeries *series0 = new QScatterSeries();

    series0->setName("scatter1");
    series0->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    series0->setMarkerSize(15.0);


    QScatterSeries *series2 = new QScatterSeries();
    series2->setName("scatter2");
    series2->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    series2->setMarkerSize(15.0);


    _timer = new QTimer();


connect(_timer, &QTimer::timeout, this, [series0, this]()
{
    series0->append(_x++, QRandomGenerator::global()->bounded(10));
});

_timer->start(1000);


    *series2 << QPointF(1, 5) << QPointF(4, 6) << QPointF(6, 3) << QPointF(9, 5);


    setRenderHint(QPainter::Antialiasing);
    chart()->addSeries(series0);
    chart()->addSeries(series2);

    chart()->setTitle("Simple scatterchart example");
    chart()->createDefaultAxes();
    chart()->setDropShadowEnabled(false);

    chart()->legend()->setMarkerShape(QLegend::MarkerShapeFromSeries);
}

输出为: