Question

If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).

I want to know how to do this to a complex widget as well, for example, an HBox that contains a VBox that contains some Labels.

Ideally this would also include a solution solution that allows me to tint the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.

Was it helpful?

Solution

Example program:

#include <gtk/gtk.h>

static void on_destroy(GtkWidget* widget, gpointer data)
{
        gtk_main_quit ();
}

int main (int argc, char* argv[])
{
        GtkWidget* window;
        GtkWidget* button;

        gtk_init(&argc, &argv);
        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        g_signal_connect(G_OBJECT (window), "destroy",
                G_CALLBACK (on_destroy), NULL);
        button = gtk_button_new_with_label("Hello world!");
        GdkColor red = {0, 0xffff, 0x0000, 0x0000};
        GdkColor green = {0, 0x0000, 0xffff, 0x0000};
        GdkColor blue = {0, 0x0000, 0x0000, 0xffff};
        gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
        gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);
        gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);
        gtk_container_add(GTK_CONTAINER(window), button);
        gtk_widget_show_all(window);
        gtk_main();
        return 0;
}

OTHER TIPS

The best documentation that I know of is the one available here: http://ometer.com/gtk-colors.html

You can always use gtk_widget_override_color () and gtk_widget_override_background_color (). These two functions allow you to change the color of a widget. But it is better to use CSS classes and regions in your widget/container implementation through gtk_style_context_add_class() and gtk_style_context_add_region().

To modify the color of a widget you can initialize a color and use it to modify the color of the widget:

GdkColor color;
gdk_color_parse("#00FF7F", &color);
gtk_widget_modify_bg(widget, GTK_STATE_NORMAL, &color);

To use an image instead of color:

GdkPixbuf *image = NULL;
GdkPixmap *background = NULL;
GtkStyle *style = NULL;

image = gdk_pixbuf_new_from_file ("background.jpg", NULL);
gdk_pixbuf_render_pixmap_and_mask (image, &background, NULL, 0);
style = gtk_style_new ();
style->bg_pixmap [0] = background;

gtk_widget_set_style (GTK_WIDGET(widget), GTK_STYLE (style));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top