In creating custom widgets sometimes I need to define my own CSS. This should be read with GTK_STYLE_PROVIDER_PRIORITY_THEME
, as they are general-purpose widgets that are not tied to any specific application.
Unfortunately I find it impossible to style a GtkButton
properly without using GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
. Something from either libadwaita
or GTK
(or I don’t know what else) overrides several properties that I am trying to declare.
It also seems that the CSS parser is blind to CSS specificity, and if I use as selector something like button.myclass:not(.one):not(.two):not(.three)
nothing changes.
To show what I mean, the following code does not style the example button properly.
test.c:
#include <gtk/gtk.h>
static void on_app_activate (
GtkApplication * app,
gpointer user_data G_GNUC_UNUSED
) {
GtkCssProvider * const app_css_provider = gtk_css_provider_new();
GFile * const css_file =
g_file_new_for_path("style.css");
gtk_css_provider_load_from_file(app_css_provider, css_file);
gtk_style_context_add_provider_for_display(
gdk_display_get_default(),
GTK_STYLE_PROVIDER(app_css_provider),
GTK_STYLE_PROVIDER_PRIORITY_THEME
);
g_object_unref(app_css_provider);
g_object_unref(css_file);
GtkWidget
* const window = gtk_application_window_new(app),
* const my_headerbar = gtk_header_bar_new(),
* const my_titlebox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0),
* const my_titlelabel = gtk_label_new("My app"),
* const my_subtitlelabel = gtk_label_new("Just some app"),
* const my_button = g_object_new(
GTK_TYPE_BUTTON,
"label", "Test",
"valign", GTK_ALIGN_CENTER,
"halign", GTK_ALIGN_CENTER,
NULL
);
gtk_widget_add_css_class(my_titlelabel, "title");
gtk_widget_add_css_class(my_subtitlelabel, "subtitle");
gtk_widget_set_valign(my_titlebox, GTK_ALIGN_CENTER);
gtk_box_append(GTK_BOX(my_titlebox), my_titlelabel);
gtk_box_append(GTK_BOX(my_titlebox), my_subtitlelabel);
gtk_header_bar_set_title_widget(
GTK_HEADER_BAR(my_headerbar),
my_titlebox
);
gtk_window_set_titlebar(GTK_WINDOW(window), my_headerbar);
gtk_window_set_default_size(GTK_WINDOW(window), 600, 400);
gtk_widget_add_css_class(my_button, "myclass");
gtk_window_set_child(GTK_WINDOW(window), my_button);
gtk_widget_show(window);
}
int main (
int argc,
char ** argv
) {
int status;
GtkApplication * app = gtk_application_new(
"org.gtk.example",
G_APPLICATION_DEFAULT_FLAGS
);
g_signal_connect(app, "activate", G_CALLBACK(on_app_activate), NULL);
status = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return status;
}
style.css:
button.myclass {
background: transparent;
border-radius: 0 24px 24px 0;
font-family: monospace;
font-size: 18px;
border: none;
padding: 0 6px 0 0;
}
This is how the button should be styled:
(it works if I use GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
)
This is how the button is actually styled:
―madmurphy