Gtk 新手入门须知
参考网站
官网下载:GTK(window
+linux
)
官网参考文档:GTK 3.0 (重点参考demo)
Linux自定gtk2.0,安装gtk3.0后指定库版本。
编译命令:gcc gtk_example.c -o gtk_example `pkg-config --libs --cflags gtk+-3.0`
较大工程建议采用cmake
构建工具
基本要素
界面设计采用glade工具进行图形化设计,生成’.glade’后缀文件,通过gtkbuilder
模块加载,
static gboolean init_builder(GtkBuilder **builder, const GString* path)
{
GError *error = NULL;
*builder = gtk_builder_new();
if (gtk_builder_add_from_file(*builder, path->str, &error) == 0) {
g_warning("cannot load buider file:%s",error->message);
g_clear_error (&error);
return FALSE;
}
return TRUE;
}
界面的样式通过加载css
文件,代码如下:
static void set_css(GtkWidget *widget)
{
GtkStyleProvider *provider= GTK_STYLE_PROVIDER (gtk_css_provider_new ());
gtk_css_provider_load_from_path(GTK_CSS_PROVIDER(provider), g_css_path, NULL);
gtk_style_context_add_provider (gtk_widget_get_style_context (widget), provider, G_MAXUINT);
if (GTK_IS_CONTAINER (widget)) {
gtk_container_forall (GTK_CONTAINER (widget), (GtkCallback) set_css, provider);
}
}
自定义无边框对话框且可移动,代码如下:
gboolean on_mouse_left_button_press (GtkWidget* widget, GdkEventButton * event, GdkWindowEdge edge)
{
if (event->type == GDK_BUTTON_PRESS) {
if (event->button == 1) {
gtk_window_begin_move_drag(GTK_WINDOW(gtk_widget_get_toplevel(widget)), event->button, event->x_root,event->y_root, event->time);
}
}
return FALSE;
}
static gboolean init_window(GtkWidget** window, GtkBuilder* builder)
{
*window = GTK_WIDGET(gtk_builder_get_object(builder , "window"));
if (*window == NULL) {
return FALSE;
}
gtk_widget_set_name (*window, "window" );
gtk_widget_add_events(*window, GDK_BUTTON_PRESS_MASK);
g_signal_connect(G_OBJECT(*window), "button-press-event", G_CALLBACK(on_mouse_left_button_press), NULL);
return TRUE;
}