QSettings and QML

Suffering from absence of useful QSettings in QML?

Its pretty easy to solve (if you not afraid of some c++ code in your project)

#ifndef SETTINGS_H
#define SETTINGS_H

#include <QObject>
#include <QSettings>

class Settings : public QObject
{
    Q_OBJECT
public:
    explicit Settings(QObject *parent = 0);
    Q_INVOKABLE void setValue(const QString & key, const QVariant & value);
    Q_INVOKABLE QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const;

signals:

public slots:
private:
    QSettings settings_;
};

#endif // SETTINGS_H

 

#include "settings.h"

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

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

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

register it:

    QQmlContext *context = engine->rootContext();
    context->setContextProperty("settings", &settings);

and use:

    FileDialog {
        id: fileDialog
        folder: settings.value("lastFolder", ".")
        onAccepted:  {
            settings.setValue("lastFolder", fileDialog.folder)
        }
    }

pretty easy, eh?