GtkLabel


到目前為止一直在用的GtkLabel,其實可以設定更多的樣式,例如簡單的標記(markup)、換行、對齊、自動換行等。

要設定標記可以使用gtk_label_set_markup()函式,要設定換行,可以使用'\n'來斷行,或是使用 gtk_label_set_line_wrap()設定依容器寬度自動換行,要設定對齊可以使用gtk_label_set_justify(),預設 是置中對齊,可以設定的值包括了:
  • GTK_JUSTIFY_CENTER:置中對齊(預設)
  • GTK_JUSTIFY_LEFT:靠左對齊
  • GTK_JUSTIFY_RIGHT:靠右對齊
  • GTK_JUSTIFY_FILL:左右對齊

以下使用一個程式實例,來看看設定過程與執行後的效果:
  • gtk_label_demo.c
#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *vbox;
GtkWidget *frame;
GtkWidget *label;

gtk_init(&argc, &argv);

window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "GtkLabel");
gtk_window_set_default_size(GTK_WINDOW(window), 400, 400);

vbox = gtk_vbox_new(FALSE, 5);

frame = gtk_frame_new("簡單標記");
label = gtk_label_new(NULL);
gtk_label_set_markup(GTK_LABEL(label),
"<span foreground='blue' size='x-large'>良葛格學習筆記</span>");
gtk_container_add(GTK_CONTAINER(frame), label);
gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);

frame = gtk_frame_new("多行");
label = gtk_label_new("良葛格學習筆記\ncaterpillar.onlyfun.net\n" \
"Gossip@Openhome");
gtk_container_add(GTK_CONTAINER(frame), label);
gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);

frame = gtk_frame_new("自動換行");
label = gtk_label_new("You might think you know but actually you don't. " \
"You might think you know but actually you don't. " \
"You might think you know but actually you don't. " \
"You might think you know but actually you don't.");
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
gtk_container_add(GTK_CONTAINER(frame), label);
gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);

frame = gtk_frame_new("靠右對齊");
label = gtk_label_new("良葛格學習筆記\ncaterpillar.onlyfun.net\n" \
"Gossip@Openhome");
gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_RIGHT);
gtk_container_add(GTK_CONTAINER(frame), label);
gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);

frame = gtk_frame_new("自動換行、左右對齊");
label = gtk_label_new("You might think you know but actually you don't. " \
"You might think you know but actually you don't. " \
"You might think you know but actually you don't. " \
"You might think you know but actually you don't.");
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_FILL);
gtk_container_add(GTK_CONTAINER(frame), label);
gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0);

gtk_container_add(GTK_CONTAINER(window), vbox);

g_signal_connect(GTK_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);

gtk_widget_show_all(window);

gtk_main();

return 0;
}

執行結果如下所示: