En inställningsdialog

Ett typiskt program kommer ha några inställningar som ska kommas ihåg från en körning till den andra. Även för vårt enkla exempelprogram kan vi vilja ändra typsnittet som används för innehållet.

We are going to use Gio::Settings to store our preferences. Gio::Settings requires a schema that describes our settings, in our case the org.gtkmm.exampleapp.gschema.xml file.

Before we can make use of this schema in our application, we need to compile it into the binary form that Gio::Settings expects. GIO provides macros to do this in autotools-based projects. See the description of GSettings. Meson provides the compile_schemas() function in the GNOME module.

Next, we need to connect our settings to the widgets that they are supposed to control. One convenient way to do this is to use Gio::Settings::bind() to bind settings keys to object properties, as we do for the transition setting in ExampleAppWindow's constructor.

m_settings = Gio::Settings::create("org.gtkmm.exampleapp");
m_settings->bind("transition", m_stack->property_transition_type());

The code to connect the font setting is a little more involved, since it corresponds to an object property in a Gtk::TextTag that we must first create. The code is in ExampleAppWindow::open_file_view().

auto tag = buffer->create_tag();
m_settings->bind("font", tag->property_font());
buffer->apply_tag(tag, buffer->begin(), buffer->end());

At this point, the application will already react if you change one of the settings, e.g. using the gsettings commandline tool. Of course, we expect the application to provide a preference dialog for these. So lets do that now. Our preference dialog will be a subclass of Gtk::Window, and we'll use the same techniques that we've already seen in ExampleAppWindow: a Gtk::Builder ui file and settings bindings. In this case the bindings are more involved, though. We use Gtk::FontDialogButton and Gtk::DropDown in the preference dialog. The types of the properties in these classes can't be automatically converted to the string type that Gio::Settings requires.

When we've created the prefs.ui file and the ExampleAppPrefs class, we revisit the ExampleApplication::on_action_preferences() method in our application class, and make it open a new preference dialog.

auto prefs_dialog = ExampleAppPrefs::create(*get_active_window());
prefs_dialog->present();

Efter allt detta arbete kan vårt program nu visa en sådan här inställningsdialog:

En inställningsdialog

Källkod