[Qt first entered the rivers and lakes] Qt QSqlTableModel underlying architecture and principle detailed description

Yuxian: CSDN content partner, CSDN new star mentor, full-stack creative star creator, 51CTO (Top celebrity + expert blogger), github open source enthusiast (go-zero source code secondary development, game back-end architecture https: https://github.com/Peakchen)

 

Qt QSqlTableModel is a model class used to implement database tables in Qt, which inherits from QAbstractTableModel. QSqlTableModel encapsulates operations such as query, modification, deletion, and insertion of database tables, and can be easily used with the QTableView control to display and edit database table data. In this article, we will introduce the underlying architecture, principles and implementation methods of Qt QSqlTableModel in detail.

The underlying architecture of Qt QSqlTableModel consists of the following parts:

  1. QSqlTableModelPrivate

QSqlTableModelPrivate is a private implementation class of QSqlTableModel, which encapsulates operations such as query, modification, deletion, and insertion of database tables, as well as caching and updating of data.

  1. QSqlRecord

QSqlRecord is a class used to encapsulate database table records in Qt. It encapsulates operations such as query, modification, and insertion of table records.

  1. QSqlField

QSqlField is a class used to encapsulate database table fields in Qt. It encapsulates operations such as query, modification, and insertion of table fields.

The following is the underlying architecture diagram of the QSqlTableModel class:

+-----------------+
|   QSqlTableModel|
+-----------------+
| - db            |
| - tableName     |
| - filter        |
| - sort          |
| - limit         |
| - offset        |
+-----------------+
          /_\
           |
           | 继承
           |
+-----------------+
|   QSqlQueryModel|
+-----------------+
| - query         |
+-----------------+
          /_\
           |
           | 实例化
           |
+-----------------+
|   QSqlTableModel|
+-----------------+

In this architecture, the QSqlTableModel class is an abstraction of a database table, which contains information such as database connection, table name, filter conditions, sorting methods, and data restrictions related to the table. The QSqlQueryModel class is the base class of the QSqlTableModel class, which implements the basic functions of using SQL query results in the Qt model/view framework. The QSqlTableModel class inherits the QSqlQueryModel class and adds some methods and signals for editing data. When the QSqlTableModel class is instantiated, a corresponding QSqlQuery object will be created to actually execute the SQL query statement.

In Qt, we can use the following methods to manipulate QSqlTableModel:

  1. QSqlTableModel::setTable()

The setTable() method is used to set the database table to be operated. For example:

QSqlTableModel model;
model.setTable("mytable");
  1. QSqlTableModel::select()

The select() method is used to get table data from the database and store it in the QSqlTableModel object. For example:

if (model.select()) {
    // 处理查询结果
} else {
    qWarning() << "Failed to select data:" << model.lastError().text();
}
  1. QSqlTableModel::setData()

The setData() method is used to set the data of the specified cell in the table. For example:

model.setData(model.index(row, column), value);
  1. QSqlTableModel::submitAll()

The submitAll() method is used to submit changes to the table data to the database. For example:

if (!model.submitAll()) {
    qWarning() << "Failed to submit changes:" << model.lastError().text();
}
  1. QSqlTableModel::removeRow()

The removeRow() method is used to delete the specified row from the table. For example:

model.removeRow(row);

The following is a simple Qt QSqlTableModel implementation example, which includes the use of the above methods:

#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QSqlError>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // 添加MySQL数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("mydatabase");
    db.setUserName("myusername");
    db.setPassword("mypassword");

    // 打开数据库连接
    if (db.open()) {
        qInfo() << "Database connection opened";

        // 创建QSqlTableModel对象
        QSqlTableModel model;
        model.setTable("mytable");

        // 从数据库中获取表格数据
        if (model.select()) {
            // 处理查询结果
            for (int row = 0; row < model.rowCount(); ++row) {
                for (int column = 0; column < model.columnCount(); ++column) {
                    QVariant value = model.data(model.index(row, column));
                    qInfo() << "Row:" << row << "Column:" << column << "Value:" << value;
                }
            }

            // 修改表格数据
            model.setData(model.index(0, 0), "New Value");

            // 提交修改到数据库
            if (!model.submitAll()) {
                qWarning() << "Failed to submit changes:" << model.lastError().text();
            }
        } else {
            qWarning() << "Failed to select data:" << model.lastError().text();
        }

        // 关闭数据库连接
        db.close();
        qInfo() << "Database connection closed";
    } else {
        qWarning() << "Failed to open database connection:" << db.lastError().text();
    }

    return app.exec();
}

In the above example, we first use the addDatabase() method to add a MySQL database connection and set the connection information. Then create a QSqlTableModel object, and use the setTable() method to set the database table to be operated. Then use the select() method to get the table data from the database, and use the data() method to get the table data. Then use the setData() method to modify the table data, and use the submitAll() method to submit the changes to the database. Finally, a row in the table data is deleted using the removeRow() method.

Qt QSqlTableModel provides a convenient way to implement model classes based on database tables, and can be easily used with the QTableView control. We only need to set the database table to be operated according to the above method, obtain table data from the database, and then use setData() and other methods to modify, delete, and insert data.

Guess you like

Origin blog.csdn.net/feng1790291543/article/details/131807588