此文章作为典型案例,以防忘记。
一、QT自带Qchart绘制动态折线图
void Chart::generateData()
{
count +=1;
lineSeries0->append(count+1 ,(data::Input_register[0].toInt())*0.001+data::Input_register[1].toInt());
if(data::Input_register[6]=="43") lineSeries1->append(count+1 ,(data::Input_register[2].toInt())*0.001+data::Input_register[3].toInt());
if(data::Input_register[6]=="45") lineSeries1->append(count+1 ,(data::Input_register[2].toInt())*0.001-data::Input_register[3].toInt());
if(data::Input_register[7]=="43") lineSeries2->append(count+1 ,(data::Input_register[4].toInt())*0.001+data::Input_register[5].toInt());
if(data::Input_register[7]=="45") lineSeries2->append(count+1 ,(data::Input_register[4].toInt())*0.001-data::Input_register[5].toInt());
if (count>width) {
lineSeries0->remove(0);//从序列中删除索引所指定位置处的点。
lineSeries1->remove(0);//从序列中删除索引所指定位置处的点。
lineSeries2->remove(0);//从序列中删除索引所指定位置处的点。
}
valueAxisX->setRange(count-width, count);
}
设置定时器触发图表更新,将新的数据点添加在折线最后,删除最前面的第0点数据,最后改变x坐标轴范围,完成折线图随时间动态更新。
二、Qcustomplot绘制动态折线图
首先初始化一个QCustomPlot对象。
void setting_standardleak::chart_init(QCustomPlot *qcustomplot,int charttype=0)
{
QCustomPlot *qcustomchart=qcustomplot;
qcustomchart->addGraph(); // blue line
qcustomchart->graph(0)->setPen(QPen(QColor(40, 110, 255)));
qcustomchart->graph(0)->setName("信号");
QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
timeTicker->setTimeFormat("%h:%m:%s");
qcustomchart->xAxis->setTicker(timeTicker);
qcustomchart->axisRect()->setupFullAxesBox();
qcustomchart->yAxis->setRange(0, 10);
qcustomchart->legend->setVisible(true); // 显示图例
if(charttype)
{
qcustomchart->graph(0)->setName("电压");
qcustomchart->yAxis->setRange(300, 400);
}
else
{
qcustomchart->graph(0)->setName("信号");
qcustomchart->yAxis->setRange(0, 35000);
}
// 重画图像
qcustomchart->replot();
}
绘制动态曲线
void setting_standardleak::chart_timer_update()
{
static QTime timeStart = QTime::currentTime();
// calculate two new data points:
double key = timeStart.msecsTo(QTime::currentTime())/1000.0; // time elapsed since start of demo, in seconds
static double lastPointKey = 0;
if (key-lastPointKey > 0.002) // at most add point every 2 ms
{
ui->qcustomplot->graph(0)->addData(key,qSin(key)+std::rand()/(double)RAND_MAX*1*qSin(key/0.3843));
lastPointKey = key;
ui->qcustomplot->xAxis->setRange(key, 8, Qt::AlignRight);
ui->qcustomplot->replot();
static double lastFpsKey;
static int frameCount;
++frameCount;
if (key-lastFpsKey > 2) // average fps over 2 seconds
{
lastFpsKey = key;
frameCount = 0;
}
}
与QChart类似,不过此时用的是时间作为横坐标,并且不会删除边缘点。