Viadeo Twitter Google Bookmarks ! Facebook Digg MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Cached Table Example


The Cached Table example shows how a table view can be used to access a database, caching any changes to the data until the user explicitly submits them using a push button.

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 QDialog

     TableEditor(const QString &tableName, QWidget *parent = 0);

 private slots:
     void submit();

     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:
 int main(int argc, char *argv[])
     QApplication app(argc, argv);
     if (!createConnection())
         return 1;

     TableEditor editor("person");;
     return editor.exec();

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).

 static bool createConnection()
     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
     if (! {
         QMessageBox::critical(0, qApp->tr("Cannot open database"),
             qApp->tr("Unable to establish a database connection.\n"
                      "This example needs SQLite support. Please read "
                      "the Qt SQL driver documentation for information how "
                      "to build it.\n\n"
                      "Click Cancel to exit."), QMessageBox::Cancel);
         return false;

     QSqlQuery query;
     query.exec("create table person (id int primary key, "
                "firstname varchar(20), lastname varchar(20))");
     query.exec("insert into person values(101, 'Danny', 'Young')");
     query.exec("insert into person values(102, 'Christine', 'Holand')");
     query.exec("insert into person values(103, 'Lars', 'Gordon')");
     query.exec("insert into person values(104, 'Roberto', 'Robitaille')");
     query.exec("insert into person values(105, 'Maria', 'Papadopoulos')");

     query.exec("create table offices (id int primary key,"
                                              "imagefile int,"
                                              "location varchar(20),"
                                              "country varchar(20),"
                                              "description varchar(100))");
     query.exec("insert into offices "
                "values(0, 0, 'Oslo', 'Norway',"
                "'Oslo is home to more than 500 000 citizens and has a "
                "lot to offer.It has been called \"The city with the big "
                "heart\" and this is a nickname we are happy to live up to.')");
     query.exec("insert into offices "
                "values(1, 1, 'Brisbane', 'Australia',"
                "'Brisbane is the capital of Queensland, the Sunshine State, "
                "where it is beautiful one day, perfect the next.  "
                "Brisbane is Australia''s 3rd largest city, being home "
                "to almost 2 million people.')");
     query.exec("insert into offices "
                "values(2, 2, 'Redwood City', 'US',"
                "'You find Redwood City in the heart of the Bay Area "
                "just north of Silicon Valley. The largest nearby city is "
                "San Jose which is the third largest city in California "
                "and the 10th largest in the US.')");
     query.exec("insert into offices "
                "values(3, 3, 'Berlin', 'Germany',"
                "'Berlin, the capital of Germany is dynamic, cosmopolitan "
                "and creative, allowing for every kind of lifestyle. "
                "East meets West in the metropolis at the heart of a "
                "changing Europe.')");
     query.exec("insert into offices "
                "values(4, 4, 'Munich', 'Germany',"
                "'Several technology companies are represented in Munich, "
                "and the city is often called the \"Bavarian Silicon Valley\". "
                "The exciting city is also filled with culture, "
                "art and music. ')");
     query.exec("insert into offices "
                "values(5, 5, 'Beijing', 'China',"
                "'Beijing as a capital city has more than 3000 years of "
                "history. Today the city counts 12 million citizens, and "
                "is the political, economic and cultural centre of China.')");

     query.exec("create table images (locationid int, file varchar(20))");
     query.exec("insert into images values(0, 'images/oslo.png')");
     query.exec("insert into images values(1, 'images/brisbane.png')");
     query.exec("insert into images values(2, 'images/redwood.png')");
     query.exec("insert into images values(3, 'images/berlin.png')");
     query.exec("insert into images values(4, 'images/munich.png')");
     query.exec("insert into images values(5, 'images/beijing.png')");

     return true;

The createConnection function opens a connection to an in-memory SQLITE database and creates a test table. If you want to use another database, simply modify this function's code.

TableEditor Class Implementation

The class implementation consists of only two functions, the constructor and the submit() slot. In the constructor we create and customize the data model and the various window elements:

 TableEditor::TableEditor(const QString &tableName, QWidget *parent)
     : QDialog(parent)
     model = new QSqlTableModel(this);

     model->setHeaderData(0, Qt::Horizontal, tr("ID"));
     model->setHeaderData(1, Qt::Horizontal, tr("First name"));
     model->setHeaderData(2, Qt::Horizontal, tr("Last name"));

First we create the data model and set the SQL database table we want the model to operate on. Note that the QSqlTableModel::setTable() function does not select data from the table; it only fetches its field information. For that reason we call the QSqlTableModel::select() function later on, populating the model with data from the table. The selection can be customized by specifying filters and sort conditions (see the QSqlTableModel class documentation for more details).

We also set the model's edit strategy. The edit strategy dictates when the changes done by the user in the view, are actually applied to the database. Since we want to cache the changes in the table view (i.e. in the model) until the user explicitly submits them, we choose the QSqlTableModel::OnManualSubmit strategy. The alternatives are QSqlTableModel::OnFieldChange and QSqlTableModel::OnRowChange.

Finally, we set up the labels displayed in the view header using the setHeaderData() function that the model inherits from the QSqlQueryModel class.

     QTableView *view = new QTableView;

Then we create a table view. The QTableView class provides a default model/view implementation of a table view, i.e. it implements a table view that displays items from a model. It also allows the user to edit the items, storing the changes in the model. To create a read only view, set the proper flag using the editTriggers property the view inherits from the QAbstractItemView class.

To make the view present our data, we pass our model to the view using the setModel() function.

     submitButton = new QPushButton(tr("Submit"));
     revertButton = new QPushButton(tr("&Revert"));
     quitButton = new QPushButton(tr("Quit"));

     buttonBox = new QDialogButtonBox(Qt::Vertical);
     buttonBox->addButton(submitButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(revertButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

The TableEditor's buttons are regular QPushButton objects. We add them to a button box to ensure that the buttons are presented in a layout that is appropriate to the current widget style. The rationale for this is that dialogs and message boxes typically present buttons in a layout that conforms to the interface guidelines for that platform. Invariably, different platforms have different layouts for their dialogs. QDialogButtonBox allows a developer to add buttons to it and will automatically use the appropriate layout for the user's desktop environment.

Most buttons for a dialog follow certain roles. When adding a button to a button box using the addButton() function, the button's role must be specified using the QDialogButtonBox::ButtonRole enum. Alternatively, QDialogButtonBox provides several standard buttons (e.g. OK, Cancel, Save) that you can use. They exist as flags so you can OR them together in the constructor.

     connect(submitButton, SIGNAL(clicked()), this, SLOT(submit()));
     connect(revertButton, SIGNAL(clicked()), model, SLOT(revertAll()));
     connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

We connect the Quit button to the table editor's close() slot, and the Submit button to our private submit() slot. The latter slot will take care of the data transactions. Finally, we connect the Revert button to our model's revertAll() slot, reverting all pending changes (i.e., restoring the original data).

     QHBoxLayout *mainLayout = new QHBoxLayout;

     setWindowTitle(tr("Cached Table"));

In the end we add the button box and the table view to a layout, install the layout on the table editor widget, and set the editor's window title.

 void TableEditor::submit()
     if (model->submitAll()) {
     } else {
         QMessageBox::warning(this, tr("Cached Table"),
                              tr("The database reported an error: %1")

The submit() slot is called whenever the users hit the Submit button to save their changes.

First, we begin a transaction on the database using the QSqlDatabase::transaction() function. A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions. A pointer to the used database can be obtained using the QSqlTableModel::database() function.

Then, we try to submit all the pending changes, i.e. the model's modified items. If no error occurs, we commit the transaction to the database using the QSqlDatabase::commit() function (note that on some databases, this function will not work if there is an active QSqlQuery on the database). Otherwise we perform a rollback of the transaction using the QSqlDatabase::rollback() function and post a warning to the user.

See also:

A complete list of Qt's SQL Database Classes, and the Model/View Programming documentation.


Best Of

Actualités les plus lues

  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 6
Page suivante

Le Qt Developer Network au hasard


Livre blanc de l'outillage de Qt Quick

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.



Liens utiles


  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !

Hébergement Web