Cached Table Example▲

The example consists of a single class, TableEditor, which is a custom dialog widget that allows the user to modify data stored in a database. We will first review the class definiton and how to use the class, then we will take a look at the implementation.
TableEditor Class Definition▲
The TableEditor class inherits QDialog making the table editor widget a top-level dialog window.
class
TableEditor : public
QWidget
{
Q_OBJECT
public
:
explicit
TableEditor(const
QString &
amp;tableName, QWidget *
parent =
nullptr
);
private
slots:
void
submit();
private
:
QPushButton *
submitButton;
QPushButton *
revertButton;
QPushButton *
quitButton;
QDialogButtonBox *
buttonBox;
QSqlTableModel *
model;
}
;
The TableEditor constructor takes two arguments: The first is a pointer to the parent widget and is passed on to the base class constructor. The other is a reference to the database table the TableEditor object will operate on.
Note the QSqlTableModel variable declaration: As we will see in this example, the QSqlTableModel class can be used to provide data to view classes such as QTableView. The QSqlTableModel class provides an editable data model making it possible to read and write database records from a single table. It is build on top of the lower-level QSqlQuery class which provides means of executing and manipulating SQL statements.
We are also going to show how a table view can be used to cache any changes to the data until the user explicitly requests to submit them. For that reason we need to declare a submit() slot in additon to the model and the editor's buttons.
Connecting to a Database |
---|
Before we can use the TableEditor class, we must create a connection to the database containing the table we want to edit: Sélectionnez
The createConnection() function is a helper function provided for convenience. It is defined in the connection.h file which is located in the sql example directory (all the examples in the sql directory use this function to connect to a database). Sélectionnez
|