功能:每一秒动态添加一个数据,可通过按钮进行控制,开始与暂停;添加spinbox控件对x轴的刻度进行控制;滚动鼠标滑轮可分别放大缩小x轴,y轴
构造函数:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
calibtation = CALIBTATION_CONFIG;
key = 0;
//动态添加数据的开始/暂停
connect(ui->con_pushButton,&QPushButton::clicked,this,[=](){
if (ftimer->isActive())
{
ftimer->stop();
}else{
ftimer->start();
}
});
//控制x轴刻度
connect(ui->spinBox,SIGNAL(valueChanged(int)),this,SLOT(set_calibtation()));
PaintChart();
}
设置x轴刻度
void MainWindow::set_calibtation()
{
calibtation = ui->spinBox->value();
}
波形图框架:
void MainWindow::PaintChart()
{
//添加一条线
ui->customPlot->addGraph();
//设置x轴,y轴标签
ui->customPlot->xAxis->setLabel("x");
ui->customPlot->yAxis->setLabel("y");
//设置x,y轴的范围
ui->customPlot->xAxis->setRange(0, 10);
ui->customPlot->yAxis->setRange(0, 10);
//设置标题
ui->customPlot->plotLayout()->insertRow(0);
QCPTextElement *title = new QCPTextElement(ui->customPlot, "****图", QFont("sans", 17, QFont::Bold));
ui->customPlot->plotLayout()->addElement(0, 0, title);
//鼠标的拖动,缩放
ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
ui->customPlot->replot();
ui->spinBox->setValue(CALIBTATION_CONFIG);
ftimer = new QTimer(this);
ftimer->setInterval(1000);
ftimer->start();
connect(ftimer, SIGNAL(timeout()), this, SLOT(on_timer_timeout()));
}
动态添加数据
void MainWindow::on_timer_timeout()
{
key++;
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
value = qrand() % 100;
if (value > max_value)
{
max_value = value;
}
ui->customPlot->graph(0)->addData(key, value);
ui->customPlot->yAxis->setRange(0,max_value);
ui->customPlot->xAxis->setRange(key,calibtation,Qt::AlignRight);
ui->customPlot->replot();
}