这篇我们将学习
Dialog
的信号相关操作。
Signals
例子
#include <gtk/gtk.h>
static GtkWidget *create_window(const gint, const gint);
void response_cb(GtkDialog *dialog, int response_id, GtkWindow *window)
{
if (!GTK_IS_DIALOG(dialog) && !GTK_IS_WINDOW(window))
{
g_print("参数错误\n");
return;
}
switch (response_id)
{
case 1:
g_print("The OK button was clicked\n");
gtk_widget_destroy(GTK_WIDGET(window));
break;
case 2:
g_print("The Cancel button was clicked\n");
gtk_widget_destroy(GTK_WIDGET(dialog));
break;
default:
break;
}
}
void close_cb(GtkDialog *dialog)
{
if (!GTK_IS_DIALOG(dialog))
{
g_print("参数错误\n");
return;
}
g_print("Esc key was pressed\n");
gtk_widget_destroy(GTK_WIDGET(dialog));
}
void button_clicked_cb(GtkWindow *window)
{
GtkWidget *dialog;
/// *** dialog
dialog = gtk_dialog_new();
gtk_window_set_title(GTK_WINDOW(dialog), "Dialog");
gtk_widget_set_size_request(dialog, 200, 300);
gtk_window_set_transient_for(GTK_WINDOW(dialog), window);
gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
/// ***
gtk_dialog_add_buttons(GTK_DIALOG(dialog), "OK", 1, "Cancel", 2, NULL);
/// ***
gtk_dialog_set_default_response(GTK_DIALOG(dialog), 1);
/// *** signals 响应_id
g_signal_connect(dialog, "response", G_CALLBACK(response_cb), window);
/// *** 默认键为Esc,按下后即可触发"close"信号
g_signal_connect_swapped(dialog, "close", G_CALLBACK(close_cb), dialog);
/// ***
gtk_widget_show_all(dialog);
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GtkWidget *window;
GtkWidget *button;
/// *** Create a Window
window = create_window(400, 500);
/// *** Create a button
button = gtk_button_new_with_mnemonic("_Open the dialog");
g_object_set(button,
"margin", 50,
"parent", window,
NULL);
g_signal_connect_swapped(button, "clicked", G_CALLBACK(button_clicked_cb), window);
gtk_widget_show_all(window);
gtk_main();
}
static GtkWidget *create_window(const gint w, const gint h)
{
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_window_set_default_size(GTK_WINDOW(window), w, h);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_title(GTK_WINDOW(window), "Hello GTK3");
gtk_container_set_border_width(GTK_CONTAINER(window), 50);
return window;
}
- 运行效果
点击
Open the dialog
,打开Dialog
点击Cancel
,关闭Dialog
点击OK
或者按下Enter
键关闭整个应用程序
按下Esc
键关闭Dialog