下面演示了如何在窗口中增加一個按鈕,示例代碼均有注釋
#include
static void print_hello (GtkWidget *widget,gpointer data)
{
//這是一個回調函數,這個data表示傳給回調函數的參數。
g_print ("你好,世界\n");
}
static gboolean on_delete_event (GtkWidget *widget,GdkEvent *event,gpointer data)
{
//如果返回FALSE在delete_event信號處理中,GTK將發送destroy信號,否則不會,這樣窗口就不會關閉。
g_print ("delete event occurred\n");
return TRUE;
}
int main (int argc,char *argv[])
{
GtkWidget *window;
GtkWidget *button;
//初始化gtk應用程序
gtk_init (&argc, &argv);
//創造新的窗口,設置它的標題
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "你好");
//將delete_event信號綁定在on_delte_devent回調函數上,傳遞的參數為NULL
g_signal_connect (window, "delete-event", G_CALLBACK (on_delete_event), NULL);
//將destroy信號綁定在gtk_main_quit回調函數上,傳遞的參數為NULL
g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
//設置窗口的邊框寬度
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
//創建一個新的標簽
button = gtk_button_new_with_label ("Hello World");
//處理按鈕的clicked信號
g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);
//g_signal_connect_swapped將clicked信號連接到window窗口的gtk_widget_destroy事件中。
g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);
//將按鈕加入到容器中
gtk_container_add (GTK_CONTAINER (window), button);
//顯示這個按鈕
gtk_widget_show (button);
//顯示窗口
gtk_widget_show (window);
//開始GTK的主循環
gtk_main ();
return 0;
}
在XMANGER下用VIM編寫好後,編譯運行