main_page.png该示例显示如何创建条形图。
0x01 创建图表容器
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Simple barchart example");
chart->setAnimationOptions(QChart::SeriesAnimations);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
0x02 配置坐标轴
QStringList categories;
categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
QBarCategoryAxis *axisX = new QBarCategoryAxis();
axisX->append(categories);
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
QValueAxis *axisY = new QValueAxis();
axisY->setRange(0,15);
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);
0x03 加载条形图数据项
QBarSet *set0 = new QBarSet("Jane");
QBarSet *set1 = new QBarSet("John");
QBarSet *set2 = new QBarSet("Axel");
QBarSet *set3 = new QBarSet("Mary");
QBarSet *set4 = new QBarSet("Samantha");
*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;
QBarSeries *series = new QBarSeries();
series->append(set0);
series->append(set1);
series->append(set2);
series->append(set3);
series->append(set4);
0x04 配置图例注解位置
chart->legend()->setVisible(true);
chart->legend()->setAlignment(Qt::AlignBottom); /* 显示在底部 */
关于更多
- 在QtCreator软件可以找到:
- 或在以下Qt安装目录找到:
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\charts\barchart
- 相关链接
https://doc.qt.io/qt-5/qtcharts-barchart-example.html
- Qt君公众号回复『Qt示例』获取更多内容。
网友评论