[Qt Tutorial] database (five) SQL table model QSqlTableModel

Lead
on a read-only QsqlQueryModel model we talked about actually editing functions can also be achieved, but it is cumbersome to implement. The QSqlTableModel provides a read-write model can only operate a single SQL table, it is a higher level of QSqlQuery alternatives may view and change individual SQL tables, and write less code, and do not need to know SQL syntax.

Environment: Windows Xp + Qt 4.8.4 + QtCreator 2.6.2

Contents
First, create a database
Second, modify the operation of
three or query operation
four sorting operation
five or delete
six or insert operation

text

First, create a database

1. Create a new Qt Gui Application project named tableModel, the base class QMainWindow, class name MainWindow.

2. After tableModel.pro open file, change the first line code:
QT + = coregui SQL
then save the file.

3. Add a new C ++ header files to your project, named connection.h. After completion of the contents changed as follows:
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QSqlDatabase>
#include <The QSqlQuery>
static BOOL the createConnection ()
{
QSqlDatabase DB = QSqlDatabase :: addDatabase ( "QSQLITE");
db.setDatabaseName ( "Database. db ");
IF (db.Open (!)) return false;
QSqlQuery Query;
query.exec (QString (
" the Create tablestudent (the above mentioned id int Primary Key, name vchar) "));
query.exec (QString (" INSERT INTO student values (0, 'Liu') "));
query.exec (QString (" INSERT INTO Student values (. 1, 'Gang') "));
query.exec (QString (" INSERT INTO Student values (2, 'WANG') "));
return to true;


This statement because the use of Chinese, so use the QString () transcoding, encoding the need to set up the main () function.

4.下面将main.cpp文件更改如下:
#include "mainwindow.h"
#include <QApplication>
#include "connection.h"
#include <QTextCodec>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
if(!createConnection())
return 1;
MainWindow w;
w.show();

return a.exec();

}
SetCodecForCStrings where () is used to set the string encoding.

The following into the design pattern, the drag Label window, Push Button, Line Edit Table View and other components, interface design, results as shown below.
25-1.jpg

6. After the mainwindow.H w member, the first header comprising:
#include <QSqlTableModel>
then add private object declaration:
QSqlTableModel * Model;

7. to mainwindow.cpp, add the following code in the constructor:
Model QSqlTableModel new new = (the this);
Model-> setTable ( "Student");
Model-> setEditStrategy (QSqlTableModel :: OnManualSubmit);
Model-> SELECT (); // select entire table all rows
// column name attribute is not displayed, if the recording time is added, the added value of the property is not a
// Model-> removeColumn (. 1);
ui-> tableView-> setModel to (Model) ;
// it can not be edited
// ui-> tableView-> setEditTriggers (QAbstractItemView :: NoEditTriggers);

Here After creating a QSqlTableModel, just use setTable () to assign a database table, and then use the select () function to query, calling these two functions is equivalent to the implementation of the "select * from student" SQL statement. Here you can also use setFilter () to specify the conditions of a query, in the back will see the use of this function. Before using this model, which generally also edit the policy settings, it is defined by the enumeration QSqlTableModel :: EditStrategy, a total of three values, as shown in FIG. When the values for explaining the database is edited, modifications submitted under what circumstances.
25-2.jpg

Running the program, results as shown below.
25-3.jpg

  可以看到,这个模型已经完全脱离了SQL语句,我们只需要执行select()函数就能查询整张表。上面有两行代码被注释掉了,你可以取消注释,测试一下它们的作用。

Second, modify operation

1. We enter the "submit Edit" button click signal slot, changes are as follows:
void MainWindow :: on_pushButton_3_clicked ()
{
Model-> Database () Transaction (); // start operation transaction.
IF (Model-> submitAll () ) {
Model-> Database () the commit ();. // submit
} the else {
Model-> Database () rOLLBACK ();. // rollback
a QMessageBox :: warning (the this, TR ( "tableModel"),
TR ( "database error:% 1")
. .arg (Model-> lastError () text ()));
}
}
this uses transactional operations, that really commit operation is model-> submitAll () one, it submits all changes .

2. Click the signal enters the slot "undo changes" button, changes are as follows:
void :: on_pushButton_4_clicked the MainWindow ()
{
Model-> revertAll ();
}

3. mainwindow.cpp contained in the file header:
#include <a QMessageBox>
#include <QSqlError>

4. Now run the program, we will, "Chen Gang" to "Li Qiang," If we click "undo changes", it will re-read "Chen Gang," and when we click on "Submit modify" it will be saved to database, then click "undo changes" on the amendment does not come back.
Can see, this model can save all the changes to the model, only when we commit modifications, will really written to the database. Of course, this is because we set at the beginning of its preservation strategy:
Model-> setEditStrategy (QSqlTableModel :: OnManualSubmit);
OnManualSubmit here shows that we want to commit a change to take effect.

Third, the query operation

1. Go to the "Search" button, click the signal slot, changes are as follows:
void MainWindow :: on_pushButton_clicked ()
{
QString name = ui-> lineEdit-> text ();
// screened by name
model-> setFilter (QString ( "name = '%. 1'") Arg (name));.
// display results
Model-> SELECT ();
}
using the setFilter () function to filter the keyword, this function is performed for the entire query result set.

2. Go to "full table display" button click signal slots, change as follows:
void :: on_pushButton_2_clicked the MainWindow ()
{
Model-> setTable ( "Student"); // table reassociation
model-> select (); // again so as to display the contents of the entire table
}
in order to display the contents of the entire table again, we need to link the table again.

3. After running the program below, enter a name, click on the "Search" button, you can display the records. Then click on "Display full table" button is returned. As shown below.
25-4.jpg

Fourth, the sorting operation

Respectively, into the "id Sort Ascending" and "Sort Descending id" button click signal slots, the following changes:
// ascending
void the MainWindow :: on_pushButton_7_clicked ()
{
Model-> setSort (0, the Qt :: ascendingOrder); / / id attribute i.e. 0-th column, in ascending order
Model-> SELECT ();
}
// descending
void the MainWindow :: on_pushButton_8_clicked ()
{
Model-> setSort (0, the Qt :: DescendingOrder);
Model-> SELECT ();
}
this uses setSort () function to sort, it has two parameters, the first parameter represents the first of several sort attribute header from left to right, the far left is the 0th property, this is the id attribute. The second parameter is a sorting method, there are two kinds of ascending and descending. Running the program, results as shown below.
25-5.jpg

Fifth, delete

We enter "Delete selected row" button click signal slot, changes are as follows:
void MainWindow :: on_pushButton_6_clicked ()
{
// get the selected row
int curRow = ui-> tableView-> currentIndex () row ();.

//删除该行
model->removeRow(curRow);

int ok = QMessageBox::warning(this,tr("删除当前行!"),tr("你确定"
                                             "删除当前行吗?"),
                              QMessageBox::Yes,QMessageBox::No);
if(ok == QMessageBox::No)
{
   model->revertAll(); //如果不删除,则撤销
}
else model->submitAll(); //否则提交,在数据库中删除该行  

}

Will delete rows stored in the first model, when we performed submitAll () after the function will actually delete the row in the database. Here we use an alert box to let the user choose whether to really want to delete the row. Running the program, results as shown below.
25-6.jpg

We click on the second row, and then click the "Delete selected row" button, a warning box. Then you will find, in front of the second row of the table there was a small exclamation mark, indicating that the line has been modified, but no real changes in the database, when the data have a school called dirty data (Dirty Data ). When we push button "Yes" button data in the database will be deleted, if you press "No", then the change will be canceled.

Sixth, insert

   我们进入“添加记录”按钮的单击信号槽,更改如下:

:: on_pushButton_5_clicked the MainWindow void ()
{
int = rowNum Model-> the rowCount (); // get the number of rows in the table
int ID = 10;
Model-> the insertRow (rowNum); // Add a line
model-> setData (model-> index (rowNum, 0), id);
// Model-> submitAll (); // can be directly submitted
}
in the last row of the table is added, as in the table, we set the student id number is the primary key, so there must be setData () function to add a new line to add the value of the id attribute, or add rows will not be successful. Here you can directly call submitAll () function to submit, you can also use the "submit Modify" button to submit. Running the program, results as shown below.
25-7.jpg

After pressing the "Add record" button, add a line, but there is an asterisk in front of the line, if we press the "submit Modify" button, the asterisk will disappear. Of course, if we will submit comments about the above code function removed, there would be the star number.

Conclusion
can see that this model is very powerful, and completely out of the SQL statement, even if you do not know much knowledge database, you can also use it for most common operations. We have seen, this model provides a buffer, you can modify saved first, when we commit function, go to actually modify the database. Of course, this model is more advanced than the previous model, speaking in front of all operations can be executed here.

Guess you like

Origin blog.51cto.com/14527980/2437473