sqltablemodel 组件可以将数据库中的特定字段动态显示在tableview
表格组件中,通常设置qsqltablemodel
类的变量作为数据模型后就可以显示数据表内容,界面组件中则通过qdatawidgetmapper
类实例设置为与某个数据库字段相关联,则可以实现自动显示字段的内容,不仅是显示,其还支持动态增删改查
等各种复杂操作,期间不需要使用任何sql语句。
首先绘制好ui界面,本次案例界面稍显复杂,左侧是一个tableview
组件,其他地方均为lineedit
组件与button
组件。
先来生成数据库表记录,此处我们只需要增加一个student
学生表,并插入两条测试数据即可,运行以下代码完成数据创建。
#include <iostream>
#include <qsqldatabase>
#include <qsqlerror>
#include <qsqlquery>
#include <qsqlrecord>
#include <qtsql>
#include <qdatawidgetmapper>
qsqldatabase db; // 数据库连接
void mainwindow::initsql()
{
qsqldatabase db = qsqldatabase::adddatabase("qsqlite");
db.setdatabasename("./lyshark.db");
if (!db.open())
{
return;
}
// 执行sql创建表
// https://www.cnblogs.com/lyshark
db.exec("drop table student");
db.exec("create table student ("
"id integer primary key autoincrement, "
"name varchar(40) not null, "
"sex varchar(40) not null, "
"age integer not null,"
"mobile varchar(40) not null,"
"city varchar(40) not null)"
);
// 逐条插入数据
db.exec("insert into student(name,sex,age,mobile,city) ""values ('lyshark.cnblogs.com','m','25','1234567890','beijing')");
db.exec("insert into student(name,sex,age,mobile,city) ""values ('www.lyshark.com','x','22','4567890987','shanghai')");
db.commit();
db.close();
}
数据库创建后表内记录如下:
程序运行后我们将在mainwindow::mainwindow(qwidget *parent)
构造函数内完成数据库表记录与tableview
组件字段的对应关系绑定,将数据库绑定到qdatawidgetmapper
对象上,绑定代码如下。
mainwindow::mainwindow(qwidget *parent) :qmainwindow(parent),ui(new ui::mainwindow)
{
ui->setupui(this);
// 打开数据库
db=qsqldatabase::adddatabase("qsqlite"); // 添加 sql lite数据库驱动
db.setdatabasename("./lyshark.db"); // 设置数据库名称
if (!db.open())
{
return;
}
// 打开数据表
tabmodel=new qsqltablemodel(this,db); // 数据表
tabmodel->settable("student"); // 设置数据表
tabmodel->seteditstrategy(qsqltablemodel::onmanualsubmit); // 数据保存方式,onmanualsubmit , onrowchange
tabmodel->setsort(tabmodel->fieldindex("id"),qt::ascendingorder); // 排序
if (!(tabmodel->select())) // 查询数据
{
return;
}
// 设置字段名称
tabmodel->setheaderdata(tabmodel->fieldindex("id"),qt::horizontal,"uid");
tabmodel->setheaderdata(tabmodel->fieldindex("name"),qt::horizontal,"uname");
tabmodel->setheaderdata(tabmodel->fieldindex("sex"),qt::horizontal,"usex");
tabmodel->setheaderdata(tabmodel->fieldindex("age"),qt::horizontal,"uage");
tabmodel->setheaderdata(tabmodel->fieldindex("mobile"),qt::horizontal,"umobile");
tabmodel->setheaderdata(tabmodel->fieldindex("city"),qt::horizontal,"ucity");
theselection=new qitemselectionmodel(tabmodel); // 关联选择模型
ui->tableview->setmodel(tabmodel); // 设置数据模型
ui->tableview->setselectionmodel(theselection); // 设置选择模型
ui->tableview->setselectionbehavior(qabstractitemview::selectrows); // 行选择模式
// 添加数据映射,将选中字段映射到指定编辑框中
// https://www.cnblogs.com/lyshark
datamapper= new qdatawidgetmapper();
datamapper->setmodel(tabmodel);
datamapper->setsubmitpolicy(qdatawidgetmapper::autosubmit);
datamapper->addmapping(ui->lineedit_name,tabmodel->fieldindex("name")); // 设置映射字段
datamapper->addmapping(ui->lineedit_mobile,tabmodel->fieldindex("mobile")); // 第二个映射字段
datamapper->tofirst(); // 默认选中首条映射记录
// 绑定信号,当鼠标选择时,在底部编辑框中输出
connect(theselection,signal(currentrowchanged(qmodelindex,qmodelindex)),this,slot(on_currentrowchanged(qmodelindex,qmodelindex)));
getfieldnames();
}
mainwindow::~mainwindow()
{
delete ui;
}
绑定成功后运行程序即可看到如下效果,数据库中的记录被映射到了组件内.
当用户点击tableview
组件内的某一行记录时,则触发mainwindow::on_currentrowchanged
函数。
void mainwindow::on_currentrowchanged(const qmodelindex ¤t, const qmodelindex &previous)
{
q_unused(previous);
datamapper->setcurrentindex(current.row()); // 更细数据映射的行号
int currecno=current.row(); // 获取行号
qsqlrecord currec=tabmodel->record(currecno); // 获取当前记录
qstring uname = currec.value("name").tostring(); // 取出数据
qstring mobile = currec.value("mobile").tostring();
ui->lineedit_name->settext(uname); // 设置到编辑框
ui->lineedit_mobile->settext(mobile);
}
运行效果如下:
增加插入与删除记录实现方法都是调用tabmodel
提供的默认函数,通过获取当前选中行号,并对该行号执行增删改查方法即可。
// 新增一条记录
// https://www.cnblogs.com/lyshark
void mainwindow::on_pushbutton_add_clicked()
{
tabmodel->insertrow(tabmodel->rowcount(),qmodelindex()); // 在末尾添加一个记录
qmodelindex curindex=tabmodel->index(tabmodel->rowcount()-1,1); // 创建最后一行的modelindex
theselection->clearselection(); // 清空选择项
theselection->setcurrentindex(curindex,qitemselectionmodel::select); // 设置刚插入的行为当前选择行
int currow=curindex.row(); // 获得当前行
tabmodel->setdata(tabmodel->index(currow,0),1000+tabmodel->rowcount()); // 自动生成编号
tabmodel->setdata(tabmodel->index(currow,2),"m"); // 默认为男
tabmodel->setdata(tabmodel->index(currow,3),"0"); // 默认年龄0
}
// 插入一条记录
void mainwindow::on_pushbutton_insert_clicked()
{
qmodelindex curindex=ui->tableview->currentindex();
int currow=curindex.row(); // 获得当前行
tabmodel->insertrow(curindex.row(),qmodelindex());
tabmodel->setdata(tabmodel->index(currow,0),1000+tabmodel->rowcount()); // 自动生成编号
theselection->clearselection(); // 清除已有选择
theselection->setcurrentindex(curindex,qitemselectionmodel::select);
}
// 删除一条记录
void mainwindow::on_pushbutton_delete_clicked()
{
qmodelindex curindex=theselection->currentindex(); // 获取当前选择单元格的模型索引
tabmodel->removerow(curindex.row()); // 删除最后一行
}
// 保存修改数据
void mainwindow::on_pushbutton_save_clicked()
{
bool res=tabmodel->submitall();
if (!res)
{
std::cout << "save as ok" << std::endl;
}
}
// 恢复原始状态
void mainwindow::on_pushbutton_reset_clicked()
{
tabmodel->revertall();
}
增删改查实现如下:
针对与排序与过滤的实现方式如下,同样是调用了标准函数。
// 以combox中的字段对目标 升序排列
void mainwindow::on_pushbutton_ascending_clicked()
{
tabmodel->setsort(ui->combobox->currentindex(),qt::ascendingorder);
tabmodel->select();
}
// 以combox中的字段对目标 降序排列
// https://www.cnblogs.com/lyshark
void mainwindow::on_pushbutton_descending_clicked()
{
tabmodel->setsort(ui->combobox->currentindex(),qt::descendingorder);
tabmodel->select();
}
// 过滤出所有男记录
void mainwindow::on_pushbutton_filter_man_clicked()
{
tabmodel->setfilter(" sex = 'm' ");
}
// 恢复默认过滤器
void mainwindow::on_pushbutton_default_clicked()
{
tabmodel->setfilter("");
}
过滤效果如下所示:
批量修改某个字段,其实现原理是首先通过i<tabmodel->rowcount()
获取记录总行数,然后通过arec.setvalue
设置指定字段数值,并最终tabmodel->submitall()
提交到表格中。
void mainwindow::on_pushbutton_clicked()
{
if (tabmodel->rowcount()==0)
return;
for (int i=0;i<tabmodel->rowcount();i++)
{
qsqlrecord arec=tabmodel->record(i); // 获取当前记录
arec.setvalue("age",ui->lineedit->text()); // 设置数据
tabmodel->setrecord(i,arec);
}
tabmodel->submitall(); // 提交修改
}
循环修改实现效果如下:
上方代码中,如果需要修改或增加特定行或记录我们只需要点击相应的按钮,并在选中行直接编辑即可实现向数据库中插入数据,而有时我们不希望通过在原表上操作,而是通过新建窗体并在窗体中完成增删改,此时就需要使用dialog窗体并配合原生sql语句来实现对记录的操作了。
以增加为例,主窗体中直接弹出增加选项卡,并填写相关参数,直接提交即可。
// https://www.cnblogs.com/lyshark
void mainwindow::on_pushbutton_insert_clicked()
{
qsqlquery query;
query.exec("select * from student where id =-1"); // 查询字段信息,是否存在
qsqlrecord currec=query.record(); // 获取当前记录,实际为空记录
currec.setvalue("id",qrymodel->rowcount()+1001);
dialog *windowptr=new dialog(this);
qt::windowflags flags=windowptr->windowflags();
windowptr->setwindowflags(flags | qt::mswindowsfixedsizedialoghint); // 设置对话框固定大小
windowptr->setinsertrecord(currec); // 插入记录
int ret=windowptr->exec(); // 以模态方式显示对话框
if (ret==qdialog::accepted) // ok键被按下
{
qsqlrecord recdata=windowptr->getrecorddata();
query.prepare("insert into student(id,name,sex,age,mobile,city)"
" values(:id, :name, :sex, :age, :mobile, :city)");
query.bindvalue(":id",recdata.value("id"));
query.bindvalue(":name",recdata.value("name"));
query.bindvalue(":sex",recdata.value("sex"));
query.bindvalue(":age",recdata.value("age"));
query.bindvalue(":mobile",recdata.value("mobile"));
query.bindvalue(":city",recdata.value("city"));
if (query.exec())
{
qstring sqlstr=qrymodel->query().executedquery(); // 执行过的select语句
qrymodel->setquery(sqlstr); // 重新查询数据
}
}
delete windowptr;
}
dialog增加效果如下: