主要是参考gtk3-demo中combo boxes例子中的源代码来改写而成的,源代码篇幅很长的,我也是用A4纸打印出来反复看才阅读明白,其实也不完全明白 以下gtk+编程例子是来自书籍《实用技术:开发Linux应用——用GTK+和GDK开发Linux图形用户界面应用》第60页的内容——复合框,创建数据库store的方法与第56页的gtk+编程例子——列表框的写法一样,区别就是多了这个函数gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, TRUE),就是combo_box本身就是一个容器 在openSUSE-Leap-15.3-DVD-x86_64的gnome3.34.7桌面环境下编译的,其中pkg-config --cflags --libs gtk±3.0两边有反引号括起来的 ruhong@localhost:~/gtk> gcc page60.c -o page56 pkg-config --cflags --libs gtk±3.0 ruhong@localhost:~/gtk> ./page60
#include <gtk/gtk.h>
enum
{
DISTRICT,
NUM_COLUMNS
};
static GtkTreeModel *create_and_fill_model (void)
{
GtkListStore *store;
GtkTreeIter iter;
store=gtk_list_store_new (1, G_TYPE_STRING);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "越秀区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "荔湾区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "海珠区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "天河区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "白云区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "黄埔区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "番禺区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "花都区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "南沙区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "增城区", -1);
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter, DISTRICT, "从化区", -1);
return GTK_TREE_MODEL (store);
}
int main( int argc, char *argv[] )
{
GtkWidget *window;
GtkWidget *combo;
GtkTreeModel *model;
GtkCellRenderer *renderer;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "广州市有11个区你在那个区?");
g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 100);
model = create_and_fill_model ();
combo = gtk_combo_box_new_with_model (model);
g_object_unref (model);
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), renderer, "text", DISTRICT, NULL);
gtk_container_add (GTK_CONTAINER (window), combo);
gtk_widget_show (combo);
gtk_widget_show (window);
gtk_main ();
return 0;
}
效果图如下
|