[Qt Tutorial] The first 24 database (four) SQL query model QSqlQueryModel

Lead
in the end we talked about one of, Qt use its own mechanisms to avoid the use of SQL statements, provides a simpler database operations and data model for us, which are read-only QSqlQueryModel, QSqlTableModel single operating table and can support QSqlRelationalTableModel and foreign keys. This time we first explain QSqlQueryModel.

Environment: Windows Xp + Qt 4.8.4 + Qt Creator2.6.2

Catalog
a simple query
two, QSqlQueryModel common operations
Third, create a custom QSqlQueryModel

text

First, the simple query operation

1. Create a new Qt Gui Application project named queryModel, base class for QMainWindow, class named MainWindow.

2. After opening queryModel.pro, change the first line code:
QT + = Core GUI SQL
then save the file.

3. Add a new C ++ header files to your project, named connection.h, after completion of its contents change as follows:
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QSqlDatabase>
#include <QSqlQuery>
static BOOL createConnection ()
{
QSqlDatabase db addDatabase QSqlDatabase :: = ( "QSQLITE");
db.setDatabaseName ( "database.db");
IF (! db.Open ()) return to false;
The QSqlQuery Query;
query.exec ( "Create Table Student (ID int Primary Key , namevchar) ");
query.exec (" INSERT INTO Student values (0, 'yafei0') ");
query.exec (" INSERT INTO Student values (. 1, 'yafei1') ");
query.exec (" INSERT Student values INTO (2, 'yafei2') ");
return to true;
}
#endif // CONNECTION_H

This uses db.setDatabaseName ( "database.db") ;, we no longer use the previous memory database, but the use of the real file so that the rear face of the operation of the database can be saved.

4. main.cpp then enters the file, change as follows:
#include "mainwindow.h"
#include <the 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();
}

The following into the design mode, the interface to drag a Push Button button, to change the display text "Query", and then click signal into its groove, change as follows:
void :: on_pushButton_clicked the MainWindow ()
{
QSqlQueryModel Model = new new QSqlQueryModel;
Model-> setQuery ( "SELECT
from Student");
Model-> setHeaderData (0, the Qt :: Horizontal, TR ( "ID"));
Model-> setHeaderData (. 1, the Qt :: Horizontal, TR ( "name") );
QTableView, View QTableView, new new =;
View-> setModel to (Model);
View-> Show ();
}
where QSqlQueryModel a new class object model, and washed with setQuery () function executes SQL statement "(" SELECT
fromstudent ");" to query the contents of the entire student table, you can see, the class did not completely avoid SQL statements. Then we set the table when the name attribute display. Finally, we created a view of view, this model and the associated model to view this data in the database can be displayed on a table in the window.

6. Add mainwindow.cpp header file comprising:
#include <QSqlQueryModel>
#include <QTableView,>

7. Run the program by pressing the search button, results as shown in FIG.
24-1.jpg

8. We look at the catalog compiled of (I am here is E: \ queryModel-build- Desktop -Debug), and there are generated database file, as shown below.
24-2.jpg

Two, QSqlQueryModel common operations

1. Query button continue to add in the following code tank:
int column = Model-> the columnCount (); // get the number of columns
int row = model-> rowCount () ; // get the row
QSqlRecord record = model-> record ( 1); // get a record
QModelIndex index = model-> index (1,1 ); // get a record of an attribute value
qDebug () << "Numis column:" << endl << column
<< " NUM IS Row: "Row << endl <<
<<" The IS SECOND Record: "Record << << endl
<<" The Data index of (1,1) IS: "<< index.data ();

2. Then add the following in the file header contains mainwindow.cpp:
#include <QSqlRecord>
#include <QModelIndex>
#include <QDebug>

3. Run the program, click on the search button, the output content as shown below.
24-3.jpg

4. In addition, we can directly use the one mentioned QSqlQuery to execute SQL statements, for example:
QSqlQuery Query = Model-> Query ();
query.exec ( "SELECT name from studentwhere ID = 2");
query.next ( );
qDebug () << Query.value (0) .toString ();

5. We will change as the search button slot:
void :: on_pushButton_clicked the MainWindow ()
{
QSqlQueryModel Model = new new QSqlQueryModel;
Model-> setQuery ( "SELECT
from Student");
Model-> setHeaderData (0, the Qt :: Horizontal, TR ( "ID"));
Model-> setHeaderData (. 1, the Qt :: Horizontal, TR ( "name"));
QTableView, new new QTableView, = * View;
View-> setModel to (Model);
View-> Show ();

QSqlQuery query = model->query();
query.exec("insertinto student values (10,'yafei10')");

}
Add a record to the table used herein query.

6. Add header #include <QSqlQuery> in mainwindow.cpp then run the program, and found that the last added record is not displayed, when the closing program, when run again show up, results as shown below.
24-4.jpg

7. Why does the above situation it? That's because we performed in front of an SQL statement to add records, but before adding records, query results already show, so we did not update dynamically displayed. In order to allow dynamic display of our update, final code may be changed as follows slots:
The QSqlQuery Query = Model-> Query ();
query.exec ( "INSERT INTO Student values (20 is, 'yafei20')");
Model -> setQuery ( "select * from student"); // query the entire table again
view-> show (); // display again
here after we finished modifying the table, query and display again. We can run the program, we discover new record can be displayed directly out.

Third, create a custom QSqlQueryModel

   前面我们讲到这个模型默认是只读的,所以在窗口上并不能对表格中的内容进行修改。但是我们可以创建自己的模型,然后按照自己的意愿来显示数据和修改数据。要想使其可读写,需要自己的类继承自QSqlQueryModel,并且重写setData() 和 flags() 两个函数。如果我们要改变数据的显示,就要重写data() 函数。
   下面的例子中我们让student表查询结果的id属性列显示红色,name属性列可编辑。

1. Add to the project in the new C ++ classes, class named MySqlQueryModel, the base class is QSqlQueryModel, select the type of information "inherited from QObject".

2. After completion of the Open mysqlquerymodel.h file, add the function declarations in public are:
the Qt :: ItemFlags the flags (const QModelIndex & index) const;
BOOL the setData (const QModelIndex & index, const the QVariant & value, int Role);
the QVariant Data (const QModelIndex & Item , int role = Qt :: DisplayRole) const;

Then add the function declaration Private:
Private:
BOOL setName (int studentId, const QString & name);
void Refresh ();

3. mysqlquerymodel.cpp file to change as follows:
#include "mysqlquerymodel.h"
#include <The QSqlQuery>
#include <a QColor>
MySqlQueryModel :: MySqlQueryModel (QObject * parent):
QSqlQueryModel (parent)
{
}

:: :: ItemFlags MySqlQueryModel the flags qt (
const & QModelIndex index) const Returns // Flexible table flag
{
qt = QSqlQueryModel :: :: ItemFlags the flags the flags (index);
IF (index.column () ==. 1) / / second attribute can change
the flags | :: = the Qt ItemIsEditable;
return the flags;
}

:: MySqlQueryModel the setData BOOL (const & QModelIndex index, the QVariant & const value, int / Role /)
// add data
{
IF (index.column () <|| index.column. 1 ()> 2)
return to false;
QModelIndex primaryKeyIndex = QSqlQueryModel index :: (index.row (), 0);
int id = Data (primaryKeyIndex) .toInt (); // Get the id
Clear ();
BOOL OK;
IF (index.column () ==. 1) // Flexible second attribute
OK = the 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();
}

// change the display style data
the QVariant MySqlQueryModel :: Data (const & QModelIndex index, int Role) const
{
the QVariant QSqlQueryModel :: Data value = (index, Role);

// first font color attribute to red
IF (Role == :: TextColorRole the Qt index.column && () == 0)
return qVariantFromValue (a QColor (the Qt :: Red));
return value;
}

4. mainwindow.cpp to add a file to the file header comprises:
#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();

// create your own model objects
MySqlQueryModel myModel = new new MySqlQueryModel; mymodel-> setQuery ( "the SELECT from Student");
mymodel-> setHeaderData (0, Qt :: Horizontal, TR ( "the above mentioned id"));
mymodel-> setHeaderData ( 1, Qt :: Horizontal, TR ( "name"));
QTableView * = View1 new new QTableView;
view1-> setWindowTitle ( "mySqlQueryModel"); // modify the window title
view1-> setModel (myModel);
view1-> Show ( );
}

Running the program, results as shown below.
24-5.jpg

Conclusion
This section explains the content QSqlQueryModel, the default class is a read-only SQL statement to query the model, but can be rewritten to achieve editing functions. The next section we will explain better QSqlTableModel model package, it has been largely out of the SQL statement.

Guess you like

Origin blog.51cto.com/14527980/2437469