This section is devoted to explaining the representation of data in a form view or a table view. But, before that, we can look at some examples of accessing databases through high-level model classes. The following classes are available in Qt for this purpose.
Let's view some quick examples of each of these classes.
This model aims at providing a high-level interface to execute SQL queries and traverse the result set. This class is built on top of the QSqlQuery
class and can be used to provide data to view classes, such as QTableView
, which we are going to discuss in the forthcoming sections. A sample program using QSqlQueryModel
is given as follows:
model = QSqlQueryModel() model.setQuery("SELECT fname FROM employee") print("Names of Employee") while i < model.rowcount() : print(model.record(i).value( "fname").toString())
In the example shown, we set the the query using the model.setQuery()
function. Once the query is set, the QSqlQueryModel.record(int)
method is used to get individual records.
The PySide.QtSql.QSqlTableModel
class provides an editable data model for a single database table. As with QSqlQueryModel
, this class also provides a high-level interface and can be used to provide data to view class. The only difference is that it allows the editing of data, which QSqlQueryModel
does not support. A sample program is given as follows for your reference:
model = QSqlTableModel() model.setTable("employee") model.setFilter("age > 40") model.setEditStrategy(QSqlTableModel.OnManualSubmit) model.select() model.removeColumn(0) # to remove the id column while i < model.rowcount() : print(model.record(i))
This works in the same way as explained in our previous example. The main difference to note here is Line 4. The QSqlTableModel.setEditStarategy()
function describes which strategy we prefer to use to edit values in the database. The various options that this function can take are given as follows:
Constant |
Description |
---|---|
|
This means that the changes to a model will be applied immediately to the database |
|
This means that the changes on a row will be applied when the user selects a different row |
|
All changes will be cached in the model until either |
Please note that to prevent inserting partial values on a row into the database, onFieldChange will behave like onRowChange for newly inserted rows. The QSqlTableModel.setFilter()
function executes the functionality of a WHERE
clause in SQL queries. If the model is already selected and populated, the setFilter()
will refilter the results. The QSqlTableModel.setRecord()
function is used to modify a row, QSqlTabelModel.removeRows(int)
is used to delete rows from the table.