Contacts API Usage
Introduction
This section provides some examples of common usage of the Qt Contacts API. 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
The first step is usually as simple as:
QContactManager cm;
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();
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.
If you wish to retrieve all of the details of a contact, you may do something similar to:
QList<QContactDetail> allDetails = firstContact.details();
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.
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;
newPhoneNumber.setNumber("12345");
firstContact.saveDetail(&newPhoneNumber);
cm.saveContact(&firstContact);
cm.removeContact(firstContact.localId());
That's it! For more in-depth discussion of usage of the API, see the sections below.
Manager Settings And Configuration
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 they delete the manager when they are finished with it in order to avoid a memory leak:
QContactManager *heapDefaultContactManager = new QContactManager;
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.";
qDebug() << "It" << (cm.hasFeature(QContactManager::MutableDefinitions) ? "supports" : "does not support") << "mutable detail definitions.";
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);
Contact Detail Manipulation
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 a detail to a contact
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 a detail in a contact
The client updates the phone number of a contact.
phoneNumberDetail.setNumber("+123 9876");
exampleContact.saveDetail(&phoneNumberDetail);
Removing a detail from a contact
The client removes the phone number of a contact.
exampleContact.removeDetail(&phoneNumberDetail);
Viewing a specific detail of a contact
The client retrieves and displays the first phone number of a contact
void viewSpecificDetail(QContactManager* cm)
{
QList<QContactLocalId> contactIds = cm->contactIds();
QContact a = cm->contact(contactIds.first());
qDebug() << "The first phone number of" << a.displayLabel()
<< "is" << a.detail(QContactPhoneNumber::DefinitionName).value(QContactPhoneNumber::FieldNumber);
}
Viewing all of the details of a contact
The client retrieves all of the details of a contact, and displays them
void viewDetails(QContactManager* cm)
{
QList<QContactLocalId> contactIds = cm->contactIds();
QContact a = cm->contact(contactIds.first());
qDebug() << "Viewing the details of" << a.displayLabel();
QList<QContactDetail> allDetails = a.details();
for (int i = 0; i < allDetails.size(); i++) {
QContactDetail detail = allDetails.at(i);
QContactDetailDefinition currentDefinition = cm->detailDefinition(detail.definitionName());
QMap<QString, QContactDetailFieldDefinition> fields = currentDefinition.fields();
qDebug("\tDetail #%d (%s):", i, detail.definitionName().toAscii().constData());
foreach (const QString& fieldKey, fields.keys()) {
qDebug() << "\t\t" << fieldKey << "(" << fields.value(fieldKey).dataType() << ") =" << detail.value(fieldKey);
}
qDebug();
}
}
It is important to note that details are implicitly shared objects with particular semantics surrounding saving, removal and modification. The following example demonstrates these semantics
void detailSharing(QContactManager* cm)
{
QList<QContactLocalId> contactIds = cm->contactIds();
QContact a = cm->contact(contactIds.first());
qDebug() << "Demonstrating detail sharing semantics with" << a.displayLabel();
QContactPhoneNumber newNumber;
newNumber.setNumber("123123123");
qDebug() << "\tThe new phone number is" << newNumber.number();
QContactPhoneNumber nnCopy(newNumber);
nnCopy.setNumber("456456456");
qDebug() << "\tThat number is still" << newNumber.number() << ", the copy is" << nnCopy.number();
a.saveDetail(&newNumber);
a.removeDetail(&nnCopy);
a.saveDetail(&newNumber);
qDebug() << "\tPrior to saving nnCopy," << a.displayLabel() << "has" << a.details().count() << "details.";
a.saveDetail(&nnCopy);
qDebug() << "\tAfter saving nnCopy," << a.displayLabel() << "still has" << a.details().count() << "details.";
nnCopy.resetKey();
qDebug() << "\tThe copy key is now" << nnCopy.key() << ", whereas the original key is" << newNumber.key();
qDebug() << "\tPrior to saving (key reset) nnCopy," << a.displayLabel() << "has" << a.details().count() << "details.";
a.saveDetail(&nnCopy);
qDebug() << "\tAfter saving (key reset) nnCopy," << a.displayLabel() << "still has" << a.details().count() << "details.";
a.removeDetail(&nnCopy);
QList<QContactPhoneNumber> allNumbers = a.details<QContactPhoneNumber>();
foreach (const QContactPhoneNumber& savedPhn, allNumbers) {
if (savedPhn.key() != newNumber.key()) {
continue;
}
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();
}
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:
QTM_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);
void definitionFetchRequestStateChanged(QContactAbstractRequest::State newState);
void definitionSaveRequestStateChanged(QContactAbstractRequest::State newState);
void definitionRemoveRequestStateChanged(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;
QContactDetailDefinitionFetchRequest m_definitionFetchRequest;
QContactDetailDefinitionSaveRequest m_definitionSaveRequest;
QContactDetailDefinitionRemoveRequest m_definitionRemoveRequest;
};
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).displayLabel();
}
} 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 a new contact in a manager
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);
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);
if (!m_manager.saveContact(&exampleContact))
qDebug() << "Error" << m_manager.error() << "occurred whilst saving contact!";
Retrieving contacts from a manager
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:
QContactLocalIdFilter idListFilter;
idListFilter.setIds(QList<QContactLocalId>() << exampleContact.localId());
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.localId());
Updating an existing contact in a manager
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 a contact from a manager
The client removes a contact from the manager by specifying its local id.
connect(&m_contactRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactRemoveRequestStateChanged(QContactAbstractRequest::State)));
m_contactRemoveRequest.setManager(m_manager);
m_contactRemoveRequest.setContactIds(QList<QContactLocalId>() << exampleContact.localId());
m_contactRemoveRequest.start();
The equivalent code using the synchronous API looks like:
m_manager.removeContact(exampleContact.localId());
Creating a new relationship between two contacts
The client specifies a relationship between two contacts stored in the manager
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);
QList<QContact> saveList;
saveList << exampleGroup << exampleGroupMember;
m_contactSaveRequest.setContacts(saveList);
m_contactSaveRequest.start();
m_contactSaveRequest.waitForFinished();
QContactRelationship groupRelationship;
groupRelationship.setFirst(exampleGroup.id());
groupRelationship.setRelationshipType(QContactRelationship::HasMember);
groupRelationship.setSecond(exampleGroupMember.id());
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:
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);
QMap<int, QContactManager::Error> errorMap;
QList<QContact> saveList;
saveList << exampleGroup << exampleGroupMember;
m_manager.saveContacts(&saveList, &errorMap);
QContactRelationship groupRelationship;
groupRelationship.setFirst(exampleGroup.id());
groupRelationship.setRelationshipType(QContactRelationship::HasMember);
groupRelationship.setSecond(exampleGroupMember.id());
m_manager.saveRelationship(&groupRelationship);
Retrieving relationships between contacts
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);
m_relationshipFetchRequest.setFirst(exampleGroup.id());
m_relationshipFetchRequest.setSecond(exampleGroupMember.id());
m_relationshipFetchRequest.start();
The equivalent code using the synchronous API looks like:
QList<QContactRelationship> groupRelationships = m_manager.relationships(QContactRelationship::HasMember, exampleGroup.id(), QContactRelationship::First);
QList<QContactRelationship> result;
for (int i = 0; i < groupRelationships.size(); i++) {
if (groupRelationships.at(i).second() == exampleGroupMember.id()) {
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.localId());
groupRelationships = exampleGroup.relationships(QContactRelationship::HasMember);
for (int i = 0; i < groupRelationships.size(); i++) {
if (groupRelationships.at(i).second() == exampleGroupMember.id()) {
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 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());
m_contactFetchRequest.setFetchHint(hasMemberRelationshipsOnly);
m_contactFetchRequest.start();
The equivalent code using the synchronous API looks like:
QContactFetchHint hasMemberRelationshipsOnly;
hasMemberRelationshipsOnly.setRelationshipTypesHint(QStringList(QContactRelationship::HasMember));
QList<QContact> allContacts = m_manager.contacts(QContactFilter(), QList<QContactSortOrder>(), hasMemberRelationshipsOnly);
Removing a relationship between two contacts
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.
Querying the schema supported by a manager
The client queries the schema supported by a manager, and checks to see if a particular detail definition supports a certain field.
m_definitionFetchRequest.setManager(m_manager);
m_definitionFetchRequest.setDefinitionNames(QStringList(QContactName::DefinitionName));
m_definitionFetchRequest.start();
m_definitionFetchRequest.waitForFinished();
QMap<QString, QContactDetailDefinition> definitions = m_definitionFetchRequest.definitions();
qDebug() << "This manager"
<< (definitions.value(QContactName::DefinitionName).fields().contains(QContactName::FieldCustomLabel) ? "supports" : "does not support")
<< "the custom label field of QContactName";
The equivalent code using the synchronous API looks like:
QMap<QString, QContactDetailDefinition> definitions = m_manager.detailDefinitions();
qDebug() << "This manager"
<< (definitions.value(QContactName::DefinitionName).fields().contains(QContactName::FieldCustomLabel) ? "supports" : "does not support")
<< "the custom label field of QContactName";
Modifying the schema supported by a manager
The client attempts to modify a particular detail definition by extending it so that it supports an extra field.
QContactDetailDefinition nameDefinition = definitions.value(QContactName::DefinitionName);
QContactDetailFieldDefinition fieldPatronym;
fieldPatronym.setDataType(QVariant::String);
nameDefinition.insertField("Patronym", fieldPatronym);
if (m_manager->hasFeature(QContactManager::MutableDefinitions)) {
m_definitionSaveRequest.setManager(m_manager);
m_definitionSaveRequest.setContactType(QContactType::TypeContact);
m_definitionSaveRequest.setDefinitions(QList<QContactDetailDefinition>() << nameDefinition);
m_definitionSaveRequest.start();
}
The equivalent code using the synchronous API looks like:
QContactDetailDefinition nameDefinition = definitions.value(QContactName::DefinitionName);
QContactDetailFieldDefinition fieldPatronym;
fieldPatronym.setDataType(QVariant::String);
nameDefinition.insertField("Patronym", fieldPatronym);
if (m_manager.hasFeature(QContactManager::MutableDefinitions)) {
m_manager.saveDetailDefinition(nameDefinition, QContactType::TypeContact);
}
Note that some managers do not support mutable definitions, and hence attempting to modify or remove detail definitions in those managers will fail.
|
|
Best Of
Actualités les plus lues
Le Qt Quarterly au hasard
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
|