gtk3 set scrolledwindow transparency and button text color, button default icon

⌚Time: 2026-03-25 15:25:00

👨‍💻Author: Jack Ge

Set GtkScrolledWindow background to transparent

The area inside GtkScrolledWindow has a white background. I want it to have a transparent background to show the window's background image.

At first, I directly set the CSS class of GtkScrolledWindow, and then set its background color to transparent in the CSS.

gtk_style_context_add_class(gtk_widget_get_style_context(g_cardListScrolledWindow),  "test-scrolled-window");
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(g_cardListScrolledWindow),g_cardListBox);
.test-scrolled-window{
    background-color: rgba(0,0,0,0);
}

But this doesn’t work. Because I found that the scrolled window contains a viewport, and it is the style of the viewport that needs to be set. So I created a new viewport myself and then set its style.

GtkWidget *viewPort = gtk_viewport_new(NULL,NULL);
gtk_style_context_add_class(gtk_widget_get_style_context(viewPort),  "test-viewport");
gtk_container_add(GTK_CONTAINER(g_cardListScrolledWindow),viewPort);
gtk_container_add(GTK_CONTAINER(viewPort),g_cardListBox);
.test-viewport{
    background-color: rgba(0,0,0,0);
}

This allows the background inside the scrolled window to be transparent.

Button text color

Create a button with a default label

g_resetBtn = gtk_button_new_with_label("restart");
gtk_style_context_add_class(gtk_widget_get_style_context(g_resetBtn),  "test-button");

At first, I thought that to change the text color of a GtkButton, all I needed to do was set the color property in the GtkButton's CSS style. But it didn’t work.

.test-button{
    color:#152F4F;
    font: Consolas 12;
}

Later I realized that what needed to be set was the style of the label inside the GtkButton. You need to create a new label yourself and add it to the button.

g_resetBtn = gtk_button_new();
colorLabel = gtk_label_new("restart");
gtk_style_context_add_class(gtk_widget_get_style_context(colorLabel),  "test-button-label");
gtk_container_add(GTK_CONTAINER(g_resetBtn),colorLabel);
    
.test-button-label{
    color:#152F4F;
    font: Consolas 12;
}

This way, you can set the text color of the button.

Button add GTK default icon

The method is to use a horizontal container to hold the image and text. Add it into a GtkButton. Use the gtk_image_new_from_stock function to retrieve GTK's default icons.


GtkWidget *hBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL,0);
gtk_container_add(GTK_CONTAINER(g_resetBtn),hBox);

GtkWidget *btnImage = gtk_image_new_from_stock("gtk-refresh", GTK_ICON_SIZE_BUTTON);
gtk_box_pack_start(GTK_BOX(hBox),btnImage,false,false,0);
   
GtkWidget *colorLabel = gtk_label_new("Restart");
gtk_box_pack_start(GTK_BOX(hBox),colorLabel,false,false,0);

This allows the button to display with the default icon.