包含折线图渐变效果以及QCPAxisTickerDateTime
的使用
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);
}