1. 初始化

void MainWindow::initPlot(QCustomPlot* customPlot)
{
    customPlot->setNotAntialiasedElements(QCP::aeAll);

    QFont font;
    font.setStyleStrategy(QFont::NoAntialias);
    customPlot->xAxis->setTickLabelFont(font);
    customPlot->yAxis->setTickLabelFont(font);
    customPlot->legend->setFont(font);

    // 只在初始化时添加graph
    if (customPlot->graphCount() == 0)
    {
        for (int i = 0; i < 6; i++)
        {
            customPlot->addGraph();
            customPlot->graph(i)->setPen(QPen(this->tempColor[i]));
            customPlot->graph(i)->setName(QString("轴%1").arg(i + 1));
            customPlot->graph(i)->setAntialiasedFill(false);
        }
    }

    // 显示完整边框
    customPlot->axisRect()->setupFullAxesBox();

    //QCPAxisTickerDateTime 时间坐标轴 必须要用智能指针
    QSharedPointer<QCPAxisTickerDateTime> timer(new QCPAxisTickerDateTime);
    timer->setDateTimeFormat("hh:mm:ss");
    //设置时间轴 一共几格
    timer->setTickCount(5);
    //设置label 旋转35° 横着显示可能显示不全
    //customPlot->xAxis->setTickLabelRotation(30);
    timer->setTickStepStrategy(QCPAxisTicker::tssMeetTickCount);
    customPlot->xAxis->setTicker(timer);

    // 设置坐标轴名称
    customPlot->xAxis->setLabel("当前时间(时:分:秒)");
    customPlot->yAxis->setLabel("纵坐标");

    // 设置图例行优先排列
    //customPlot->legend->setFillOrder(QCPLayoutGrid::foColumnsFirst);
    // 设置六个图例自动换行
    customPlot->legend->setWrap(6);
    // 设置图例可见
    customPlot->legend->setVisible(true);
    // 设置边框隐藏
    //customPlot->legend->setBorderPen(Qt::NoPen);
    // 设置图例位置
    customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignLeft | Qt::AlignTop);

    // 设置放大缩小
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    // 设置x轴范围
    double nowTime = QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000.0;
    customPlot->xAxis->setRange(nowTime, 30, Qt::AlignRight);

    // make left and bottom axes transfer their ranges to right and top axes:
    connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
}

2.清空、添加数据

	// 获取当前时间
    double nowTime = QDateTime::currentDateTime().toMSecsSinceEpoch() / 1000.0;

	// 清空所有数据
    ui.widget_Plot1->clearGraphs();
	// 添加数据
	ui.widget_Plot1->graph(0)->addData(nowTime, value1);
    // 自动重设坐标
    ui.widget_Plot1->graph(0)->rescaleValueAxis(true);
	// 设置横坐标宽度为30s
    ui.widget_Plot1->xAxis->setRange(time, 30, Qt::AlignRight);
    // 刷新显示
    ui.widget_Plot1->replot();
	// 获取当前数据点数
    int pointCnt= ui.widget_Plot1->graph(0)->dataCount();
    // 清空线条内容
    ui.widget_Plot1->graph(0)->data().data()->clear();
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐