第一步、先配置CMakeLists.txt
在CMakeLists.txt中添加
find_package(Qt6 REQUIRED COMPONENTS Sql)
find_package(Qt6 REQUIRED COMPONENTS Charts)
target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Sql)
target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Charts)
避免在包含Qsql库中出现不存在的情况。
第二步、在资源文件中添加.DB文件
先创建resource file。
创建了一个命名为data.qrc的文件,并在cmake中添加该文件。
添加.db文件。
第二步、打开数据库,创建表头,增删改查
//打开数据库
//获得一个基于SQLite的数据库连接对象
db = QSqlDatabase::addDatabase("QSQLITE");
//设置数据库文件的名称
db.setDatabaseName("./raic.db"); // 数据库文件为raic.db
if (!db.open())
{
qDebug() << "默认数据库打开失败" << db.lastError();
}
//创建表头
void Composition::createTable()
{
QString sql="CREATE TABLE composition(id INTERGER PERIMARY KEY,material TEXT,yvalue INTERGER,createtimestamp TEXT,createtime DATETIME)";
//数据库操作类
QSqlQuery sq;
if(sq.exec(sql))
{
qDebug()<<"建表成功!";
}else
{
qDebug()<<sq.lastError().text();//上一次操作的错误信息
}
}
//增加数据
void MainWindow::on_insertBtn_clicked()
{
int materialID = ui->lineEdit->text().toInt();
QString material = ui->lineEdit_2->text();
int yvalue = ui->lineEdit_3->text().toInt();
QDateTime time = QDateTime::currentDateTime();
QString timestr = time.toString("yyyy-MM-dd hh::mm::ss");
qint64 timeT = time.toMSecsSinceEpoch();
qDebug()<<timeT;
ui->lineEdit_4->setText(QString::number(timeT));
ui->lineEdit_5->setText(timestr);
Composition com;
com.materialID = materialID;
com.material = material;
com.yvalue = yvalue;
com.createtimestamp = timeT;
com.createtime = timestr;
Composition::insertCompositionToDatabase1(com);
}
第四步、根据数据库的数据画图
//画分布图
QDateTimeEdit//起始时间框
QChartview//画布
//皮带上物料的分布
void MainWindow::on_beltclassify_clicked()
{
QList<int> beltMaterialList;
// 判断时间
int64 beginT = ui->startdateTimeEdit->dateTime().toMSecsSinceEpoch();
int64 endT = ui->enddateTimeEdit->dateTime().toMSecsSinceEpoch();
if (beginT >= endT)
{
QMessageBox::information(this, "起止时间", "开始时间必须小于结束时间");
return;
}
Composition::getPeriodYvalueInfoFromDatabase(&beltMaterialList, beginT, endT);
if (beltMaterialList.count() == 0)
{
qDebug() << "当前条件下无皮带上物料分布数据";
QMessageBox::information(this, "物料分布", "当前条件下无皮带上物料分布数据");
return;
}
// 绘制皮带上物料分布柱状图
beltMaterialBarChart(&beltMaterialList);
}
void Composition::getPeriodYvalueInfoFromDatabase(QList<int> *list, qint64 beginStamp, qint64 endStamp)
{
// 根据时间范围查询所有物料的y值
QSqlQuery query;
QString sqlstr;
sqlstr = QString("SELECT yvalue FROM composition WHERE createtimestamp >= %1 AND createtimestamp <= %2").arg(beginStamp).arg(endStamp);
// qDebug() << "物料成分查询记录sql: " << sqlstr;
query.exec(sqlstr);
while (query.next())
{
QSqlRecord record = query.record();
int y = record.value("yvalue").toInt();
list->append(y); // 将获取到的物料成分信息追加到链表中
}
}
void MainWindow::beltMaterialBarChart(QList<int> *list)
{
if (list->count() < 1)
{
qDebug() << "valveBarChart:无数据";
return;
}
// 整理数据
int data[5] = {0};
QList<QString> axisXLabels;
// axisXLabels << "0-200"<< "200-400"<< "400-600"<< "600-800"<< "800-1000"; //5
axisXLabels << "1"<< "2"<< "3"<< "4"<< "5"; // 5
foreach(int y, *list)
{
if (y >1000){
y = 1000;
}
if (y < 0){
y = 0;
}
data[y/200]++; // 向下取整 配合从0开始的索引 正好
}
QChart *chart = new QChart();
QBarSet *set = new QBarSet("数量"); // 创建条线数据
QBarCategoryAxis *axisX = new QBarCategoryAxis; // 创建X轴
axisX->append(axisXLabels);
int max = 0;
for(int i = 0; i<5;i++)
{
*set << data[i];
if (data[i] > max)
max = data[i];
}
// 设置X轴字体大小
QFont font;
font.setPointSize(12);
axisX->setLabelsFont(font);
set->setLabelFont(font); // 调整柱子上数字的大小
set->setLabelColor(Qt::black); // 用了主题 颜色被覆盖了
QBarSeries *series = new QBarSeries();
series->append(set);
series->setVisible(true);
series->setLabelsPosition(QAbstractBarSeries::LabelsOutsideEnd); //设置标签显示的位置
series->setLabelsVisible(true); //设置数据标签可见
chart->addSeries(series); // 添加系列到QChart上
// 创建Y轴
QValueAxis *axisY = new QValueAxis;
axisY->setRange(0, ceil(max * 0.1 * 1.1) * 10);
axisY->setLabelFormat("%d");
// 设置Y轴字体大小
axisY->setLabelsFont(font);
axisY->setVisible(false);
chart->addAxis ( axisX, Qt::AlignBottom );
chart->addAxis ( axisY, Qt::AlignLeft );
series->attachAxis ( axisX );
series->attachAxis ( axisY );
//修改图例
chart->legend()->hide();
chart->setTitle("皮带物料分布");
// 设置表格主题
// chart->setTheme(QChart::ChartThemeBlueCerulean);
chart->setTheme(QChart::ChartThemeDark);
chart->setAnimationOptions(QChart::AllAnimations); //动画效果
ui->beltView->setChart(chart);
ui->beltView->setRenderHint(QPainter::Antialiasing);
}
void MainWindow::on_materialclassify_clicked()
{
int64 beginT = ui->startdateTimeEdit->dateTime().toMSecsSinceEpoch();
int64 endT = ui->enddateTimeEdit->dateTime().toMSecsSinceEpoch();
if (beginT >= endT)
{
QMessageBox::information(this, "起止时间", "开始时间必须小于结束时间");
return;
}
QList<int> MaterialList;
Composition::getmaterialInfoFromDatabase(&MaterialList, beginT, endT);
if (MaterialList.count() == 0)
{
qDebug() << "当前条件下无皮带上物料分布数据";
QMessageBox::information(this, "物料分布", "当前条件下无皮带上物料分布数据");
return;
}
setpieChart(&MaterialList);
}
void MainWindow::setpieChart(QList<int> *list)
{
if (list->count() < 1)
{
qDebug() << "valveBarChart:无数据";
return;
}
double blackNum = 0, AggreNum = 0;
foreach(int y, *list)
{
if (y ==0){
blackNum++ ;
}
if (y== 1){
AggreNum++;
}
}
double total = blackNum+AggreNum;
// qDebug()<<"混凝土"<<AggreNum;
// qDebug()<<"红砖"<<blackNum;
// qDebug()<<"总计"<<total;
double Blackpart =qCeil( blackNum/total*100);
double Aggrepart = qFloor(AggreNum/total*100);
// qDebug()<<"红砖占比"<<Blackpart;
// qDebug()<<"混凝土占比"<<Aggrepart;
m_mySeries = new QPieSeries();
m_mySeries->append("红砖",Blackpart);
m_mySeries->append("混凝土",Aggrepart);
QPieSlice *myRed = m_mySeries->slices().at(0);
QPieSlice *myGreen = m_mySeries->slices().at(1);
myRed->setColor(QColor(255,0,0,255));
myRed->setLabelVisible();
myGreen->setColor(QColor(0,255,0,255));
myGreen->setLabelVisible();
QChart *myChart = new QChart;
myChart->addSeries(m_mySeries);
QFont font;
font.setPointSize(8);
myChart->setTitle("混凝土和红砖分布");
myChart->setTitleFont(font);
myChart->legend()->hide(); //隐藏图例
// myChart->setTheme(QChart::ChartThemeBlueNcs); //设置主题
myChart->setTheme(QChart::ChartThemeDark);
myChart->setAnimationOptions(QChart::AllAnimations); //动画效果
ui->materialView->setChart(myChart);
ui->materialView->setRenderHint(QPainter::Antialiasing);
}
最终图示: