Search code examples
comboboxgtk3

Using default color for combo box cell layout renderer with GTK >=3.16


I use a combobox whose items are dynamically created, the same goes for headlines inside the combobox in black which might or might not appear, depending on the current choice. It looks like this:

enter image description here

The code for the cell layout renderer is this (just for the concept, the details are not of interest for my following question):

void option_list_with_headlines
(G_GNUC_UNUSED GtkCellLayout *cell_layout, 
GtkCellRenderer *action_option_combo_box_renderer, 
GtkTreeModel *action_option_combo_box_model, 
GtkTreeIter *action_option_combo_box_iter, 
G_GNUC_UNUSED gpointer data) {
  gchar *action_option_combo_item;
  GdkRGBA normal_fg_color, normal_bg_color;

  gboolean headline;

  gtk_style_context_get_color (gtk_widget_get_style_context (action_option),
  GTK_STATE_NORMAL, &normal_fg_color);
  gtk_style_context_get_background_color (gtk_widget_get_style_context
  (action_option), GTK_STATE_NORMAL, &normal_bg_color);

  gtk_tree_model_get (action_option_combo_box_model,
  action_option_combo_box_iter, ACTION_OPTION_COMBO_ITEM,
  &action_option_combo_item, -1);

  headline = g_regex_match_simple ("Add|Choose", 
  action_option_combo_item, G_REGEX_ANCHORED, 0);

  g_object_set (action_option_combo_box_renderer, 
  "foreground-rgba", (headline) ? &((GdkRGBA) { 1.0, 1.0, 1.0, 1.0 }) :
  &normal_fg_color, "background-rgba"
  (g_str_has_prefix(action_option_combo_item, "Choose")) ? 
  &((GdkRGBA) { 0.31, 0.31, 0.79, 1.0 }) : 
  ((g_str_has_prefix (action_option_combo_item, "Add")) ? 
  &((GdkRGBA) { 0.0, 0.0, 0.0, 1.0 }) : &normal_bg_color),
  "sensitive", !headline, NULL);

  // Cleanup
  g_free (action_option_combo_item);
}

Now my question regarding this function:

From Gtk >=3.16 on I am no longer supposed to use gtk_style_context_get_background_color. But what can I do to set a color to default in a combo box item list then, like I do with "Name" and "Prompt" in the image above? Currently I use g_object_set together with the color I've gathered with gtk_style_context_get_background_color and GTK_STATE_NORMAL as a parameter.


Solution

  • The solution has turned out to be quite simple: I don't have to retrieve the default background color at all; it is enough to set the value for background-rgba to NULL when using g_object_set:

    g_object_set (action_option_combo_box_renderer, "background-rgba", NULL, ...)
    

    I didn't know that this is possible; I assumed that background-rgba always needs some kind of value.