【QCustomPlot实战系列】QCPGraph折线图的渐变

包含折线图渐变效果以及QCPAxisTickerDateTime的使用
QCPGraph折线图的渐变

static QBrush GenerateLinearBrush(Qt::Orientation orientation)
{
    qreal x = 1;
    qreal y = 0;
    if (orientation == Qt::Vertical) {
        x=0;
        y=1.5;
    }

    QLinearGradient gradient(0, y, x, 0);
    gradient.setCoordinateMode(QLinearGradient::ObjectMode);
    gradient.setColorAt(0, QColor(255, 255, 180));
    gradient.setColorAt(1, QColor(190, 68, 76));
    return { gradient };
}

static QCPGraph* GenerateGraph(QCustomPlot *parentPlot, Qt::Orientation orientation)
{
    QVector<double> x;
    QVector<double> y = {
            116, 129, 135, 86, 73, 85, 73, 68, 92, 130, 245, 139, 115, 111, 309,
            206, 137, 128, 85, 94, 71, 106, 84, 93, 85, 73, 83, 125, 107, 82,
            44, 72, 106, 107, 66, 91, 92, 113, 107, 131, 111, 64, 69, 88, 77, 83,
            111, 57, 55, 60
    };

    x.resize(y.count());

    auto startDateTime = QDateTime(QDate(2000, 6, 5)).toSecsSinceEpoch();

    for (int i = 0; i < y.count(); ++i) {
        x[i] = double(startDateTime + i * 3600 * 24);
    }

    auto ticker = QSharedPointer<QCPAxisTickerDateTime>::create();
    ticker->setDateTimeFormat("yyyy-MM-dd");
    ticker->setTickOrigin(x.first());
    ticker->setTickCount(10);

    auto axisRect = new QCPAxisRect(parentPlot);
    axisRect->axis(QCPAxis::atBottom)->setTicker(ticker);

    auto graph = new QCPGraph(axisRect->axis(QCPAxis::atBottom), axisRect->axis(QCPAxis::atLeft));
    graph->setData(x, y);
    graph->setPen(QPen(GenerateLinearBrush(orientation), 2));

    axisRect->axis(QCPAxis::atBottom)->rescale();
    axisRect->axis(QCPAxis::atLeft)->setRange(0, 350);

    auto text = new QCPTextElement(parentPlot);
    auto font = text->font();
    font.setPointSize(18);
    text->setFont(font);
    text->setTextColor(QColor(70, 70, 70));
    if (orientation == Qt::Vertical) {
        text->setText("Gradient along the y axis");
    } else {
        text->setText("Gradient along the x axis");
    }
    parentPlot->plotLayout()->addElement(text);
    parentPlot->plotLayout()->addElement(axisRect);
    QAbstractPlotItem::applyDefaultStyle(axisRect);

    return graph;
}

void LineGradient::initCustomPlot(QCustomPlot *parentPlot)
{
    parentPlot->plotLayout()->clear();
    parentPlot->plotLayout()->setFillOrder(QCPLayoutGrid::foRowsFirst);

    auto margin = new QCPLayoutElement(parentPlot);
    margin->setMinimumSize(0, 50);
    margin->setMaximumSize(QWIDGETSIZE_MAX, 50);
    GenerateGraph(parentPlot, Qt::Vertical);
    parentPlot->plotLayout()->addElement(margin);
    GenerateGraph(parentPlot, Qt::Horizontal);
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值