c++ 更新线系列时动态更新QChart

5tmbdcev  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(192)

如果有QLineSeries和QChart。
我希望添加一个新点会自动更新图表。但发现让它更新图表的唯一方法是这段可怕的代码:

//
// Add the score and update the score chart
//
if (nullptr != scoreSeries)
    scoreChart->removeSeries(scoreSeries);
else
{
    scoreSeries = new QLineSeries(this);
    scoreSeries->setName(tr("Score", "IDC_SCORE"));
    scoreSeries->setPointsVisible(true);
    connect(scoreSeries, &QLineSeries::hovered,
        this, &ChartTab::scoreHovered);
}

scoreSeries->append(x, fScore);
scoreMap.emplace(name, size - 1);
scoreChart->addSeries(scoreSeries);
scoreChart->createDefaultAxes();
axes = scoreChart->axes(Qt::Horizontal);
for (const auto& p : axes)
{
    QValueAxis* axis{ dynamic_cast<QValueAxis*>(p) };
    if (axis)
    {
        axis->setRange(1.0, size);
        axis->setTickAnchor(1.0);
        axis->setTickType(QValueAxis::TicksDynamic);
        axis->setTickInterval(interval);
    }
}

我相信有一个更好的方法来更新图表,当我追加到线系列,但到目前为止,我还没有找到任何实际工作。
请让我摆脱痛苦,告诉我这件事该怎么办。
我使用的是Qt 6.5.1,但我怀疑这会有很大的不同。

dluptydi

dluptydi1#

如果添加的点在图表的坐标轴范围之外,那么您将什么也看不到(就像我一样)。
因此,您需要创建线系列和轴,然后在附加新点之前调整轴范围。
因此,在我的类头中定义了以下内联函数:

inline QValueAxis* axisX(QChart* chart)
{
    return qobject_cast<QValueAxis*>(chart->axes(Qt::Horizontal)[0]);
}
inline QValueAxis* axisY(QChart* chart)
{
    return qobject_cast<QValueAxis*>(chart->axes(Qt::Vertical)[0]);
}

在ctor中:

QValueAxis* xAxis;
QValueAxis* yAxis;

scoreChart = new QChart();
scoreSeries = new QLineSeries(this);
scoreSeries->setName(tr("Score", "IDC_SCORE"));
scoreSeries->setPointsVisible(true);
scoreChart->addSeries(scoreSeries);
scoreChart->createDefaultAxes();
xAxis = axisX(scoreChart);
yAxis = axisY(scoreChart);
xAxis->setLabelFormat("%d");
xAxis->setTickType(QValueAxis::TicksDynamic);
yAxis->setRange(0, 1000);

然后在mf中添加我需要的点:

QValueAxis* xAxis;
QValueAxis* yAxis;

// Establish a value for maximum x as rangeMax
// I did it based on the number of data points to plot as in my case
// the x value is just the data point number. So e.g. I set rangeMax
// to 20 if there were 20 or fewer points to plot
// 
// Code for that omitted
//

//
// Adjust score axes if necessary (data won't display if we don't)
//
xAxis = axisX(scoreChart);
xAxis->setRange(1.0, rangeMax);
xAxis->setTickAnchor(1.0);
xAxis->setTickInterval(interval);
yAxis = axisY(scoreChart);
if (fScore > yAxis->max())
    yAxis->setMax(fScore * 1.1);
if (fScore < yAxis->min())
    yAxis->setMin(fScore);

//
// Add the score and update the score chart
//
scoreSeries->append(x, fScore);
yAxis->applyNiceNumbers();

我希望这能帮助其他正在与QChart斗争的人。
大卫

相关问题