SQL查询模型QSqlQueryModel 版权声明
导语 在上一篇的最后我们讲到,Qt中使用了自己的机制来避免使用SQL语句,为我们提供了更简单的数据库操作及数据显示模型,分别是只读的QSqlQueryModel,操作单表的QSqlTableModel和以及可以支持外键的QSqlRelationalTableModel。这次我们先讲解QSqlQueryModel。
环境:Windows Xp + Qt 4.8.4+Qt Creator2.6.2
目录 一、简单的查询操作 二、QSqlQueryModel常用操作 三、创建自定义QSqlQueryModel
正文
一、简单的查询操作
1.新建Qt Gui应用,项目名称为queryModel,基类为QMainWindow,类名为MainWindow。
2.完成后打开queryModel.pro,将第一行代码更改为: QT += core gui sql 然后保存该文件。
3.往项目中添加新的C++头文件,名称为connection.h,完成后将其内容更改如下: #ifndef CONNECTION_H #define CONNECTION_H #include <QSqlDatabase> #include <QSqlQuery> static bool createConnection() { QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("database.db"); if(!db.open()) return false; QSqlQuery query; query.exec("create table student (id int primary key, name vchar)"); query.exec("insert into student values (0,'yafei0')"); query.exec("insert into student values (1,'yafei1')"); query.exec("insert into student values (2,'yafei2')"); return true; } #endif // CONNECTION_H
这里使用了db.setDatabaseName("database.db");,我们没有再使用以前的内存数据库,而是使用了真实的文件,这样后面对数据库进行的操作就能保存下来了。
4.然后进入main.cpp文件,更改如下: #include "mainwindow.h"
#include <QApplication>
#include "connection.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if(!createConnection())
return 1;
MainWindow w;
w.show();
return a.exec();
}
5.下面进入设计模式,向界面上拖入一个Push Button按钮,更改显示文本为“查询”,然后进入其单击信号槽,更改如下:
void MainWindow::on_pushButton_clicked() { QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("select * from student"); model->setHeaderData(0, Qt::Horizontal, tr("id")); model->setHeaderData(1, Qt::Horizontal, tr("name")); QTableView *view = new QTableView; view->setModel(model); view->show(); } 这里新建了QSqlQueryModel类对象model,并用setQuery()函数执行了SQL语句“("select * fromstudent");”用来查询整个student表的内容,可以看到,该类并没有完全避免SQL语句。然后我们设置了表中属性显示时的名字。最后我们建立了一个视图view,并将这个model模型关联到视图中,这样数据库中的数据就能在窗口上的表中显示出来了。
6.在mainwindow.cpp中添加头文件包含: #include <QSqlQueryModel> #include <QTableView>
7.运行程序,按下查询按钮,效果如下图所示。
8.我们查看一下编译生成的目录(我这里是E:\queryModel-build-桌面-Debug),这里面有生成的数据库文件,如下图所示。
二、QSqlQueryModel常用操作
1.在查询按钮槽中继续添加如下代码: int column= model->columnCount(); //获得列数 int row = model->rowCount(); // 获得行数 QSqlRecord record = model->record(1); //获得一条记录 QModelIndex index = model->index(1,1); //获得一条记录的一个属性的值 qDebug() << "column numis:" << column << endl << "row num is:" << row << endl <<"the second record is:" << record << endl << "the data of index(1,1) is:"<< index.data();
2.然后在mainwindow.cpp文件中添加下面的头文件包含: #include <QSqlRecord> #include <QModelIndex> #include <QDebug>
3.运行程序,点击查询按钮,输出内容如下图所示。
4.另外我们可以直接使用上一节讲到的QSqlQuery来执行SQL语句,例如: QSqlQuery query = model->query(); query.exec("select name from studentwhere id = 2 "); query.next(); qDebug() << query.value(0).toString();
5.我们将查询按钮槽更改如下: void MainWindow::on_pushButton_clicked() { QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("select * from student"); model->setHeaderData(0, Qt::Horizontal, tr("id")); model->setHeaderData(1, Qt::Horizontal, tr("name")); QTableView *view = new QTableView; view->setModel(model); view->show(); QSqlQuery query = model->query(); query.exec("insertinto student values (10,'yafei10')"); } 这里使用query向表中添加了一条记录。
6.在mainwindow.cpp中添加头文件#include <QSqlQuery>,然后运行程序,发现最后添加的记录并没有显示出来,当关闭程序,再次运行的时候才显示出来,效果如下图所示。
7.为什么会出现上面的情况呢?那是因为前面我们执行了添加记录的SQL语句,但是在添加记录之前,查询结果就已经显示了,所以我们的更新没能动态的显示出来。为了能让其动态地显示我们的更新,可以将槽最后的代码更改如下: QSqlQuery query = model->query(); query.exec("insert into student values (20,'yafei20')"); model->setQuery("select * from student"); //再次查询整张表 view->show(); //再次进行显示 这里我们修改完表以后,再次进行了查询并显示。大家可以运行程序,发现新的记录可以直接显示出来了。
三、创建自定义QSqlQueryModel
前面我们讲到这个模型默认是只读的,所以在窗口上并不能对表格中的内容进行修改。但是我们可以创建自己的模型,然后按照自己的意愿来显示数据和修改数据。要想使其可读写,需要自己的类继承自QSqlQueryModel,并且重写setData() 和 flags() 两个函数。如果我们要改变数据的显示,就要重写data() 函数。 下面的例子中我们让student表查询结果的id属性列显示红色,name属性列可编辑。
1.向项目中添加新的C++类,类名为MySqlQueryModel,基类为QSqlQueryModel,类型信息选择“继承自QObject”。
2.完成后打开mysqlquerymodel.h文件,在public中添加函数声明: Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); QVariant data(const QModelIndex &item, int role=Qt::DisplayRole) const;
然后添加私有函数声明: private: bool setName(int studentId, const QString &name); void refresh();
3.到mysqlquerymodel.cpp文件中,更改如下: #include "mysqlquerymodel.h" #include <QSqlQuery> #include <QColor> MySqlQueryModel::MySqlQueryModel(QObject *parent) : QSqlQueryModel(parent) { }
Qt::ItemFlags MySqlQueryModel::flags( const QModelIndex &index) const //返回表格是否可更改的标志 { Qt::ItemFlags flags = QSqlQueryModel::flags(index); if (index.column() == 1) //第二个属性可更改 flags |= Qt::ItemIsEditable; return flags; }
bool MySqlQueryModel::setData(const QModelIndex &index, const QVariant &value, int /* role */) //添加数据 { if (index.column() < 1 || index.column() > 2) return false; QModelIndex primaryKeyIndex = QSqlQueryModel::index(index.row(), 0); int id = data(primaryKeyIndex).toInt(); //获取id号 clear(); bool ok; if (index.column() == 1) //第二个属性可更改 ok = setName(id, value.toString()); refresh(); return ok; }
void MySqlQueryModel::refresh() //更新显示 { setQuery("select * from student"); setHeaderData(0, Qt::Horizontal, QObject::tr("id")); setHeaderData(1, Qt::Horizontal, QObject::tr("name")); }
//添加name属性的值 bool MySqlQueryModel::setName(int studentId, const QString &name) { QSqlQuery query; query.prepare("update student set name = ? where id = ?"); query.addBindValue(name); query.addBindValue(studentId); return query.exec(); }
//更改数据显示样式 QVariant MySqlQueryModel::data(const QModelIndex &index, int role) const { QVariant value = QSqlQueryModel::data(index, role);
//第一个属性的字体颜色为红色 if (role == Qt::TextColorRole && index.column() == 0) return qVariantFromValue(QColor(Qt::red)); return value; }
4.到mainwindow.cpp文件中先添加头文件包含: #include "mysqlquerymodel.h"
5.更改查询按钮槽内容如下: void MainWindow::on_pushButton_clicked() { QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("select * from student"); model->setHeaderData(0, Qt::Horizontal, tr("id")); model->setHeaderData(1, Qt::Horizontal, tr("name")); QTableView *view = new QTableView; view->setModel(model); view->show(); //创建自己模型的对象 MySqlQueryModel *myModel = new MySqlQueryModel; myModel->setQuery("select * from student"); myModel->setHeaderData(0, Qt::Horizontal, tr("id")); myModel->setHeaderData(1, Qt::Horizontal, tr("name")); QTableView *view1 = new QTableView; view1->setWindowTitle("mySqlQueryModel"); //修改窗口标题 view1->setModel(myModel); view1->show(); }
运行程序,效果如下图所示。
结语 本节讲解了QSqlQueryModel的相关内容,该类默认是一个只读的SQL语句查询模型,不过可以对其进行重写来实现编辑功能。下一节我们将讲解封装更好的QSqlTableModel模型,它已经基本上摆脱了SQL语句。
涉及到的源码:
上一篇:第23篇 数据库(三)利用QSqlQuery类执行SQL语句
下一篇: 第25篇 数据库(五)SQL表格模型QSqlTableModel
返回:系列教程目录
|