Namespaces
Variants
Actions
Revision as of 18:42, 8 May 2012 by lildeimos (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Using QSettings in QML with also json and XML support

Jump to: navigation, search

This article explains how to use settings in QML

Article Metadata

Tested with
SDK: Nokia Qt SDK 1.2.1
Devices(s): all

Compatibility
Platform(s): all
Device(s): all

Article
Keywords: QSettings
Created: lildeimos (09 May 2012)
Last edited: lildeimos (08 May 2012)

Contents

Introduction

This class is used as a context property in QML applications as an easy way to store and get user settings. It supports storing arrays. These can also retrieved in json or xml format.

Usage

Start copying setting.cpp and setting.h into your project source directory. In the main.cpp file include the .h:

#include "setting.h"

the register the context property

Settings settings(appName, fileName);
viewer.rootContext()->setContextProperty("settings", &settings);

fileName will be create as follow:

QDesktopServices::storageLocation( QDesktopServices::DataLocation ) + "/" + appName + "/" + fileName;

In your QML sources you will now be able to use the property settings in ini format as explained below.

single settings

The ini format is likely as:

[main]
user=Marco
location=Italy
...

so to write a new value or overwrite the existing just put in your qml this

settings.setValue("main/user", "Marco");

to get a value:

var user;
user = settings.getValue("main/user");

if you want to have a default value if there is not yet a setting named "main/user", do:

var user;
user = settings.getValue("main/user", "Marco");

if "main/user" exist it will return that value, else will return "Marco".


array settings

The ini format for arrays is likely as:

[main]
user/size=2
user/1/name=Marco
user/1/location=Italy
user/2/name=Marco2
user/2/location=Italy2
...

appendToArray

to make this in your qml just use:

settings.appendToArray( "main/user", { "name": "Marco" , "location": "Italy" });
settings.appendToArray( "main/user", { "name": "Marco2" , "location": "Italy2" });

removeArray

to remove the whole array:

settings.removeArray( "main/user");

removeArrayEntry

to remove a single entry of the array:

settings.removeArrayEntry( "main/user", 1);

getIndexOfValueInArray

this will get the index settings.getIndexOfValueInArray("favourites/place", "name", value);

325 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved