- Qt 5.0
- Qt Contacts API Usage
- Qt 5.0.0 Reference Documentation

# Qt Contacts API Usage

With the Qt Contacts API, typical use cases are:

- Access a list of personal contacts from the contact database supported by the selected backend.
- Sort or filter contacts and access them as a list.
- Import contacts in vCard format into the selected contacts database.
- Export contacts to a vCard format to share elsewhere.

This section provides some examples of common usage of the Qt Contacts API.

## Retrieving Contact Details

The most common use of the API is to retrieve a contact and then display certain details of that contact. To do so, several steps must be taken:

- A contact manager must be instantiated
- The contact must be retrieved from the manager
- The required details of the contact must be selected from the contact

### Instantiating Contact Manager

The first step is usually as simple as:

     QContactManager cm; // instantiate the default manager

### Retrieving a Contact from the Manager

The second step requires either a filtering operation, or, if the id of the contact is already known, a direct selection operation. If you are interested in all contacts, a default filter retrieve operation is used. The retrieval operations may either be synchronous or asynchronous; we recommend using asynchronous operations for applications which require a responsive user interface. For simplicity, however, the example below uses the synchronous API to retrieve all contacts:

     QList<QContact> allContacts = cm.contacts();

### Selecting a Detail

The third step may be performed in several ways. The recommended way is to utilize the templated detail accessor, if you know which type of detail you are interested in:

     QContact firstContact = allContacts.first();
     qDebug() << "The first contact has a phone number:" << firstContact.detail<QContactPhoneNumber>().number();

Alternatively, you can use the base QContactDetail class methods to select the detail in which you are interested in, and the field keys specified in the derived class to select the value which you are interested in:

     qDebug() << "The first contact has a phone number:" << firstContact.detail(QContactPhoneNumber::DefinitionName).value(QContactPhoneNumber::FieldNumber);

Note that in each case, if the contact did not have a phone number detail, the return value of QContact::detail() is an empty detail. Also note that in the first case, the return value will be of the QContactPhoneNumber detail type, whereas in the second case, the return value will be of the QContactDetail (base-class detail) type -- although the actual detail returned in both cases is exactly the same.

### Retrieving All Details

If you wish to retrieve all of the details of a contact, you may do something similar to:

     QList<QContactDetail> allDetails = firstContact.details();

### Retrieving Details of a Type

Alternatively, if you wish only to retrieve the details which are of some particular type, you can use either the templated or non-templated accessor:

     QList<QContactPhoneNumber> allPhoneNumbers = firstContact.details<QContactPhoneNumber>();
     QList<QContactDetail> allPhoneNumbers2 = firstContact.details(QContactPhoneNumber::DefinitionName);

Note that in each case, if the contact did not have any phone number details, the return value of QContact::details() is an empty list. Also note that in the first case, the return value will be a list of the QContactPhoneNumber detail type, whereas in the second case, the return value will be a list of the QContactDetail (base-class detail) type -- although the actual details returned in both cases will be exactly the same.

## Saving Contacts

The next most common use of the API is to save a contact. Such an operation consists of two steps:

- Saving a detail in a contact
- Saving the contact in a manager

Removing a contact is done similarly to saving a contact. An example of these two operations is given below. Note that it uses the synchronous API to save and remove the contact, although in a real application we recommend using the asynchronous API to perform such manager-related operations.

     QContactPhoneNumber newPhoneNumber;       // create the detail to add
     newPhoneNumber.setNumber("12345");        // set the value(s) to save
     firstContact.saveDetail(&newPhoneNumber); // save the detail in the contact
     cm.saveContact(&firstContact);            // save the contact in the manager
     cm.removeContact(firstContact.id()); // remove the contact from the manager

That's it! For more in-depth discussion of usage of the API, see the sections below.

## Configuring Managers

Users of the contacts API can define which backend they wish to access if a manager for that backend is available. The list of available managers can be queried programmatically at run-time, and the capabilities of different managers can be ascertained by inspecting a QContactManager instance. Furthermore, some managers can be constructed with parameters which affect the operation of the backend.

### Loading the Default Manager for the Platform

Most users of the API will want to use the default manager for the platform, which provides access to the system address book. Instantiating a manager by using the default constructor will result in the default manager for that platform being instantiated.

The default constructor can either be used to create a manager on the stack, in which case it will be deleted automatically when it goes out of scope:

         QContactManager stackDefaultContactManager;

or it can be used explicitly to create a manager on the heap, in which case the client must ensure that it deletes the manager when it is finished with it in order to avoid a memory leak:

         QContactManager *heapDefaultContactManager = new QContactManager;
         // ... perform contact manipulation
         delete heapDefaultContactManager;

### Querying a Manager for Capabilities

Different managers will support different capabilities and details. Clients can use the meta data reporting functions of QContactManager to determine what the capabilities of the manager they have instantiated might be.

         QContactManager cm;
         qDebug() << "The default manager for the platform is:" << cm.managerName();
         qDebug() << "It" << (cm.isRelationshipTypeSupported(QContactRelationship::HasAssistant()) ? "supports" : "does not support") << "assistant relationships.";
         qDebug() << "It" << (cm.supportedContactTypes().contains(QContactType::TypeGroup) ? "supports" : "does not support") << "groups.";

### Loading the Manager for a Specific Backend

In this example, the client loads a manager for a specific backend. While this could be found and retrieved using a more advanced plugin framework (such as the Qt Service Framework), this code assumes that the client has prior knowledge of the backend in question.

Clients may wish to use this feature of the API if they wish to store or retrieve contact information to a particular manager (for example, one that interfaces with a particular online service).

         QContactManager contactManager("KABC");

### Loading a Manager with Specific Parameters

The client loads a manager with specific parameters defined. The parameters which are available are backend specific, and so the client had to know that the Settings parameter was valid for the particular backend, and what argument it took. In this example, the client tells the backend to load detail definitions saved in a particular settings file.

         QMap<QString, QString> parameters;
         parameters.insert("Settings", "~/.qcontactmanager-kabc-settings.ini");
         QContactManager contactManager("KABC", parameters);

## Manipulating Contact Details

Once a contact has been created (or retrieved from a manager), the client can retrieve, create, update or delete details from the contact. Since QContact and QContactDetail are both container (value) classes, the API offered for these operations is purely synchronous.

A contact consists of the details it contains, as well as an id. Some details are read-only (such as the display label of a contact) or irremovable (like the type of a contact), but most are freely modifiable by clients.

### Adding Details

The client adds a name and a phone number to a contact.

         QContact exampleContact;

         QContactName nameDetail;
         nameDetail.setFirstName("Adam");
         nameDetail.setLastName("Unlikely");

         QContactPhoneNumber phoneNumberDetail;
         phoneNumberDetail.setNumber("+123 4567");

         exampleContact.saveDetail(&nameDetail);
         exampleContact.saveDetail(&phoneNumberDetail);

### Updating Details

The client updates the phone number of a contact.

         phoneNumberDetail.setNumber("+123 9876");
         exampleContact.saveDetail(&phoneNumberDetail); // overwrites old value on save

### Removing Details

The client removes the phone number of a contact.

         exampleContact.removeDetail(&phoneNumberDetail);

### Viewing Details

The client retrieves and displays the first phone number of a contact.

     void viewSpecificDetail(QContactManager* cm)
     {
         QList<QContactId> contactIds = cm->contactIds();
         QContact exampleContact = cm->contact(contactIds.first());
         qDebug() << "The first phone number is" << exampleContact.detail(QContactPhoneNumber::Type).value(QContactPhoneNumber::FieldNumber);
     }

### Viewing All Details of a Contact

The client retrieves all of the details of a contact, and displays them.

     void viewDetails(QContactManager* cm)
     {
         QList<QContactId> contactIds = cm->contactIds();
         QContact exampleContact = cm->contact(contactIds.first());

         QList<QContactDetail> allDetails = exampleContact.details();
         for (int i = 0; i < allDetails.size(); i++) {
             QContactDetail detail = allDetails.at(i);
             QMap<int, QVariant> fields = detail.values();

             qDebug("\tDetail #%d (%d):", i, detail.type());
             foreach (const int& fieldKey, fields.keys()) {
                 qDebug() << "\t\t" << fieldKey << "(" << fields.value(fieldKey) << ") =" << detail.value(fieldKey);
             }
             qDebug();
         }
     }

Note: Details are implicitly shared objects with particular semantics surrounding saving, removal and modification. The following example demonstrates these semantics.

     void detailSharing(QContactManager* cm)
     {
         QList<QContactId> contactIds = cm->contactIds();
         QContact a = cm->contact(contactIds.first());

         /* Create a new phone number detail. */
         QContactPhoneNumber newNumber;
         newNumber.setNumber("123123123");
         qDebug() << "\tThe new phone number is" << newNumber.number();

         /*
          * Create a copy of that detail.  These will be implicitly shared;
          * changes to nnCopy will not affect newNumber, and vice versa.
          * However, attempting to save them will cause overwrite to occur.
          * Removal is done purely via key() checking, also.
          */
         QContactPhoneNumber nnCopy(newNumber);
         nnCopy.setNumber("456456456");
         qDebug() << "\tThat number is still" << newNumber.number() << ", the copy is" << nnCopy.number();

         /* Save the detail in the contact, then remove via the copy, then resave. */
         a.saveDetail(&newNumber);
         a.removeDetail(&nnCopy);  // identical to a.removeDetail(&newNumber);
         a.saveDetail(&newNumber); // since newNumber.key() == nnCopy.key();

         /* Saving will cause overwrite */
         qDebug() << "\tPrior to saving nnCopy has" << a.details().count() << "details.";
         a.saveDetail(&nnCopy);
         qDebug() << "\tAfter saving nnCopy still has" << a.details().count() << "details.";

         /* In order to save nnCopy as a new detail, we must reset its key */
         nnCopy.resetKey();
         qDebug() << "\tThe copy key is now" << nnCopy.key() << ", whereas the original key is" << newNumber.key();
         qDebug() << "\tPrior to saving (key reset) nnCopy has" << a.details().count() << "details.";
         a.saveDetail(&nnCopy);
         qDebug() << "\tAfter saving (key reset) nnCopy still has" << a.details().count() << "details.";
         a.removeDetail(&nnCopy);

         /*
          * Note that changes made to details are not
          * propagated automatically to the contact.
          * To persist changes to a detail, you must call saveDetail().
          */
         QList<QContactPhoneNumber> allNumbers = a.details<QContactPhoneNumber>();
         foreach (const QContactPhoneNumber& savedPhn, allNumbers) {
             if (savedPhn.key() != newNumber.key()) {
                 continue;
             }

             /*
              * This phone number is the saved copy of the newNumber detail.
              * It is detached from the newNumber detail, so changes to newNumber
              * shouldn't affect savedPhn until saveDetail() is called again.
              */
             qDebug() << "\tCurrently, the (stack) newNumber is" << newNumber.number()
                      << ", and the saved newNumber is" << savedPhn.number();
             newNumber.setNumber("678678678");
             qDebug() << "\tNow, the (stack) newNumber is" << newNumber.number()
                      << ", but the saved newNumber is" << savedPhn.number();
         }

         /*
          * Removal of the detail depends only on the key of the detail; the fact
          * that the values differ is not taken into account by the remove operation.
          */
         a.removeDetail(&newNumber) ? qDebug() << "\tSucceeded in removing the temporary detail."
                                    : qDebug() << "\tFailed to remove the temporary detail.\n";
     }

## Persistent Contact Information

After instantiating a manager, clients will wish to retrieve or modify contact information (including relationships and possibly detail definitions) which is persistently stored in the manager (for example, in a database or online cloud).

If the client wishes to use the asynchronous API, it is suggested that their class uses member variables for the manager and requests, similarly to:

     QTCONTACTS_USE_NAMESPACE
     class AsyncRequestExample : public QObject
     {
         Q_OBJECT

     public:
         AsyncRequestExample();
         ~AsyncRequestExample();

     public slots:
         void performRequests();

     private slots:
         void contactFetchRequestStateChanged(QContactAbstractRequest::State newState);
         void contactSaveRequestStateChanged(QContactAbstractRequest::State newState);
         void contactRemoveRequestStateChanged(QContactAbstractRequest::State newState);
         void relationshipFetchRequestStateChanged(QContactAbstractRequest::State newState);
         void relationshipSaveRequestStateChanged(QContactAbstractRequest::State newState);
         void relationshipRemoveRequestStateChanged(QContactAbstractRequest::State newState);

     private:
         QContactManager *m_manager;
         QContactFetchRequest m_contactFetchRequest;
         QContactSaveRequest m_contactSaveRequest;
         QContactRemoveRequest m_contactRemoveRequest;
         QContactRelationshipFetchRequest m_relationshipFetchRequest;
         QContactRelationshipSaveRequest m_relationshipSaveRequest;
         QContactRelationshipRemoveRequest m_relationshipRemoveRequest;
     };

This allows them to define slots which deal with the data as required when the state of the request changes:

     void AsyncRequestExample::contactFetchRequestStateChanged(QContactAbstractRequest::State newState)
     {
         if (newState == QContactAbstractRequest::FinishedState) {
             QContactFetchRequest *request = qobject_cast<QContactFetchRequest*>(QObject::sender());
             if (request->error() != QContactManager::NoError) {
                 qDebug() << "Error" << request->error() << "occurred during fetch request!";
                 return;
             }

             QList<QContact> results = request->contacts();
             for (int i = 0; i < results.size(); i++) {
                 qDebug() << "Retrieved contact:" << results.at(i);
             }
         } else if (newState == QContactAbstractRequest::CanceledState) {
             qDebug() << "Fetch operation canceled!";
         }
     }

Note that if the client is interested in receiving the results of the request as they become available, rather than only the final set of results once the request changes state (to `FinishedState`, for example), the client should instead connect the QContactAbstractRequest::resultsAvailable() signal to the slot which deals with the results.

### Creating Contacts

The client creates a new contact and saves it in a manager.

         QContact exampleContact;

         QContactName nameDetail;
         nameDetail.setFirstName("Adam");
         nameDetail.setLastName("Unlikely");

         QContactPhoneNumber phoneNumberDetail;
         phoneNumberDetail.setNumber("+123 4567");

         exampleContact.saveDetail(&nameDetail);
         exampleContact.saveDetail(&phoneNumberDetail);

         // save the newly created contact in the manager
         connect(&m_contactSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactSaveRequestStateChanged(QContactAbstractRequest::State)));
         m_contactSaveRequest.setManager(m_manager);
         m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
         m_contactSaveRequest.start();

Alternatively, the client can explicitly block execution until the request is complete, by doing something like:

         m_contactSaveRequest.setManager(m_manager);
         m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
         m_contactSaveRequest.start();
         m_contactSaveRequest.waitForFinished();
         QList<QContact> savedContacts = m_contactSaveRequest.contacts();

The equivalent code using the synchronous API looks like:

         QContact exampleContact;

         QContactName nameDetail;
         nameDetail.setFirstName("Adam");
         nameDetail.setLastName("Unlikely");

         QContactPhoneNumber phoneNumberDetail;
         phoneNumberDetail.setNumber("+123 4567");

         exampleContact.saveDetail(&nameDetail);
         exampleContact.saveDetail(&phoneNumberDetail);

         // save the newly created contact in the manager
         if (!m_manager.saveContact(&exampleContact))
             qDebug() << "Error" << m_manager.error() << "occurred whilst saving contact!";

### Retrieving Contacts

The client requests all contacts from the manager which match a particular filter.

         connect(&m_contactFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactFetchRequestStateChanged(QContactAbstractRequest::State)));
         m_contactFetchRequest.setManager(m_manager);
         m_contactFetchRequest.setFilter(QContactPhoneNumber::match("+123 4567"));
         m_contactFetchRequest.start();

The equivalent code using the synchronous API looks like:

         QList<QContact> results = m_manager.contacts(QContactPhoneNumber::match("+123 4567"));

The client can also retrieve a particular existing contact from a manager, by directly requesting the contact with a particular (previously known) id. With the asynchronous API, this takes the form of another filter:

         QContactIdFilter idListFilter;
         idListFilter.setIds(QList<QContactId>() << exampleContact.id());
         m_contactFetchRequest.setManager(m_manager);
         m_contactFetchRequest.setFilter(idListFilter);
         m_contactFetchRequest.start();

The synchronous API provides a function specifically for this purpose:

         QContact existing = m_manager.contact(exampleContact.id());

### Updating Contacts

The client updates a previously saved contact by saving the updated version of the contact. Any contact whose id is the same as that of the updated contact will be overwritten as a result of the save request.

         phoneNumberDetail.setNumber("+123 9876");
         exampleContact.saveDetail(&phoneNumberDetail);
         m_contactSaveRequest.setManager(m_manager);
         m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
         m_contactSaveRequest.start();

The equivalent code using the synchronous API looks like:

         phoneNumberDetail.setNumber("+123 9876");
         exampleContact.saveDetail(&phoneNumberDetail);
         m_manager.saveContact(&exampleContact);

### Removing Contacts

The client removes a contact from the manager by specifying its id.

         connect(&m_contactRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactRemoveRequestStateChanged(QContactAbstractRequest::State)));
         m_contactRemoveRequest.setManager(m_manager);
         m_contactRemoveRequest.setContactIds(QList<QContactId>() << exampleContact.id());
         m_contactRemoveRequest.start();

The equivalent code using the synchronous API looks like:

         m_manager.removeContact(exampleContact.id());

### Creating Relationships

The client specifies a relationship between two contacts stored in the manager

         // first, create the group and the group member
         QContact exampleGroup;
         exampleGroup.setType(QContactType::TypeGroup);
         QContactNickname groupName;
         groupName.setNickname("Example Group");
         exampleGroup.saveDetail(&groupName);

         QContact exampleGroupMember;
         QContactName groupMemberName;
         groupMemberName.setFirstName("Member");
         exampleGroupMember.saveDetail(&groupMemberName);

         // second, save those contacts in the manager
         QList<QContact> saveList;
         saveList << exampleGroup << exampleGroupMember;
         m_contactSaveRequest.setContacts(saveList);
         m_contactSaveRequest.start();
         m_contactSaveRequest.waitForFinished();

         // third, create the relationship between those contacts
         QContactRelationship groupRelationship;
         groupRelationship.setFirst(exampleGroup);
         groupRelationship.setRelationshipType(QContactRelationship::HasMember());
         groupRelationship.setSecond(exampleGroupMember);

         // finally, save the relationship in the manager
         connect(&m_relationshipSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipSaveRequestStateChanged(QContactAbstractRequest::State)));
         m_relationshipSaveRequest.setManager(m_manager);
         m_relationshipSaveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
         m_relationshipSaveRequest.start();

The equivalent code using the synchronous API looks like:

         // first, create the group and the group member
         QContact exampleGroup;
         exampleGroup.setType(QContactType::TypeGroup);
         QContactNickname groupName;
         groupName.setNickname("Example Group");
         exampleGroup.saveDetail(&groupName);

         QContact exampleGroupMember;
         QContactName groupMemberName;
         groupMemberName.setFirstName("Member");
         exampleGroupMember.saveDetail(&groupMemberName);

         // second, save those contacts in the manager
         QMap<int, QContactManager::Error> errorMap;
         QList<QContact> saveList;
         saveList << exampleGroup << exampleGroupMember;
         m_manager.saveContacts(&saveList, &errorMap);

         // third, create the relationship between those contacts
         QContactRelationship groupRelationship;
         groupRelationship.setFirst(exampleGroup);
         groupRelationship.setRelationshipType(QContactRelationship::HasMember());
         groupRelationship.setSecond(exampleGroupMember);

         // finally, save the relationship in the manager
         m_manager.saveRelationship(&groupRelationship);

### Retrieving Relationships

The client requests the relationships that a particular contact is involved in from the manager in which the contact is stored.

         connect(&m_relationshipFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipFetchRequestStateChanged(QContactAbstractRequest::State)));
         m_relationshipFetchRequest.setManager(m_manager);
         // retrieve the list of relationships between the example group contact and the example member contact
         // where the group contact is the first contact in the relationship, and the member contact is the
         // second contact in the relationship.  In order to fetch all relationships between them, another
         // relationship fetch must be performed with their roles reversed, and the results added together.
         m_relationshipFetchRequest.setFirst(exampleGroup);
         m_relationshipFetchRequest.setSecond(exampleGroupMember);
         m_relationshipFetchRequest.start();

The equivalent code using the synchronous API looks like:

         QList<QContactRelationship> groupRelationships = m_manager.relationships(exampleGroup, QContactRelationship::First);
         QList<QContactRelationship> result;
         for (int i = 0; i < groupRelationships.size(); i++) {
             if (groupRelationships.at(i).second() == exampleGroupMember) {
                 result.append(groupRelationships.at(i));
             }
         }

When a contact is retrieved, it will contain a cache of the relationships in which it is involved at the point in time at which it was retrieved. This provides clients with a simple way to retrieve the relationships in which a contact is involved, but carries the risk that the cache is stale.

         exampleGroup = m_manager.contact(exampleGroup.id()); // refresh the group contact
         groupRelationships = exampleGroup.relationships(QContactRelationship::HasMember());
         for (int i = 0; i < groupRelationships.size(); i++) {
             if (groupRelationships.at(i).second() == exampleGroupMember) {
                 result.append(groupRelationships.at(i));
             }
         }

Clients can inform the manager that they do not require this cache of relationships to be populated when retrieving a contact, which can allow a manager to optimize contact retrieval. Other retrieval optimizations are also possible to specify, for example that they do not require action preferences to be returned, or that they are only interested in certain types of details. The following code shows how the client can inform the manager that they are only interested in relationships of the `HasMember` type (groups):

         QContactFetchHint hasMemberRelationshipsOnly;
         hasMemberRelationshipsOnly.setRelationshipTypesHint(QStringList(QContactRelationship::HasMember()));

         m_contactFetchRequest.setManager(m_manager);
         m_contactFetchRequest.setFilter(QContactFilter()); // all contacts
         m_contactFetchRequest.setFetchHint(hasMemberRelationshipsOnly);
         m_contactFetchRequest.start();

The equivalent code using the synchronous API looks like:

         QContactFetchHint hasMemberRelationshipsOnly;
         hasMemberRelationshipsOnly.setRelationshipTypesHint(QStringList(QContactRelationship::HasMember()));

         // retrieve all contacts, with no specified sort order, requesting that
         // HasMember relationships be included in the cache of result contacts
         QList<QContact> allContacts = m_manager.contacts(QContactFilter(), QList<QContactSortOrder>(), hasMemberRelationshipsOnly);

### Removing Relationships

The client can remove a relationship directly from a manager.

         connect(&m_relationshipRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipRemoveRequestStateChanged(QContactAbstractRequest::State)));
         m_relationshipRemoveRequest.setManager(m_manager);
         m_relationshipRemoveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
         m_relationshipRemoveRequest.start();

The equivalent code using the synchronous API looks like:

         m_manager.removeRelationship(groupRelationship);

Alternatively, when a contact which is involved in a relationship is removed, any relationships in which it is involved will be removed also.