QCharts绘制柱状图,柱高和y轴数据刻度不匹配
1 //在项目pro文件中添加以下内容
2 QT += charts
3
4 //在.h文件中添加以下内容,注意:需要将头文件及命名空间添加到ui命名空间之前,否则将提示错误
5 #include <QtCharts/QChartView>
6 #include <QtCharts/QBarSeries>
7 #include <QBarCategoryAxis>
8 #include <QValueAxis>
9 #include <QBarSet>
10
11 QT_CHARTS_USE_NAMESPACE
12
13 创建项目,在main.cpp中添加以下内容:
14
15 #include "mainwindow.h"
16 #include <QApplication>
17
18 int main(int argc, char *argv[])
19 {
20 QApplication a(argc, argv);
21 QBarSet *set0 = new QBarSet("警告");
22 QBarSet *set1 = new QBarSet("报警");
23
24 *set0 << 1 << 2 << 3 << 5 << 4;
25 *set1 << 2 << 4 << 0 << 5 << 4;
26
27 QBarSeries *series = new QBarSeries();
28 series->append(set0);
29 series->append(set1);
30
31 QChart *chart = new QChart();
32 //chart->addSeries(series); /************* 该语句应当放置此位置************/
33
34 QStringList dateList;
35 dateList << "11" << "12" << "13" << "14" << "15";
36 QBarCategoryAxis *axisX = new QBarCategoryAxis();
37 axisX->append(dateList);
38 axisX->setTitleText("日期");
39
40 QValueAxis *axisY = new QValueAxis();
41 axisY->setRange(0,10);
42 axisY->setLabelFormat("%d");
43 axisY->setTickCount(6);
44 axisY->setTitleText("次数");
45
46 chart->setAxisX(axisX, series); //设置X坐标轴
47 chart->setAxisY(axisY, series); //设置Y坐标轴
48
49 chart->legend()->setVisible(true); //设置图例为显示状态
50 chart->legend()->setAlignment(Qt::AlignBottom); //设置图例的显示位置在底部
51
52 chart->addSeries(series); /************* 问题所在************/
53 chart->setTitle("火情记录");
54 chart->setAnimationOptions(QChart::SeriesAnimations);
55
56 QChartView *chartView = new QChartView(chart);
57 chartView->setRenderHint(QPainter::Antialiasing);
58
59 MainWindow w;
60 w.setCentralWidget(chartView);
61 w.show();
62
63 return a.exec();
64 }
程序运行结果如下:
细心的朋友可以发现,明明数据值最大为5,但是柱状图的最高值为10,这就是问题所在
如果想要解决以上问题,需要将chart对象绑定数据序列放在创建坐标轴之前,修改后程序运行效果如下:
问题解决