QChart 在 QT 应用程序中变慢

QChart slows down in QT application

所以我正在编写一个 QT 应用程序,该应用程序将从串行端口读取值并在运行时将它们显示在图形中。我设法在运行时使用随机生成的值更新我的 QChart 以尝试实时更新并且一切正常。

但是我的应用程序越来越慢,直到它变得完全无法使用。

我知道包含我的点数的列表在增长,但是在 100 点左右之后它真的真的变慢了,那真的很快,感觉我有某种内存泄漏?

我知道通常的答案是 "Don't use QCharts",但我是 C++ 和 QT 的初学者,所以这就是我为简单起见而使用的。

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QGridLayout>

#include <QLabel>
#include <QDebug>

QT_CHARTS_USE_NAMESPACE
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    series = new QLineSeries();

    chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->createDefaultAxes();
    chart->axes(Qt::Vertical).back()->setRange(-10, 10);
    chart->axes(Qt::Horizontal).back()->setRange(0, 100);

    chart->setContentsMargins(0, 0, 0, 0);
    chart->setBackgroundRoundness(0);

    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    ui->setupUi(this);

    QLabel *label = new QLabel();
    label->setText("Hello World");

    QGridLayout *layout = new QGridLayout;
    QWidget * central = new QWidget();
    setCentralWidget(central);
    centralWidget()->setLayout(layout);

    layout->addWidget(chartView, 0, 0);

    clock = 0;

    SerialPortReader *reader = new SerialPortReader(this);

    connect(reader, SIGNAL(onReadValue(int)), this, SLOT(onReadValue(int)));

    reader->run();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onReadValue(int value){
    ++clock;    
    series->append(clock + 30, value);
    chart->axes(Qt::Horizontal).back()->setRange(0 + clock, 100 + clock);    
}

SerialPortReader.cpp

#include "serialportreader.h"
#include "mainwindow.h"
#include <QtCore>
#include <QRandomGenerator>
#include <QDebug>

SerialPortReader::SerialPortReader(QObject *parent) : QThread(parent)
{
    this->parent = parent;
    this->randomGenerator = QRandomGenerator::global();
}

void SerialPortReader::run() {

    QTimer *timer = new QTimer(this);
    timer->start(100);
    connect(timer, SIGNAL(timeout()), this, SLOT(readValue()));
}

void SerialPortReader::readValue() {
    int value = randomGenerator->bounded(-10, 10);
    emit onReadValue(value);
}

我只是想知道是否有人对可能出现的问题有任何建议?或者如果有什么我可以做的,除了更改 chart-lib。

在四处修修补补之后,我发现罪魁祸首实际上并不是内存泄漏,而是:

chartView->setRenderHint(QPainter::Antialiasing);

随着呈现的数据越来越多,它执行所有抗锯齿的速度也越来越慢。

当我删除它时,一切突然变得非常顺利。