QT barchart将数据转化成条形图

1.在工程文件.pro中加入

QT       += charts

2.需要的头文件

#include <QChart>

#include <QBarSet>

#include <QBarSeries>

3.创建集合并向它们追加数据

 QBarSet *set0 = new QBarSet("Jane");

*set0 << 1 << 2 << 3 << 4 << 5 << 6;

4.创建 series结合并且添加barsets

QBarSeries *series = new QBarSeries();
series->append(set0);

5.创建chart,并且添加series

QChart *chart = new QChart();
 chart->addSeries(series);

6.创建类别轴和类别列表

1 QStringList categories;
2 categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
3  QBarCategoryAxis *axis = new QBarCategoryAxis();
4  axis->append(categories);
5  chart->createDefaultAxes();
6  chart->setAxisX(axis, series);

7.显示图例

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

8.创建画布

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

显示代码

 1 barChart::barChart(QWidget *parent) :
 2     QWidget(parent),
 3     ui(new Ui::barChart)
 4 {
 5     ui->setupUi(this);
 6     QBarSet* set0 = new QBarSet("jane");
 7     QBarSet* set1 = new QBarSet("jone");
 8     QBarSet* set2 = new QBarSet("mary");
 9     QBarSet* set3 = new QBarSet("Alsex");
10     QBarSet* set4 = new QBarSet("summer");
11     *set0<<1<<2<<3<<4<<5;
12     *set1<<5<<9<<2<<0<<3;
13     *set2<<3<<7<<1<<4<<2;
14     *set3<<6<<1<<9<<8<<3;
15     *set4<<0<<2<<6<<8<<1;
16     QBarSeries* barSerise = new QBarSeries();
17     barSerise->append(set0);
18     barSerise->append(set1);
19     barSerise->append(set2);
20     barSerise->append(set3);
21     barSerise->append(set4);
22     QChart* chart = new QChart();
23     chart->addSeries(barSerise);
24     chart->setTitle("Simple barchart example");
25     chart->setAnimationOptions(QChart::SeriesAnimations);
26     
27     QStringList str;
28     str<< "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
29     QBarCategoryAxis* axisx = new QBarCategoryAxis();
30     axisx->append(str);
31     chart->createDefaultAxes();
32     chart->setAxisX(axisx);
33 
34     chart->legend()->setVisible(true);
35     chart->legend()->setAlignment(Qt::AlignBottom);
36 
37     QChartView* chartView = new QChartView(chart);
38     chartView->setRenderHint(QPainter::Antialiasing);
39 
40     QHBoxLayout *layout = new QHBoxLayout();
41     layout->setContentsMargins(0, 0, 0, 0);
42     layout->addWidget(chartView);
43     setLayout(layout);
44 
45 }
46 
47 barChart::~barChart()
48 {
49     delete ui;
50 }

 运行结果

posted on 2018-07-12 18:28  小小小哈  阅读(3814)  评论(1编辑  收藏  举报

导航