Enginio C++ Examples - Cloud Address Book
This example explains how to use the full text search feature of Enginio, and how to sort and filter data showed from the EnginioModel. A simple addressbook-like application will be created to illustrate this. This example doesn't cover security or multi-user management. For such topics, please refer to the Social Todo example.
Preconditions
To start the example, a backend id and a backend secret have to be provided for an existing and configured Enginio backend. The backend can be created using the dashboard, where the Cloud Address Book preconfigured backend can be chosen.
Backend Description
We recommend to use preconfigured backend, because it contains already all data and structures that are needed to run these examples, but it is not difficult to create the backend from scratch too. The backend should contain one custom object type objects.addressbook
having properties:
- firstName
- lastName
- phone
- address
All properties are of string
type and have to be indexed, because only indexed properties will be searched by the full text search.
Application Design
The application's ui mainly consists of a table showing all addresses and a text filed where a query can be typed. A user should be able to sort addresses or highlight an address containing a specified phrase.
Implementation
From a developer point of view the application consists of a few simple components:
- EnginioClient which encapsulates all information needed to keep the connection to the backend
- EnginioModel which queries all addresses
- QSortFilterProxy which sorts the data
- QTableView which shows the data
First we need to establish a connection to the Enginio service. We need to specify the backend id as well as backend secret.
client = new EnginioClient(this); client->setBackendId(EnginioBackendId);
The second step is to create EnginioModel which queries all data from the backend. The query is quite simple, it specifies an object type of which all objects need to be returned.
model = new AddressBookModel(this); model->setClient(client); QJsonObject query; query["objectType"] = QString::fromUtf8("objects.addressbook"); model->setQuery(query);
EnginioModel can sort or filter data only initially, which means that, for example, a newly added item will not be placed correctly. To solve the problem QSortFilterProxy has to be used.
sortFilterProxyModel = new QSortFilterProxyModel(this); sortFilterProxyModel->setSourceModel(model); tableView->setSortingEnabled(true); tableView->setModel(sortFilterProxyModel);
Now is a time to look deeper into EngnioModel. EnginioModel should define data roles.
enum Roles { FirstNameRole = Enginio::CustomPropertyRole, LastNameRole, EmailRole, PhoneRole, AddressRole }; QHash<int, QByteArray> AddressBookModel::roleNames() const { QHash<int, QByteArray> roles = EnginioModel::roleNames(); roles.insert(FirstNameRole, "firstName"); roles.insert(LastNameRole, "lastName"); roles.insert(EmailRole, "email"); roles.insert(PhoneRole, "phone"); roles.insert(AddressRole, "address"); return roles; }
and as always the data() and setData() functions have to be overridden to provide Qt::DisplayRole in such a way as to nicely cooperate with QTableView.
QVariant AddressBookModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { // we assume here that column order is constant and it is the same as in AddressBookModel::Roles return EnginioModel::data(index, FirstNameRole + index.column()).value<QJsonValue>().toString(); } if (role == Qt::FontRole) { // this role is used to mark items found in the full text search. QFont font; QString id = EnginioModel::data(index, Enginio::IdRole).value<QString>(); font.setBold(_markedItems.contains(id)); return font; } return EnginioModel::data(index, role); } bool AddressBookModel::setData(const QModelIndex &index, const QVariant &value, int role) { bool result = role == Qt::EditRole ? EnginioModel::setData(this->index(index.row()), value, FirstNameRole + index.column()) : EnginioModel::setData(this->index(index.row()), value, role); // if the data was edited, the marked items set may not be valid anymore // so we need to clear it. if (result) _markedItems.clear(); return result; }
QTableView requires the specification of columns headers, so that they can be shown in the user interface:
int AddressBookModel::columnCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : 5; } QVariant AddressBookModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case 0: return QStringLiteral("First name"); case 1: return QStringLiteral("Last name"); case 2: return QStringLiteral("Email"); case 3: return QStringLiteral("Phone number"); case 4: return QStringLiteral("Address"); } return QVariant(); } return EnginioModel::headerData(section, orientation, role); }
Integration of the full text search is the last step in this tutorial. The goal is to highlight items that contain a given phrase. The highlighting is done by data(), which returns a bold font for Qt::FontRole if an item is matching the search query. For reasons of simplicity, this example assumes that the matching items count is not big and can be kept in a QSet, which would be recreated on each search.
To do a full text search, a JSON query needs to be constructed:
// construct JSON object: // { // "objectTypes": ["objects.addressbook"], // "search": { "phrase": "*PHRASE*", // "properties": ["firstName", "lastName", "email", "phone", "address"] // } // } QJsonObject query; { QJsonArray objectTypes; objectTypes.append(QString::fromUtf8("objects.addressbook")); QJsonArray properties; properties.append(QString::fromUtf8("firstName")); properties.append(QString::fromUtf8("lastName")); properties.append(QString::fromUtf8("email")); properties.append(QString::fromUtf8("phone")); properties.append(QString::fromUtf8("address")); QJsonObject searchQuery; searchQuery.insert("phrase", "*" + search + "*"); searchQuery.insert("properties", properties); query.insert("objectTypes", objectTypes); query.insert("search", searchQuery); }
The query contains objectTypes
property (note the 's' at the end) which is an array of all object types which have to be searched. In this case, it is only one type: objects.addressbook
. Next the search
property has to be specified. It is an object that is required to have a phrase
property, containing the phrase to search for. phrase that has to be found. Please use the wildcard *
in the search criteria, otherwise only full words will be found. To avoid substrings, for example in an object id
, which is not visible for a user, the search is limited to a selected array of properties
. When the search query is constructed, it is enough to call fullTextSearch():
_searchReply = client()->fullTextSearch(query); QObject::connect(_searchReply, &EnginioReply::finished, this, &AddressBookModel::searchResultsArrived); QObject::connect(_searchReply, &EnginioReply::finished, _searchReply, &EnginioReply::deleteLater);
The result will be delivered to the searchResultsArrived
slot. All objects ids found will be gathered in a markedItems
set.
void AddressBookModel::searchResultsArrived() { // clear old marks. _markedItems.clear(); // update marked ids. QJsonArray results = _searchReply->data()["results"].toArray(); foreach (const QJsonValue &value, results) { QJsonObject person = value.toObject(); _markedItems.insert(person["id"].toString()); } QVector<int> roles; roles.append(Qt::FontRole); // We do not keep id -> row mapping, therefore it is easier to emit // data change signal for all items, even if it is not optimal from // the performance point of view. emit dataChanged(index(0), index(rowCount() - 1, columnCount() - 1) , roles); _searchReply = 0; emit searchFinished(); }
Files:
© 2015 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.