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  · 

Combo Widget Mapper Example

Files:

The Delegate Widget Mapper example shows how to use a custom delegate to map information from a model to specific widgets on a form.

In the Simple Widget Mapper Example, we showed the basic use of a widget mapper to relate data exposed by a model to simple input widgets in a user interface. However, sometimes we want to use input widgets that expose data as choices to the user, such as QComboBox, and we need a way to relate their input to the values stored in the model.

This example is very similar to the Simple Widget Mapper Example. Again, we create a Window class with an almost identical user interface, except that, instead of providing a spin box so that each person's age can be entered, we provide a combo box to allow their addresses to be classified as "Home", "Work" or "Other".

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 *typeLabel;
     QLineEdit *nameEdit;
     QTextEdit *addressEdit;
     QComboBox *typeComboBox;
     QPushButton *nextButton;
     QPushButton *previousButton;

     QStandardItemModel *model;
     QStringListModel *typeModel;
     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 and a QStringListModel to hold information about the types of address that can be applied to each person's data.

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();
     typeLabel = new QLabel(tr("&Type:"));
     typeComboBox = new QComboBox();
     nextButton = new QPushButton(tr("&Next"));
     previousButton = new QPushButton(tr("&Previous"));

     nameLabel->setBuddy(nameEdit);
     addressLabel->setBuddy(addressEdit);
     typeLabel->setBuddy(typeComboBox);

     typeComboBox->setModel(typeModel);

Note that we set up the mapping the combo box in the same way as for other widgets, but that we apply its own model to it so that it will display data from its own model, the typeModel, rather than from the model containing data about each person.

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(typeComboBox, 2, "currentIndex");

For the combo box, we pass an extra argument to tell the widget mapper which property to relate to values from the model. As a result, the user is able to select an item from the combo box, and the corresponding value stored in the widget's currentIndex property will be stored in the model.

The rest of the constructor is very similar to that of the Simple Widget Mapper Example:

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

     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(typeLabel, 3, 0, 1, 1);
     layout->addWidget(typeComboBox, 3, 1, 1, 1);
     setLayout(layout);

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

The model is initialized in the window's setupModel() function. Here, we create a standard model with 5 rows and 3 columns. In each row, we insert a name, address, and a value that indicates the type of address. The address types are stored in a string list model.

 void Window::setupModel()
 {
     QStringList items;
     items << tr("Home") << tr("Work") << tr("Other");
     typeModel = new QStringListModel(items, this);

     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 types;
     types << "0" << "1" << "2" << "0" << "2";

     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(types[row]);
       model->setItem(row, 2, item);
     }
 }

As we insert each row into the model, like a record in a database, we store values that correspond to items in typeModel for each person's address type. When the widget mapper reads these values from the final column of each row, it will need to use them as references to values in typeModel, as shown in the following diagram. This is where the delegate is used.

We show the implementation of the updateButtons() slot for completeness:

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

Summary and Further Reading

The use of a separate model for the combo box provides a menu of choices that are separate from the data stored in the main model. Using a named mapping that relates the combo box's currentIndex property to a column in the model effectively allows us to store a look-up value in the model.

However, when reading the model outside the context of the widget mapper, we need to know about the typeModel to make sense of these look-up values. It would be useful to be able to store both the data and the choices held by the typeModel in one place. This is covered by the SQL Widget Mapper Example.

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 59
  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. 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 Labs au hasard

Logo

Construire l'avenir : (ré-)introduction aux composants de Qt Quick

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. 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.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 !
 
 
 
 
Partenaires

Hébergement Web