#include <gtk/gtk.h>
enum
{
LIST_ITEM = 0,
N_COLUMNS
};
void init_list(GtkWidget *list)
{
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
renderer = gtk_cell_renderer_text_new();
column = gtk_tree_view_column_new_with_attributes("TreeView in TreeView Mode",renderer, "text", LIST_ITEM, NULL);
gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
}
void init_data(GtkWidget *list)
{
GtkTreeStore *store;
GtkTreeIter toplevel, child;
store = gtk_tree_store_new(N_COLUMNS,G_TYPE_STRING);
gtk_tree_store_append(store, &toplevel, NULL);
gtk_tree_store_set(store, &toplevel,LIST_ITEM, "users",-1);
gtk_tree_store_append(store, &child, &toplevel);
gtk_tree_store_set(store, &child,LIST_ITEM, "fishc",-1);
gtk_tree_store_append(store, &child, &toplevel);
gtk_tree_store_set(store, &child,LIST_ITEM, "g0398",-1);
gtk_tree_view_set_model(GTK_TREE_VIEW(list),GTK_TREE_MODEL(store));
}
void selection_changed(GtkTreeSelection *selection, gpointer user_data)
{
GtkTreeIter iter;
GtkTreeModel *model;
char *value;
if (gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection), &model, &iter))
{
gtk_tree_model_get(model, &iter, LIST_ITEM, &value, -1);
g_print("select item is: %s\n", value);
g_free(value);
}
}
int main(int argc,char *argv[ ])
{
GtkWidget *window,*list;
GtkTreeSelection *selection;
gtk_init(&argc,&argv);
window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"hello fishc - TreeView");
gtk_widget_set_size_request(GTK_WIDGET(window),300,200);
list = gtk_tree_view_new();
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), TRUE);
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
g_signal_connect(selection, "changed", G_CALLBACK(selection_changed), NULL);
init_list(list);
init_data(list);
gtk_container_add(GTK_CONTAINER(window), list);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
和上节的代码一样,只是Model变了而已,MVC模式的特性体现出来了。主要看 init_data函数,这个函数用来设置View关联的Model。