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  · 

QVersitContactImporter Class Reference

The QVersitContactImporter class creates QContacts from QVersitDocuments. More...

    #include <QVersitContactImporter>

Public Types

enum Error { NoError, InvalidDocumentError, EmptyDocumentError }

Public Functions

QVersitContactImporter ()
~QVersitContactImporter ()
QList<QContact> contacts () const
QMap<int, Error> errors () const
bool importDocuments ( const QList<QVersitDocument> & documents )
QVersitContactImporterPropertyHandler * propertyHandler () const
QVersitResourceHandler * resourceHandler () const
void setPropertyHandler ( QVersitContactImporterPropertyHandler * handler )
void setResourceHandler ( QVersitResourceHandler * handler )

Detailed Description

The QVersitContactImporter class creates QContacts from QVersitDocuments.

A QVersitResourceHandler is associated with the importer to supply the behaviour for saving files to persistent storage. By default, this is set to a QVersitDefaultResourceHandler, which does not save files to persistent storage. Note that although avatars found in vCards are not saved to disk by default, the importer does set the pixmap of the contact detail to the image. If a full-sized avatar image needs to be persisted, a custom QVersitResourceHandler should be supplied which implements this.

By associating a QVersitContactImporterPropertyHandler with the importer using setPropertyHandler(), the client can pass in a handler to override the processing of properties and/or handle properties that QVersitContactImporter doesn't support.

An example property handler that decodes unknown properties generated by the example detail handler provided in the QVersitContactExporter documentation:

    class MyPropertyHandler : public QVersitContactImporterPropertyHandler {
    public:
        bool preProcessProperty(const QVersitDocument& document, const QVersitProperty& property,
                                int contactIndex, QContact* contact) {
            Q_UNUSED(document) Q_UNUSED(property) Q_UNUSED(contactIndex) Q_UNUSED(contact)
            return false;
        }
        /* eg. if the document has the properties:
         * G0.DETAIL-FIELD1:Value1
         * G0.DETAIL-FIELD2:Value2
         * G1.DETAIL-FIELD1:Value3
         * This will generate two details - the first with fields "FIELD1"="Value1" and
         * "FIELD2"="Value2" and the second with "FIELD1"="Value3"
         * ie. the vCard groups determine which properties form a single detail.
         */
        bool postProcessProperty(const QVersitDocument& document, const QVersitProperty& property,
                                 bool alreadyProcessed, int contactIndex, QContact* contact) {
            Q_UNUSED(document) Q_UNUSED(contactIndex)
            const QString prefix = QLatin1String("X-QCONTACTDETAIL-");
            if (alreadyProcessed)
                return false;
            if (!property.name().startsWith(prefix))
                return false;
            QString detailAndField = property.name().mid(prefix.size());
            QStringList detailAndFieldParts = detailAndField.split(QLatin1Char('-'),
                                                                   QString::SkipEmptyParts);
            if (detailAndFieldParts.size() != 2)
                return false;
            QString definitionName = detailAndFieldParts.at(0);
            QString fieldName = detailAndFieldParts.at(1);
            if (property.groups().size() != 1)
                return false;
            QString group = property.groups().first();
            // find a detail generated from the a property with the same group
            QContactDetail detail = handledDetails.value(group);
            // make sure the the existing detail has the same definition name
            if (detail.definitionName() != definitionName)
                detail = QContactDetail(definitionName);
            detail.setValue(fieldName, property.value());
            contact->saveDetail(&detail);
            handledDetails.insert(group, detail);
            return false;
        }
        QMap<QString, QContactDetail> handledDetails; // map from group name to detail
    };

An example usage of QVersitContactImporter

        QVersitContactImporter importer;

        MyPropertyHandler propertyHandler;
        importer.setPropertyHandler(&propertyHandler);

        QVersitDocument document;

        QVersitProperty property;
        property.setName(QString::fromAscii("N"));
        property.setValue("Citizen;John;Q;;");
        document.addProperty(property);

        property.setName(QString::fromAscii("X-UNKNOWN-PROPERTY"));
        property.setValue("some value");
        document.addProperty(property);

        if (importer.importDocuments(QList<QVersitDocument>() << document)) {
            QList<QContact> contactList = importer.contacts();
            // contactList.first() now contains the "N" property as a QContactName
            // propertyHandler.mUnknownProperties contains the list of unknown properties
        }

Importing categories

The importer imports the vCard CATEGORIES property by converting each category to a QContactTag. Some managers may not have support for QContactTag, but instead support categorization using the HasMember QContactRelationship along with contacts of type TypeGroup. For these backends, if the categorization information needs to be retained through group relationships, extra work needs to be done to do the conversion. Below is some example code that does this translation.

    /*! Adds contacts in  \a newContacts into \a manager, converting categories specified
      with tags into group membership relationships.  Note that this implementation uses the
      synchronous API of QContactManager for clarity.  It is recommended that the asynchronous
      API is used in practice.

      Relationships are added so that if a contact, A, has a tag "b", then a HasMember relationship is
      created between a group contact in the manager, B with display label "b", and contact A.  If there
      does not exist a group contact with display label "b", one is created.
      */
    void insertWithGroups(const QList<QContact>& newContacts, QContactManager* manager)
    {
        // Cache map from group names to QContactIds
        QMap<QString, QContactId> groupMap;

        foreach (QContact contact, newContacts) {
            if (!manager->saveContact(&contact))
                continue; // In practice, better error handling may be required
            foreach (const QContactTag& tag, contact.details<QContactTag>()) {
                QString groupName = tag.tag();
                QContactId groupId;
                if (groupMap.contains(groupName)) {
                    // We've already seen a group with the right name
                    groupId = groupMap.value(groupName);
                } else {
                    QContactDetailFilter groupFilter;
                    groupFilter.setDetailDefinitionName(QContactType::DefinitionName);
                    groupFilter.setValue(QLatin1String(QContactType::TypeGroup));
                    groupFilter.setMatchFlags(QContactFilter::MatchExactly);
                    // In practice, some detail other than the display label could be used
                    QContactDetailFilter nameFilter = QContactDisplayLabel::match(groupName);
                    QList<QContactLocalId> matchingGroups = manager->contactIds(groupFilter & nameFilter);
                    if (!matchingGroups.isEmpty()) {
                        // Found an existing group in the manager
                        QContactId groupId;
                        groupId.setManagerUri(manager->managerUri());
                        groupId.setLocalId(matchingGroups.first());
                        groupMap.insert(groupName, groupId);
                    }
                    else {
                        // Make a new group
                        QContact groupContact;
                        QContactName name;
                        name.setCustomLabel(groupName);
                        // Beware that not all managers support custom label
                        groupContact.saveDetail(&name);
                        if (!manager->saveContact(&groupContact))
                            continue; // In practice, better error handling may be required
                        groupId = groupContact.id();
                        groupMap.insert(groupName, groupId);
                    }
                }
                // Add the relationship
                QContactRelationship rel;
                rel.setFirst(groupId);
                rel.setRelationshipType(QContactRelationship::HasMember);
                rel.setSecond(contact.id());
                manager->saveRelationship(&rel);
            }
        }
    }

See also QVersitDocument, QVersitReader, and QVersitContactImporterPropertyHandler.


Member Type Documentation

enum QVersitContactImporter::Error

This enum specifies an error that occurred during the most recent call to importDocuments()

ConstantValueDescription
QVersitContactImporter::NoError0The most recent operation was successful
QVersitContactImporter::InvalidDocumentError1One of the documents is not a vCard
QVersitContactImporter::EmptyDocumentError2One of the documents is empty


Member Function Documentation

QVersitContactImporter::QVersitContactImporter ()

Constructs a new importer

QVersitContactImporter::~QVersitContactImporter ()

Frees the memory used by the importer

QList<QContact> QVersitContactImporter::contacts () const

Returns the contacts imported in the most recent call to importDocuments().

See also importDocuments().

QMap<int, Error> QVersitContactImporter::errors () const

Returns the map of errors encountered in the most recent call to importDocuments(). The key is the index into the input list of documents and the value is the error that occurred on that document.

See also importDocuments().

bool QVersitContactImporter::importDocuments ( const QList<QVersitDocument> & documents )

Converts documents into a corresponding list of QContacts. After calling this, the converted contacts can be retrieved by calling contacts(). Returns true on success. If any of the documents cannot be imported as contacts (eg. they aren't vCards), false is returned and errors() will return a list describing the errors that occurred. The successfully imported documents will still be available via contacts().

See also contacts() and errors().

QVersitContactImporterPropertyHandler * QVersitContactImporter::propertyHandler () const

Gets the handler for processing QVersitProperties.

See also setPropertyHandler().

QVersitResourceHandler * QVersitContactImporter::resourceHandler () const

Returns the associated resource handler.

See also setResourceHandler().

void QVersitContactImporter::setPropertyHandler ( QVersitContactImporterPropertyHandler * handler )

Sets handler to be the handler for processing QVersitProperties, or 0 to have no handler.

Does not take ownership of the handler. The client should ensure the handler remains valid for the lifetime of the exporter.

See also propertyHandler().

void QVersitContactImporter::setResourceHandler ( QVersitResourceHandler * handler )

Sets handler to be the handler to save files with, or 0 to have no handler.

Does not take ownership of the handler. The client should ensure the handler remains valid for the lifetime of the exporter.

See also resourceHandler().

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 qtmobility-1.0
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