How to change the colors of an arbitrary widget in GTK +?

If I write an application that wants to convey some information using color, how do I change the background and foreground color of this widget? I would like to know how to do this in a clearing, if possible, as well as programmatically (for the calculated color).

I want to know how to do this for a complex widget, for example, HBox , which contains a VBox , which contains some Labels .

Ideally, it will also be a solution to the problem, which allows me to display a widget of existing colors and determine the average colors of any images used by the theme, so that I can programmatically compensate for any color solutions that can make the text unreadable or otherwise collide - but I would happy if he could just turn the button in red.

+4
source share
4 answers

Program Example:

 #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; } 
+8
source

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

+2
source

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

+1
source

To change the color of the widget, you can initialize the color and use it to change 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)); 
+1
source

Source: https://habr.com/ru/post/1276911/


All Articles