Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us 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  · 

Simple Widget Mapper Example

Files:

The Simple Widget Mapper example shows how to use a widget mapper to display data from a model in a collection of widgets.

The QDataWidgetMapper class allows information obtained from a model to be viewed and edited in a collection of widgets instead of in an item view. Any model derived from QAbstractItemModel can be used as the source of data and almost any input widget can be used to display it.

The example itself is very simple: we create Window, a QWidget subclass that we use to hold the widgets used to present the data, and show it. The Window class will provide buttons that the user can click to show different records from the model.

Window Class Definition

The class provides a constructor, a slot to keep the buttons up to date, and a private function to set up the model:

 class Window : public QWidget
 {
     Q_OBJECT

 public:
     Window(QWidget *parent = 0);

 private slots:
     void updateButtons(int row);

 private:
     void setupModel();

     QLabel *nameLabel;
     QLabel *addressLabel;
     QLabel *ageLabel;
     QLineEdit *nameEdit;
     QTextEdit *addressEdit;
     QSpinBox *ageSpinBox;
     QPushButton *nextButton;
     QPushButton *previousButton;

     QStandardItemModel *model;
     QDataWidgetMapper *mapper;
 };

In addition to the QDataWidgetMapper object and the controls used to make up the user interface, we use a QStandardItemModel to hold our data. We could use a custom model, but this standard implementation is sufficient for our purposes.

Window Class Implementation

The constructor of the Window class can be explained in three parts. In the first part, we set up the widgets used for the user interface:

 Window::Window(QWidget *parent)
     : QWidget(parent)
 {
     setupModel();

     nameLabel = new QLabel(tr("Na&me:"));
     nameEdit = new QLineEdit();
     addressLabel = new QLabel(tr("&Address:"));
     addressEdit = new QTextEdit();
     ageLabel = new QLabel(tr("A&ge (in years):"));
     ageSpinBox = new QSpinBox();
     nextButton = new QPushButton(tr("&Next"));
     previousButton = new QPushButton(tr("&Previous"));

     nameLabel->setBuddy(nameEdit);
     addressLabel->setBuddy(addressEdit);
     ageLabel->setBuddy(ageSpinBox);

We also set up the buddy relationships between various labels and the corresponding input widgets.

Next, we set up the widget mapper, relating each input widget to a column in the model specified by the call to setModel():

     mapper = new QDataWidgetMapper(this);
     mapper->setModel(model);
     mapper->addMapping(nameEdit, 0);
     mapper->addMapping(addressEdit, 1);
     mapper->addMapping(ageSpinBox, 2);

     connect(previousButton, SIGNAL(clicked()),
             mapper, SLOT(toPrevious()));
     connect(nextButton, SIGNAL(clicked()),
             mapper, SLOT(toNext()));
     connect(mapper, SIGNAL(currentIndexChanged(int)),
             this, SLOT(updateButtons(int)));

We also connect the mapper to the Next and Previous buttons via its toNext() and toPrevious() slots. The mapper's currentIndexChanged() signal is connected to the updateButtons() slot in the window which we'll show later.

In the final part of the constructor, we set up the layout, placing each of the widgets in a grid (we could also use a QFormLayout for this):

     QGridLayout *layout = new QGridLayout();
     layout->addWidget(nameLabel, 0, 0, 1, 1);
     layout->addWidget(nameEdit, 0, 1, 1, 1);
     layout->addWidget(previousButton, 0, 2, 1, 1);
     layout->addWidget(addressLabel, 1, 0, 1, 1);
     layout->addWidget(addressEdit, 1, 1, 2, 1);
     layout->addWidget(nextButton, 1, 2, 1, 1);
     layout->addWidget(ageLabel, 3, 0, 1, 1);
     layout->addWidget(ageSpinBox, 3, 1, 1, 1);
     setLayout(layout);

     setWindowTitle(tr("Simple Widget Mapper"));
     mapper->toFirst();
 }

Lastly, we set the window title and initialize the mapper by setting it to refer to the first row in the model.

The model is initialized in the window's setupModel() function. Here, we create a standard model with 5 rows and 3 columns, and we insert some sample names, addresses and ages into each row:

 void Window::setupModel()
 {
     model = new QStandardItemModel(5, 3, this);

     QStringList names;
     names << "Alice" << "Bob" << "Carol" << "Donald" << "Emma";

     QStringList addresses;
     addresses << "<qt>123 Main Street<br/>Market Town</qt>"
               << "<qt>PO Box 32<br/>Mail Handling Service"
                  "<br/>Service City</qt>"
               << "<qt>The Lighthouse<br/>Remote Island</qt>"
               << "<qt>47338 Park Avenue<br/>Big City</qt>"
               << "<qt>Research Station<br/>Base Camp<br/>Big Mountain</qt>";

     QStringList ages;
     ages << "20" << "31" << "32" << "19" << "26";

     for (int row = 0; row < 5; ++row) {
       QStandardItem *item = new QStandardItem(names[row]);
       model->setItem(row, 0, item);
       item = new QStandardItem(addresses[row]);
       model->setItem(row, 1, item);
       item = new QStandardItem(ages[row]);
       model->setItem(row, 2, item);
     }
 }

As a result, each row can be treated like a record in a database, and the widget mapper will read the data from each row, using the column numbers specified earlier to access the correct data for each widget. This is shown in the following diagram:

Since the user can navigate using the buttons in the user interface, the example is fully-functional at this point, but to make it a bit more user-friendly, we implement the updateButtons() slot to show when the user is viewing the first or last records:

 void Window::updateButtons(int row)
 {
     previousButton->setEnabled(row > 0);
     nextButton->setEnabled(row < model->rowCount() - 1);
 }

If the mapper is referring to the first row in the model, the Previous button is disabled. Similarly, the Next button is disabled if the mapper reaches the last row in the model.

More Complex Mappings

The QDataWidgetMapper class makes it easy to relate information from a model to widgets in a user interface. However, it is sometimes necessary to use input widgets which offer choices to the user, such as QComboBox, in conjunction with a widget mapper.

In these situations, although the mapping to input widgets remains simple, more work needs to be done to expose additional data to the widget mapper. This is covered by the Combo Widget Mapper and SQL Widget Mapper examples.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 54
  2. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  3. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  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. La rubrique Qt a besoin de vous ! 1
Page suivante

Le Qt Quarterly au hasard

Logo

FAQ sur l'internationalisation

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • 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.7
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 !
 
 
 
 
Partenaires

Hébergement Web