How to use QSettings in QML blackberry 10

913 Views Asked by At

I am doing login functionality in my mobile application. and you know we have to save some data in our mobile phone when we do login.

my total program is in QML and i want to save some data locally in my phone. I am unable to find any sample code through which i can see how to use QSettings inside our QML

please let me know if you are unable to understand my problem.

2

There are 2 best solutions below

0
On

Even though QSettings inherits QObject it is not really structured for use in the declarative portions of a QML file. A short walk through the results of a Google search tend to confirm my thoughts which is to create a custom C++ object that handles the interface with QSettings.

0
On

The simplest solution I've found is to create a subclass of QSettings, adding Q_INVOKABLE to the methods I want to call from QML. I then place an instance of this class in the QML context.

Here's how it looks in code.

In settings.hpp:

#ifndef Settings_HPP
#define Settings_HPP
#include <QSettings>
class Settings: public QSettings
{
    Q_OBJECT
public:
    Settings(QObject *parent = 0);
    Q_INVOKABLE QVariant value(const QString& key, const QVariant& defaultValue = QVariant()) const;
    Q_INVOKABLE void setValue(const QString& key, const QVariant& value);
};
#endif

In settings.cpp:

#include "settings.hpp"

Settings::Settings(QObject *parent)
    : QSettings(parent)
{
}

QVariant Settings::value(const QString& key, const QVariant& defaultValue) const
{
    return QSettings::value(key, defaultValue);
}

void Settings::setValue(const QString& key, const QVariant& value)
{
    QSettings::setValue(key, value);
}

And of course where ever you create your QmlDocument instance (applicationui.cpp in my case), you would add:

#include "settings.hpp"
...
qml->setContextProperty("settings", new Settings());

From the QML code, I can then do things like:

ToggleButton {
    checked: settings.value('somekey')
    onCheckedChanged: {
        settings.setValue('somekey', checked);
}