C++ QT:折线图显示数据

QT:折线图显示数据

  • 1.在ui中加入一个widget控件
  • 2.需要另外导入类:qcustomplot,将新建的widget控件在设计师页面提升为qcustomplot

注意:提升的类名不要写错大小写
在这里插入图片描述

  • 3.在构造函数中创建折线图的标题和XY轴信息
	//折线图
    QCustomPlot* customPlot_AA = ui->widget_chart;
    customPlot_AA->xAxis->setRange(0, 10);//设置X列范围
    customPlot_AA->yAxis->setRange(0, 150);//设置Y列范围
    customPlot_AA->xAxis->setVisible(true);
    customPlot_AA->yAxis->setVisible(true);
    //初始化曲线图标题
    QCPTextElement* title_AA = new QCPTextElement(customPlot_AA, QSC("曲线标题"), QFont("sans", 10, QFont::Bold));
    title_AA->setTextColor(Qt::green);
    title_AA->setMargins(QMargins(0, 6, 0, 10));
    customPlot_AA->plotLayout()->insertRow(0);// 插入一行
    customPlot_AA->plotLayout()->addElement(0, 0, title_AA);

    ui->widget_chart->xAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
    ui->widget_chart->yAxis->setUpperEnding(QCPLineEnding::esSpikeArrow);
    ui->widget_chart->legend->setFont(QFont("微软雅黑", 15));
    ui->widget_chart->xAxis->setLabel("步数");  //设置X列名字
    ui->widget_chart->yAxis->setLabel(QSC("数据"));   //设置Y列名字

    ui->widget_chart->replot();

在这里插入图片描述

  • 4.写入数据
//折线图
    //step:图形第步数,此处举例三个折线,在此步数的数值为:num1,num2,num3
    void setChart(int step,int num1, int num2, int num3);
void MainWidget::setChart(int step, int num1, int num2, int num3)
{
    QCustomPlot* customPlot = ui->widget_chart;

    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(Qt::blue)); 
    customPlot->graph(0)->setName("chart1");
    ui->widget_chart->graph(0)->addData(step, num1);

    customPlot->addGraph();//添加graph等价于添加一条新曲线
    customPlot->graph(1)->setPen(QPen(Qt::red)); // 颜色
    customPlot->graph(1)->setName("chart2");//设置名称
    ui->widget_chart->graph(1)->addData(step, num2);

    customPlot->addGraph();
    customPlot->graph(2)->setPen(QPen(Qt::yellow)); // 颜色
    customPlot->graph(2)->setName("chart3");
    ui->widget_chart->graph(2)->addData(step, num3);

    customPlot->replot();
}

测试:

void MainWidget::on_pushButton_clicked()
{
    setChart(0, 10, 20, 30);
    setChart(1, 40, 50, 60);
    setChart(2, 50, 70, 80);
    setChart(3, 20, 90, 100);
    setChart(9, 40, 20, 70);
}

在这里插入图片描述

  • 5.进行覆盖(清空折线图)
//清空折线图数据(初始化数据)
    void ChartInit();
void MainWidget::ChartInit()
{
    ui->widget_chart->clearGraphs();
    ui->widget_chart->replot();
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值