示例:
要求:查询成绩表中各个分数段的人数,并以柱状图的形式显示。
注:分数信息储存在(navicat)student_score表中,点击mainwindow中的一个按钮,弹出statistic窗口,在statistic窗口显示柱状图。
mainwindow.cpp
QSqlQuery query;
int arrary[10]={0};//储存查询到的结果
query.exec("select score from student_score");
while(query.next())
{
int a=query.value("score").toInt();
if (a>=0&&a<10)
arrary[0]+=1;
if (a>=10&&a<20)
arrary[1]+=1;
if (a>=20&&a<30)
arrary[2]+=1;
if (a>=30&&a<40)
arrary[3]+=1;
if (a>=40&&a<50)
arrary[4]+=1;
if (a>=50&&a<60)
arrary[5]+=1;
if (a>=60&&a<70)
arrary[6]+=1;
if (a>=70&&a<80)
arrary[7]+=1;
if (a>=80&&a<90)
arrary[8]+=1;
if (a>=90&&a<=100)
arrary[9]+=1;
}
statistics *s=new statistics;//创建指向statistic页面的指针
s->show();
这里在mainwindow.cpp中创建了一个数组,但是无法将查询到的结果传到statistic.cpp,也创建不了能够显示结果的柱状图。
修改:
mainwindow.h
创建类的公有静态成员数组,这样不创建类的对象也可以使用该数组。
public:
static int arrary[10];
mainwindow.cpp
首先要删掉这一句:
int arrary[10]={0};//储存查询到的结果
添加静态成员数组的初始化:
int MainWindow::arrary[10]={0};
在.pro文件添加:
QT+=charts
在statistic.cpp添加:
#include <QtCharts>
statistic.cpp
QChart *chart = new QChart();
chart->setTitle("课程平均分数段人数分布");
//创建一个表示柱状图数据集的一个对象,创建Y轴数据
QBarSet *set = new QBarSet("人数");
int i;
for (i=0;i<10;i++)
{
*set<<MainWindow::arrary[i];//这里是关键
}
//创建x轴数据
QStringList categories;
categories<<"0~9"<<"10~19"<<"20~29"<<"30~39"<<"40~49"<<"50~59"<<"60~69"<<"70~79"<<"80~89"<<"90~100";
//创建一个用于显示柱状图的对象
QBarSeries *series = new QBarSeries();
series->append(set);
//创建X轴
QBarCategoryAxis *axisX=new QBarCategoryAxis;
axisX->setTitleText("分数段");
axisX->append(categories);
chart->addAxis(axisX,Qt::AlignBottom);
//创建Y轴
QValueAxis *axisY=new QValueAxis();
axisY->setTitleText("人数");
chart->addAxis(axisY,Qt::AlignLeft);
//添加
chart->addSeries(series);
series->attachAxis(axisX);
series->attachAxis(axisY);
// 创建图表视图组件并设置图表
QChartView *chartView = new QtCharts::QChartView(chart, this);
// 设置垂直布局
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(chartView);
结果:
希望能够对大家有所帮助,欢迎指正。