GtkLabel是少数的几个不创建自己的窗口的GTK+控件之一.相反,它直接的将自己画在父控件上.这就是说:如果你想为GtkLabel控件设置背景,你需要改变它的父控件的的背景.

    这是GTK+ FAQ 中"6.10. 如何给GtkLabel控件设置背景颜色?"给出的解释。一般情况下设置某个GtkWidget的背景都用一般情况下用函数 gtk_widget_modify_bg()。注意在gtk_widget_modify_bg()函数的说明里有一段话:

Note that "no window" widgets (which have the GTK_NO_WINDOW flag set) draw on their parent container's window and thus may not draw any background themselves. This is the case for e.g. GtkLabel. To modify the background of such widgets, you have to set the background color on their parent; if you want to set the background of a rectangular area around a label, try placing the label in a GtkEventBox widget and setting the background color on that.

    其实这已经告诉了我们如何设置“无窗口”widgets背景颜色的方法:将GtkLabel包含在GtkEventBox里,然后用函数gtk_widget_modify_bg()设置GtkEventBox的背景。

    设置GtkLabel的字体颜色用gtk_widget_set_markup()函数,该函数的第二个参数是一个markup string,详见Pango reference manual里PangoMarkupFormat的Pango Text Attribute Markup Language。以下为代码实现,仅供参考:




文件名:gtk-set-color.c




​#include <gtk/gtk.h>

gchar * _(gchar *string);

int main(int argc, char *argv[])
{
    GtkWidget *window, *event_box, *label;
    GdkColor color;

    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_container_set_border_width(GTK_CONTAINER(window), 10);
    
    g_signal_connect(G_OBJECT(window), "destroy",
            G_CALLBACK(gtk_main_quit), NULL);

    event_box = gtk_event_box_new();
    gtk_container_add(GTK_CONTAINER(window), event_box);
    color.red = 0xffff;
    color.green = 0xffff;
    color.blue = 0xffff;    
    /* 设置GtkEventBox的背景颜色为白色 */
    gtk_widget_modify_bg(event_box,GTK_STATE_NORMAL, &color);
    
    label = gtk_label_new(NULL);
    /* 设置GtkLabel的字体颜色为红色 */
    gtk_label_set_markup(GTK_LABEL(label), \
        _("GtkLabel白色背景红色字体"));
    gtk_widget_set_size_request(label, 300, 200);
    /* GtkEventBox为包含GtkLabel的父window */
    gtk_container_add(GTK_CONTAINER(event_box), label);
    


    gtk_widget_show_all(window);

    gtk_main();

    return 0;
}

/* 支持中文显示 */
gchar *
_(gchar *string)
{
    return(g_locale_to_utf8(string, -1, NULL, NULL, NULL));
}



[root@localhost Desktop]# gcc gtk-set-color.c -o gtk-set-color  `pkg-config --cflags  --libs  gtk+-2.0 `

[root@localhost Desktop]# ./gtk-set-color


   显示效果如下:

500)this.width=500;" border="0">。


这里再转载一下GTKSCORLLEDWINDOW背景修改的方法:

直接通过下面的方式是无法改变GtkScrolledWindow背景色的:




​ 1. GdkColor white;
   2. gdk_color_parse ("WHITE", &white);
   3. gtk_widget_modify_bg (scrolledWindow, GTK_STATE_NORMAL, &white); ​


必须连GTKVIEWPORT的背景也同时改变:



​ 1. const char scroll_style[] =
   2. "style \"view-scroll\" {"
   3. " bg[NORMAL] = \"#FFFFFF\""
   4. "}"
   5. "class \"GtkViewport\" style \"view-scroll\""
   6. "class \"GtkScrolledWindow\" style \"view-scroll\"";
   7. gtk_rc_parse_string (scroll_style); ​



 TAG

​GTK+​

​GtkLabel​

​背景颜色​



​​​​​​​​​​​​​​​​​​​​​​