线和条形图范例

示例将组合线图表与条形图表,并将类别轴用作 2 者的公共轴。

运行范例

要运行范例从 Qt Creator ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,拜访 构建和运行范例 .

组合图表

在这里,为条形系列创建数据。

    QBarSet *set0 = new QBarSet("Jane");
    QBarSet *set1 = new QBarSet("John");
    QBarSet *set2 = new QBarSet("Axel");
    QBarSet *set3 = new QBarSet("Mary");
    QBarSet *set4 = new QBarSet("Sam");
    *set0 << 1 << 2 << 3 << 4 << 5 << 6;
    *set1 << 5 << 0 << 0 << 4 << 0 << 7;
    *set2 << 3 << 5 << 8 << 13 << 8 << 5;
    *set3 << 5 << 6 << 7 << 3 << 4 << 5;
    *set4 << 9 << 7 << 5 << 3 << 1 << 2;
					

We create a bar series and append sets to it. The first values of each set are grouped together in the first category, the second values in the second category and so on.

    QBarSeries *barseries = new QBarSeries();
    barseries->append(set0);
    barseries->append(set1);
    barseries->append(set2);
    barseries->append(set3);
    barseries->append(set4);
					

Then we create a line series and add data to it. To make the data match with the barchart, we use the index as an x-value for our line series, so that first point is at (0,value) second at (1,value) and so on.

    QLineSeries *lineseries = new QLineSeries();
    lineseries->setName("trend");
    lineseries->append(QPoint(0, 4));
    lineseries->append(QPoint(1, 15));
    lineseries->append(QPoint(2, 20));
    lineseries->append(QPoint(3, 4));
    lineseries->append(QPoint(4, 12));
    lineseries->append(QPoint(5, 17));
					

Here we create the chart and add both series to it.

    QChart *chart = new QChart();
    chart->addSeries(barseries);
    chart->addSeries(lineseries);
    chart->setTitle("Line and barchart example");
					

To make the chart show the series properly, we have to create custom axes for the series. If we don't create custom axes, then each series will get scaled to use the maximum area of the chart (like in single series case) and the result will be incorrect. With custom axes we set the range of both series to follow the same axis. For the x-axis we use the QBarCategoryAxis and for the y-axis we use QValuesAxis.

    QStringList categories;
    categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(categories);
    chart->setAxisX(axisX, lineseries);
    chart->setAxisX(axisX, barseries);
    axisX->setRange(QString("Jan"), QString("Jun"));
    QValueAxis *axisY = new QValueAxis();
    chart->setAxisY(axisY, lineseries);
    chart->setAxisY(axisY, barseries);
    axisY->setRange(0, 20);
					

And we also want to show the legend.

    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);
					

Finally we add the chart onto a view.

    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
					

Now it is ready to be shown in a window.

    QMainWindow window;
    window.setCentralWidget(chartView);
    window.resize(440, 300);
    window.show();
					

文件: