使用QCPDataSelection来设置选中的区域,并将QCPGraph的可选择区域设置成QCP::stMultipleDataRanges
void AreaPieces::initCustomPlot(QCustomPlot *parentPlot)
{
QVector<double> x = {
0, 1, 2, 3, 4, 5, 6, 7, 8
};
QVector<double> y = {
200, 560, 750, 580, 250, 300, 450, 300, 100,
};
QVector<QString> labels = {
"2019-10-10",
"2019-10-11",
"2019-10-12",
"2019-10-13",
"2019-10-14",
"2019-10-15",
"2019-10-16",
"2019-10-17",
"2019-10-18",
};
auto ticker = QSharedPointer<QCPAxisTickerText>::create();
ticker->setTicks(x, labels);
QCPDataSelection selection;
selection.addDataRange(QCPDataRange(1, 4));
selection.addDataRange(QCPDataRange(5, 8));
QPen pen(QColor("#5470C6"), 5);
auto graph = new QCPSmoothGraph(parentPlot->xAxis, parentPlot->yAxis);
parentPlot->graph()->setData(x, y);
parentPlot->graph()->setPen(pen);
parentPlot->graph()->selectionDecorator()->setBrush(QColor(0, 0, 180, 102));
parentPlot->graph()->selectionDecorator()->setPen(pen);
parentPlot->graph()->setSelectable(QCP::stMultipleDataRanges);
parentPlot->graph()->setSelection(selection);
parentPlot->xAxis->setTicker(ticker);
parentPlot->xAxis->grid()->setVisible(false);
parentPlot->yAxis->setRange(0, 1000);
parentPlot->xAxis->setRange(0, 8);
}