Search code examples
cssgtk3

How to reset the background color of a widget to default state after using gtk_css_provider_load_from_data()


I used to set and reset background colors of widgets via gtk_widget_override_background_color. This function is now deprecated, so I'd like to switch to using GtkCssProvider.

I know that I can change the background color of an entry field with for example

GtkCssProvider *provider = gtk_css_provider_new ();
gtk_css_provider_load_from_data (provider,
".entry { background: #927373}", -1, NULL);
gtk_style_context_add_provider (gtk_widget_get_style_context (entry_field),
GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

That's working fine. However, as before, under certain circumstances I'd like to revert the background color to default state. Using

provider = gtk_css_provider_get_default ();
gtk_style_context_add_provider (gtk_widget_get_style_context (entry_field),
GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

doesn't have any effect, and using

gtk_css_provider_load_from_data (provider,
".entry { background: #none}", -1, NULL);

is not the right way, since there is a default background color in the widget (for example white (dependent on the theme), and after using background: #none it will be grey).

How can I achieve resetting to default color without using deprecated functions?


Solution

  • I have solved this via adding and removing a class:

    GtkStyleContext *context = gtk_widget_get_style_context (entry);
    

    adding:

    gtk_style_context_add_class (context, "newclass");
    gtk_css_provider_load_from_data (provider, 
    ".entry.newclass { background: #927373}", -1, NULL);
    

    removing:

    gtk_style_context_remove_class (context, "newclass");