SettingsStorage.cpp Example File
persistentobjects/src/SettingsStorage.cpp
#include "SettingsStorage.hpp"
#include "Person.hpp"
const QString SettingsStorage::m_author = "Example Inc.";
const QString SettingsStorage::m_appName = "PersistentObjectApp";
const QString SettingsStorage::m_personListSettingsKey = "PersonList";
const QString SettingsStorage::m_lastCustomerIDKey = "PersonList_LastCustomerID";
const QString SettingsStorage::m_customerIDKey = "customerID";
const QString SettingsStorage::m_firstNameKey = "firstName";
const QString SettingsStorage::m_lastNameKey = "lastName";
SettingsStorage::SettingsStorage()
{
}
SettingsStorage::~SettingsStorage()
{
}
int SettingsStorage::load(int& lastID, GroupDataModel *model)
{
int loadedCount = 0;
QSettings settings(m_author, m_appName);
lastID = settings.value(m_lastCustomerIDKey, 0).toInt();
const int personCount = settings.beginReadArray(m_personListSettingsKey);
for (int i = 0; i < personCount; i++) {
settings.setArrayIndex(i);
Person *p;
if (loadPerson(settings, p)) {
model->insert(p);
loadedCount++;
} else {
break;
}
}
settings.endArray();
return loadedCount;
}
bool SettingsStorage::clear()
{
QSettings settings(m_author, m_appName);
settings.clear();
return true;
}
bool SettingsStorage::save(int lastID, GroupDataModel *model)
{
QSettings settings(m_author, m_appName);
settings.setValue(m_lastCustomerIDKey, lastID);
settings.beginWriteArray(m_personListSettingsKey);
for (int i = 0; i < model->size(); i++) {
settings.setArrayIndex(i);
Person *person = (Person *) model->children()[i];
settings.setValue(m_customerIDKey, person->customerID());
settings.setValue(m_firstNameKey, person->firstName());
settings.setValue(m_lastNameKey, person->lastName());
}
settings.endArray();
return true;
}
bool SettingsStorage::loadPerson(const QSettings& settings, Person*& person) const
{
bool loaded = false;
if (settings.contains(m_customerIDKey) && settings.contains(m_firstNameKey)
&& settings.contains(m_lastNameKey)) {
person = new Person();
person->setCustomerID(settings.value(m_customerIDKey).toString());
person->setFirstName(settings.value(m_firstNameKey).toString());
person->setLastName(settings.value(m_lastNameKey).toString());
loaded = true;
} else {
return false;
}
return (loaded && person);
}