This section is devoted to explaining the representation of data in a form view or a table view. But, before that we can see some examples of accessing databases through high-level model classes. The following classes are available in Qt for this purpose:
Let us view some quick examples of each of these classes.
This model aims at providing a high-level interface for executing SQL queries and traversing the result set. This class is built on top of the QSqlQuery
class and can be used to provide data to view classes, for example, QTableView
which we are going to discuss in the forthcoming sections. A sample program using QSqlQueryModel
is 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 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 editing of data which QSqlQueryModel
does not support. A sample program for your reference is as follows:
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 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 for editing values in the database. The various options that this function can take are given as follows:
It is to be noted 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()
method 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.