预先准备
- 添加源文件和头文件
- greaterThan(QT_MAJOR_VERSION, 4): QT += widgets printsupport添加打印支持
- 在界面新建widget并且提升为qcustomplot
基础绘图
void MainWindow::create(QCustomPlot* customPlot){
QVector x(101),y(101);
for(int i=0;i<101;i++){
x[i]=i/50.0-1;
y[i]=x[i]*x[i];
}
customPlot->addGraph();
customPlot->graph(0)->setData(x,y);
customPlot->yAxis->setLabel("x");
customPlot->xAxis->setLabel("y");
customPlot->yAxis->setRange(0,1);
customPlot->xAxis->setRange(-1,1);
}
动态时间绘图
void MainWindow::setupRealtimeDataDemo(QCustomPlot *customPlot)//实时显示
{
customPlot->addGraph(); //在面板添加曲线
customPlot->graph(0)->setPen(QPen(QColor(40, 110, 255)));//曲线颜色
QSharedPointer timeTicker(new QCPAxisTickerTime);//智能指针
timeTicker->setTimeFormat("%h:%m:%s");//对指针设置时间格式
customPlot->xAxis->setTicker(timeTicker);//x的坐标区间
customPlot->axisRect()->setupFullAxesBox();//坐标轴撑满面板
customPlot->yAxis->setRange(-1.2, 1.2);//y坐标范围
connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));//当定时器溢出之后
dataTimer.start(0); //开启定时器
}
void MainWindow::realtimeDataSlot()
{
static QTime timeStart = QTime::currentTime();//从当前时间开始
double key = timeStart.msecsTo(QTime::currentTime())/1000.0;
static double lastPointKey = 0;
if (key-lastPointKey > 0.002)//每2毫秒添加一个点
{
ui->widget->graph(0)->addData(key,qSin(key/0.3843));//添加一个点
lastPointKey = key;
}
ui->widget->xAxis->setRange(key, 10, Qt::AlignRight);//位置,大小,对齐
ui->widget->replot();
}