Color Scheme
Setting a dark or light style for your app
elementary OS ships with two styles for app widgets: a dark style and a light style. By default, your app will use the light style, but by using Gtk.Settings and Granite.Settings you can choose to always use a dark style or to follow the user's preference.

Setting a Dark Style

A dark styled app
Some apps, like photo or video editors, benefit from reducing the contrast between their content and the app's UI by always choosing to be displayed using a dark style. You can set the dark style for your app by using Gtk.Settings and setting the property gtk_application_prefer_dark_theme. In your Application class, add the following lines to your activate function:
1
protected override void activate () {
2
var gtk_settings = Gtk.Settings.get_default ();
3
gtk_settings.gtk_application_prefer_dark_theme = true;
4
}
Copied!
Here, we get the default Gtk.Settings object and then we set this property to instruct GTK to use the dark style. Build your app and run it and notice that it now uses a dark style instead of a light style.

Using The User's Preference

Many apps will be usable in either a light or dark style. In this case, apps should respect the user's style preference and adapt when it is changed.
First, make sure you've included Granite in the build dependencies declared in your meson.build file:
1
executable(
2
meson.project_name(),
3
'src/Application.vala',
4
dependencies: [
5
dependency('granite'),
6
dependency('gtk+-3.0')
7
],
8
install: true
9
)
Copied!
Now, you can read and respond to the user's style preference with Granite.Settings and then use Gtk.Settings to set it in your app's activate function.
1
protected override void activate () {
2
// First we get the default instances for Granite.Settings and Gtk.Settings
3
var granite_settings = Granite.Settings.get_default ();
4
var gtk_settings = Gtk.Settings.get_default ();
5
6
// Then, we check if the user's preference is for the dark style and set it if it is
7
gtk_settings.gtk_application_prefer_dark_theme = granite_settings.prefers_color_scheme == Granite.Settings.ColorScheme.DARK;
8
9
// Finally, we listen to changes in Granite.Settings and update our app if the user changes their preference
10
granite_settings.notify["prefers-color-scheme"].connect (() => {
11
gtk_settings.gtk_application_prefer_dark_theme = granite_settings.prefers_color_scheme == Granite.Settings.ColorScheme.DARK;
12
});
13
}
Copied!
Last modified 15d ago