QSqlTableModel Class

Detailed Description

QSqlTableModel is a high-level interface for reading and writing database records from a single table. It is built on top of the lower-level QSqlQuery and can be used to provide data to view classes such as QTableView. For example:

 
Sélectionnez
    QSqlTableModel *model = new QSqlTableModel;
    model->setTable("employee");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model->setHeaderData(0, Qt::Horizontal, tr("Name"));
    model->setHeaderData(1, Qt::Horizontal, tr("Salary"));

    QTableView *view = new QTableView;
    view->setModel(model);
    view->hideColumn(0); // don't show the ID
    view->show();

We set the SQL table's name and the edit strategy, then we set up the labels displayed in the view header. The edit strategy dictates when the changes done by the user in the view are actually applied to the database. The possible values are OnFieldChange, OnRowChange, and OnManualSubmit.

QSqlTableModel can also be used to access a database programmatically, without binding it to a view:

 
Sélectionnez
    QSqlTableModel model;
    model.setTable("employee");
    model.select();
    int salary = model.record(4).value("salary").toInt();

The code snippet above extracts the salary field from record 4 in the result set of the query SELECT * from employee.

It is possible to set filters using setFilter(), or modify the sort order using setSort(). At the end, you must call select() to populate the model with data.

The tablemodel example illustrates how to use QSqlTableModel as the data source for a QTableView.

QSqlTableModel provides no direct support for foreign keys. Use the QSqlRelationalTableModel and QSqlRelationalDelegate if