Vala Settings Sample

Requires Vala >= 0.10.0 and GLib/GIO >= 2.26

Create a GSettings schema file for your application settings, with filename extension .gschema.xml, e.g.

  <schema id="" path="/org/example/my-app/" gettext-domain="my-app">

    <key name="greeting" type="s">
      <default l10n="messages">"Hello, earthlings"</default>
      <summary>A greeting</summary>
        Greeting of the invading martians

    <key name="bottles-of-beer" type="i">
      <summary>Bottles of beer</summary>
        Number of bottles of beer on the wall

    <key name="lighting" type="b">
      <summary>Is the light switched on?</summary>
        State of an imaginary light switch.


Install it to a glib-2.0/schemas subdirectory of a XDG_DATA_DIRS directory and recompile all schema files of this directory with glib-compile-schemas:

$ cp /usr/share/glib-2.0/schemas/
$ glib-compile-schemas /usr/share/glib-2.0/schemas/

Compile and run the following demo program:

void main () {
    var settings = new Settings ("");

    // Getting keys
    var greeting = settings.get_string ("greeting");
    var bottles = settings.get_int ("bottles-of-beer");
    var lighting = settings.get_boolean ("lighting");

    print ("%s\n", greeting);
    print ("%d bottles of beer on the wall\n", bottles);
    print ("Is the light switched on? %s\n", lighting ? "yes" : "no");

    // Change notification for any key in the schema
    settings.changed.connect ((key) => {
        print ("Key '%s' changed\n", key);

    // Change notification for a single key
    settings.changed["greeting"].connect (() => {
        print ("New greeting: %s\n", settings.get_string ("greeting"));

    // Setting keys
    settings.set_int ("bottles-of-beer", bottles - 1);
    settings.set_boolean ("lighting", !lighting);
    settings.set_string ("greeting", "hello, world");

    print ("Please start 'dconf-editor' and edit keys in /org/example/my-app/\n");

    new MainLoop ().run ();

Compile and Run

$ valac --pkg gio-2.0 gio-settings-demo.vala
$ ./gio-settings-demo

Start dconf-editor and edit some keys in /org/example/my-app/. On some systems you have to install dconf-editor first, e.g. the dconf-tools package on Debian based distributions.


Projects/Vala/GSettingsSample (last edited 2013-11-22 16:48:26 by WilliamJonMcCann)