[Qt first entered the rivers and lakes] Qt QSqlRelationalTableModel 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 QSqlRelationalTableModel is a model class used to implement associated tables in Qt, which inherits from QSqlTableModel. QSqlRelationalTableModel encapsulates operations such as querying, modifying, deleting, and inserting database associated tables, and can be easily used with the QTableView control to display and edit associated table data. In this article, we will introduce the underlying architecture, principles and implementation methods of Qt QSqlRelationalTableModel in detail.

The underlying architecture of Qt QSqlRelationalTableModel is similar to that of Qt QSqlTableModel, except that it also encapsulates queries and operations on associated tables. Qt QSqlRelationalTableModel describes the relationship between database tables through the QSqlRelation class. QSqlRelation encapsulates the foreign key relationship, which describes the relationship between two tables, and specifies the name of the foreign key and the name of the associated table.

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

+-----------------------------+
|   QSqlRelationalTableModel  |
+-----------------------------+
| - db                        |
| - tableName                 |
| - filter                    |
| - sort                      |
| - limit                     |
| - offset                    |
| - relations                 |
| - relationModelCacheEnabled |
+-----------------------------+
          /_\
           |
           | 继承
           |
+-----------------------------+
|   QSqlTableModel            |
+-----------------------------+
| - relation                 |
| - relationColumn           |
+-----------------------------+
          /_\
           |
           | 实例化
           |
+-----------------------------+
|   QSqlRelationalTableModel  |
+-----------------------------+

In this architecture, the QSqlRelationalTableModel class is an abstraction of a database table containing foreign key relationships, which contains information such as database connections, table names, filter conditions, sorting methods, data restrictions, and foreign key relationships related to the table. The QSqlTableModel class is the base class of the QSqlRelationalTableModel class, which implements the basic functions of using database tables in the Qt model/view framework. The QSqlRelationalTableModel class inherits the QSqlTableModel class and adds some methods and signals for editing data containing foreign key relationships.

In the QSqlRelationalTableModel class, foreign key relationships are represented by QSqlRelation objects. A QSqlRelation object contains a foreign key column name, a reference table name, and a reference table column name. The purpose of a QSqlRelation object is to convert the data type of a column from a simple value to a value in a reference table.

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

  1. QSqlRelationalTableModel::setTable()

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

QSqlRelationalTableModel model;
model.setTable("mytable");
  1. QSqlRelationalTableModel::setRelation()

The setRelation() method is used to set the foreign key relationship of the table. For example:

model.setRelation(column, QSqlRelation("othertable", "id", "name"));
  1. QSqlRelationalTableModel::select()

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

if (model.select()) {
    // 处理查询结果
} else {
    qWarning() << "Failed to select data:" << model.lastError().text();
}
  1. QSqlRelationalTableModel::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. QSqlRelationalTableModel::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. QSqlRelationalTableModel::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 QSqlRelationalTableModel implementation example, which includes the use of the above methods:

#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlRelationalTableModel>
#include <QSqlRelation>
#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";

        // 创建QSqlRelationalTableModel对象
        QSqlRelationalTableModel model;
        model.setTable("mytable");
        model.setRelation(1, QSqlRelation("othertable", "id", "name"));

        // 从数据库中获取表格数据
        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 QSqlRelationalTableModel object, and use the setTable() method to set the database table to be operated, and use the setRelation() method to set the foreign key relationship of the table. 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 QSqlRelationalTableModel provides a convenient way to implement model classes with associated tables, and can be easily used with the QTableView control. We only need to set the database table and foreign key relationship 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/131807684