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  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Address Book 4 - Editing and Removing Addresses

Files:

In this chapter, we look at ways to modify the contents of contact stored in the address book application.

We now have an address book that not only holds contacts in an organized manner, but also allows navigation. It would be convenient to include edit and remove functions so that a contact's details can be changed when needed. However, this requires a little improvement, in the form of enums. In our previous chapters, we had two modes: AddingMode and NavigationMode - but they weren't defined as enums. Instead, we enabled and disabled the corresponding buttons manually, resulting in multiple lines of repeated code.

In this chapter, we define the Mode enum with three different values:

  • NavigationMode,
  • AddingMode, and
  • EditingMode.

Defining the AddressBook Class

The addressbook.h file is updated to contain the Mode enum:

     enum Mode { NavigationMode, AddingMode, EditingMode };

We also add two new slots, editContact() and removeContact(), to our current list of public slots.

     void editContact();
     void removeContact();

In order to switch between modes, we introduce the updateInterface() function to control the enabling and disabling of all QPushButton objects. We also add two new push buttons, editButton and removeButton, for the edit and remove functions mentioned earlier.

     void updateInterface(Mode mode);
     ...
     QPushButton *editButton;
     QPushButton *removeButton;
     ...
     Mode currentMode;

Lastly, we declare currentMode to keep track of the current mode of the enum.

Implementing the AddressBook Class

We now have to implement the mode-changing features of the address book application. The editButton and removeButton are instantiated and disabled by default, as the address book starts up with zero contacts in memory.

     editButton = new QPushButton(tr("&Edit"));
     editButton->setEnabled(false);
     removeButton = new QPushButton(tr("&Remove"));
     removeButton->setEnabled(false);

These buttons are then connected to their respective slots, editContact() and removeContact(), and we add them to buttonLayout1.

     connect(editButton, SIGNAL(clicked()), this, SLOT(editContact()));
     connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact()));
     ...
     buttonLayout1->addWidget(editButton);
     buttonLayout1->addWidget(removeButton);

The editContact() function stores the contact's old details in oldName and oldAddress, before switching the mode to EditingMode. In this mode, the submitButton and cancelButton are both enabled, hence, the user can change the contact's details and click either button.

 void AddressBook::editContact()
 {
     oldName = nameLine->text();
     oldAddress = addressText->toPlainText();

     updateInterface(EditingMode);
 }

The submitContact() function has been divided in two with an if-else statement. We check currentMode to see if its in AddingMode. If it is, we proceed with our adding process.

 void AddressBook::submitContact()
 {
     ...
     if (currentMode == AddingMode) {

         if (!contacts.contains(name)) {
             contacts.insert(name, address);
             QMessageBox::information(this, tr("Add Successful"),
                 tr("\"%1\" has been added to your address book.").arg(name));
         } else {
             QMessageBox::information(this, tr("Add Unsuccessful"),
                 tr("Sorry, \"%1\" is already in your address book.").arg(name));
             return;
         }

Otherwise, we check to see if currentMode is in EditingMode. If it is, we compare oldName with name. If the name has changed, we remove the old contact from contacts and insert the newly updated contact.

     } else if (currentMode == EditingMode) {

         if (oldName != name) {
             if (!contacts.contains(name)) {
                 QMessageBox::information(this, tr("Edit Successful"),
                     tr("\"%1\" has been edited in your address book.").arg(oldName));
                 contacts.remove(oldName);
                 contacts.insert(name, address);
             } else {
                 QMessageBox::information(this, tr("Edit Unsuccessful"),
                     tr("Sorry, \"%1\" is already in your address book.").arg(name));
                 return;
             }
         } else if (oldAddress != address) {
             QMessageBox::information(this, tr("Edit Successful"),
                 tr("\"%1\" has been edited in your address book.").arg(name));
             contacts[name] = address;
         }
     }

     updateInterface(NavigationMode);
 }

If only the address has changed (i.e., oldAddress is not the same as address), we update the contact's address. Lastly, we set currentMode to NavigationMode. This is an important step as it re-enables all the disabled push buttons.

To remove a contact from the address book, we implement the removeContact() function. This function checks to see if the contact exists in contacts.

 void AddressBook::removeContact()
 {
     QString name = nameLine->text();
     QString address = addressText->toPlainText();

     if (contacts.contains(name)) {

         int button = QMessageBox::question(this,
             tr("Confirm Remove"),
             tr("Are you sure you want to remove \"%1\"?").arg(name),
             QMessageBox::Yes | QMessageBox::No);

         if (button == QMessageBox::Yes) {

             previous();
             contacts.remove(name);

             QMessageBox::information(this, tr("Remove Successful"),
                 tr("\"%1\" has been removed from your address book.").arg(name));
         }
     }

     updateInterface(NavigationMode);
 }

If it does, we display a QMessageBox, to confirm the removal with the user. Once the user has confirmed, we call previous() to ensure that the user interface shows another contact, and we remove the contact using QMap's remove() function. As a courtesy, we display a QMessageBox to inform the user. Both the message boxes used in this function are shown below:

Updating the User Interface

We mentioned the updateInterface() function earlier as a means to enable and disable the push buttons depending on the current mode. The function updates the current mode according to the mode argument passed to it, assigning it to currentMode before checking its value.

Each of the push buttons is then enabled or disabled, depending on the current mode. The code for AddingMode and EditingMode is shown below:

 void AddressBook::updateInterface(Mode mode)
 {
     currentMode = mode;

     switch (currentMode) {

     case AddingMode:
     case EditingMode:

         nameLine->setReadOnly(false);
         nameLine->setFocus(Qt::OtherFocusReason);
         addressText->setReadOnly(false);

         addButton->setEnabled(false);
         editButton->setEnabled(false);
         removeButton->setEnabled(false);

         nextButton->setEnabled(false);
         previousButton->setEnabled(false);

         submitButton->show();
         cancelButton->show();
         break;

For NavigationMode, however, we include conditions within the parameters of the QPushButton::setEnabled(). This is to ensure that the editButton and removeButton push buttons are enabled when there is at least one contact in the address book; nextButton and previousButton are only enabled when there is more than one contact in the address book.

     case NavigationMode:

         if (contacts.isEmpty()) {
             nameLine->clear();
             addressText->clear();
         }

         nameLine->setReadOnly(true);
         addressText->setReadOnly(true);
         addButton->setEnabled(true);

         int number = contacts.size();
         editButton->setEnabled(number >= 1);
         removeButton->setEnabled(number >= 1);
         nextButton->setEnabled(number > 1);
         previousButton->setEnabled(number >1 );

         submitButton->hide();
         cancelButton->hide();
         break;
     }
 }

By performing the task of setting the mode and updating the user interface in the same function, we avoid the possibility of the user interface getting "out of sync" with the internal state of the application.

[Previous: Address Book 3 - Navigating between Entries] [Contents] [Next: Chapter 5]

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 56
  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 Developer Network au hasard

Logo

Combiner licence, à propos et fermer d'une dernière manière

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.

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