将数据添加到 QLineSeries 后如何更新/重绘 QChart? [英] How to update/redraw QChart after data is added to QLineSeries?
问题描述
我正在生成一些我想使用 QChart 绘制图表的数据 &朋友们.这是我第一次使用 QChart
,所以基本上我所做的是复制 QLineSeries Example 并根据我的需要修改它.我当前的代码如下所示:
I am generating some data that I want to chart using QChart & friends. This is my first time using QChart
, and so basically what I did was copy the QLineSeries Example and modify it to my needs. My current code looks like this:
quint64 last=0;
quint64 *lastp=&last;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, series( nullptr )
{
ui->setupUi(this);
QChart *chart = new QChart();
series=new QLineSeries(chart);
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Simple line chart example");
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
setCentralWidget(chartView);
GeneticTask *gTask = new GeneticTask();
connect(gTask, &GeneticTask::point, this, [=](QPointF pt) {
// New point added to series
*series<<pt;
// Limit updates to once per second
quint64 now=QDateTime::currentMSecsSinceEpoch();
if(now-(*lastp)>1000) {
qDebug()<<"UPDATE";
// [A] WHAT TO PUT HERE TO HAVE CHART REDRAW WITH NEW DATA?
*lastp=now;
}
}
);
QThreadPool::globalInstance()->start(gTask);
}
当我运行此代码时,我希望我的新数据显示在图表中,但事实并非如此,所以我的问题是:如何更新图表以显示新数据? 换句话说,我应该在注释内容为 [A]
的代码中放什么?
When I run this code I would expect my new data to show up in the graph, but it does not, so my question is: How can I have the chart update to show the new data? In other words, what should I put in the code where the comment reads [A]
?
推荐答案
使用运算符 <<
或 append<将值附加到
QLineSeries
/code> 方法应该重新绘制图形.如果由于某种原因没有发生,您可以尝试调用 QChartView
上的 repaint
方法.
Appending a value to QLineSeries
using the operator <<
or the append
method should repaint the graph. If it does not happen form some reason, you could trying calling the repaint
method on the QChartView
.
以下是一些代码,在添加数据后将数据居中,上限为每秒一次:
Here is some code that will center the data once it is added with a cap of at most once per second:
// Global or class scope or
qreal max=-10000000000;
qreal min=-max;
qreal *maxp=&max;
qreal *minp=&min;
// Same scope as before
connect(gTask, &GeneticTask::point, this, [=](QPointF pt) {
if(pt.y()>*maxp) {
*maxp=pt.y();
}
if(pt.y()<*minp) {
*minp=pt.y();
}
*series<<pt;
quint64 now=QDateTime::currentMSecsSinceEpoch();
if(now-(*lastp)>1000) {
qDebug()<<"UPDATE";
chart->axisX()->setRange(0,series->count());
chart->axisY()->setRange(*minp,*maxp);
*lastp=now;
}
}
);
这篇关于将数据添加到 QLineSeries 后如何更新/重绘 QChart?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!