#include <gtk/gtk.h>
enum
{
LIST_ITEM = 0,
LIST_AGE,
N_COLUMNS
};
void init_list(GtkWidget *list)
{
//要念让望图隐示没数据,必需 树立 GtkCellRenderer取GtkTreeViewColumn
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
GtkListStore *store;
//树立 一个GtkCellRenderer
renderer = gtk_cell_renderer_text_new ();
//树立 一个带题目 的列 而且 将renderer搁进个中 使其能隐示内容
column = gtk_tree_view_column_new_with_attributes("List Items", renderer, "text", LIST_ITEM, NULL);
//将列参加 gtk_tree_view
gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
//树立 一个GtkCellRenderer
renderer = gtk_cell_renderer_text_new ();
//g_object_set (G_OBJECT (renderer), "xalign", 一.0, NULL);//居左
//树立 一个带题目 的列 而且 将renderer搁进个中 使其能隐示内容
column = gtk_tree_view_column_new_with_attributes("List age", renderer, "text", LIST_AGE, NULL);
//将列参加 gtk_tree_view
gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
store = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING,G_TYPE_INT);
//联系关系 望图取模子
gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));
//将数据模子 接给望图治理 ,望图烧毁 时数据会被一异烧毁
g_object_unref(store);
}
void add_to_list(GtkWidget *list, const gchar *str ,gint age)
{
GtkListStore *store;
GtkTreeIter iter;
store = GTK_LIST_STORE(gtk_tree_view_get_model
(GTK_TREE_VIEW(list)));
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter, LIST_ITEM, str,LIST_AGE,age, - 一);
}
void on_changed(GtkWidget *widget, gpointer label)
{
GtkTreeIter iter;
GtkTreeModel *model;
gchar *value;
//得到 treeview外选外的一止的GtkTreeIter
if (gtk_tree_selection_get_selected( GTK_TREE_SELECTION(widget), &model, &iter))
{
gtk_tree_model_get(model, &iter, LIST_ITEM, &value, - 一);
gtk_label_set_text(GTK_LABEL(label), value);
g_free(value);
}
}
int main(int argc, char *argv[])
{
GtkWidget *window;
GtkWidget *list;
GtkWidget *vbox;
GtkWidget *label;
GtkTreeSelection *selection;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
list = gtk_tree_view_new();
gtk_window_set_title(GTK_WINDOW(window), "List view");
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_container_set_border_width(GTK_CONTAINER(window), 一0);
gtk_widget_set_size_request(window, 二 七0, 二 五0);
//设置题目 的否睹性状况 。
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), TRUE );
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);//gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), list, TRUE, TRUE, 五);
label = gtk_label_new("");
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 五);
gtk_container_add(GTK_CONTAINER(window), vbox);
init_list(list);
add_to_list(list, "Aliens" , 一0 );
add_to_list(list, "Leon" , 二 );
add_to_list(list, "The Verdict" , 三0 );
add_to_list(list, "North Face" , 四 );
add_to_list(list, "Der Untergang", 五0 );
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
g_signal_connect(selection, "changed",
G_CALLBACK(on_changed), label);
g_signal_connect(G_OBJECT (window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window);
gtk_main();
return 0;