VS2015 Qt5.11.3使用QChart实现柱状图

首先打开.ui文件,拖动一个Widget到窗口上:
VS2015 Qt5.11.3使用QChart实现柱状图_第1张图片
在widget上右键,点击提升为:
VS2015 Qt5.11.3使用QChart实现柱状图_第2张图片
输入提升的类名称为:QChartView,头文件改为:QtCharts/qchartview.h,然后点击添加和提升。(输入类名称时头文件会自动填入qchartview.h,如果不想手动改则需要在项目属性->c/c+±>常规->附加包含目录中加入:$(QTDIR)\include\QtCharts)

然后在.h中(在#include "ui_xxx.h"之前)添加QChart的头文件和宏,和需要的库,具体代码:

#include 
QT_CHARTS_USE_NAMESPACE

#ifdef _DEBUG
#pragma comment(lib,"Qt5Chartsd.lib") //Debug
#else
#pragma comment(lib,"Qt5Charts.lib") //Release
#endif 

#include 
#include "ui_QtTest.h"
                 最后附上作图代码,该代码是demo上照搬过来的
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;// Jane 6个月份的值
	*set1 << 5 << 0 << 0 << 4 << 0 << 7;
	*set2 << 3 << 5 << 8 << 19 << 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);

	QChart *chart = new QChart();
	chart->addSeries(series);
	chart->setTitle(QString::fromLocal8Bit("柱状图"));
	chart->setAnimationOptions(QChart::SeriesAnimations);

	QStringList categories;
	categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun";
	QBarCategoryAxis *axis = new QBarCategoryAxis();
	axis->append(categories);
	chart->createDefaultAxes();//创建默认的左侧的坐标轴(根据 QBarSet 设置的值)
	chart->setAxisX(axis, series);//设置坐标轴

	chart->legend()->setVisible(true); //设置图例为显示状态
	chart->legend()->setAlignment(Qt::AlignBottom);//设置图例的显示位置在底部

	ui.widget->setChart(chart);
	ui.widget->setRenderHint(QPainter::Antialiasing);

效果图:
VS2015 Qt5.11.3使用QChart实现柱状图_第3张图片

你可能感兴趣的:(QT,QtCharts,C++)