GTK: set default button for dialog

It seems that GtkDialog automatically sets focus to the left-most button (in my case, it is “Cancel”). I want to change this focus by default to another button, but I cannot go through the "gtk_dialog_set_default_response" route, because I manually packed the buttons into the scope of the dialog box.

Then, by searching the API document up and down, I realized that GtkDialog is a descendant of GtkWindow and thus tried "gtk_window_set_default", which first gave me some kind of "warning" gtk_widget_get_can_default (default_widget) "failed", To match, I used "gtk_widget_set_can_default" on the button and the warning disappeared. BUT: the focus is still set to the Cancel button.

Is there no way at all to use gtk_dialog_add_action_widget?

+4
source share
1 answer

Just use the gtk_widget_grab_focus widget that you want to focus on. The widget must be customizable, which by default is true in the case of a button. Here is a sample code for your reference:

 #include <gtk/gtk.h> /* Uncomment the below macro to see the default focus */ //#define DEFAULT_FOCUS int main(void) { gtk_init (NULL, NULL); #ifdef DIALOG_WITH_BUTTONS GtkWidget * dialog = gtk_dialog_new_with_buttons ("Dialog", NULL, GTK_DIALOG_MODAL, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); #ifndef DEFAULT_FOCUS gtk_widget_grab_focus(gtk_dialog_get_widget_for_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK)); #endif #else GtkWidget *dialog = gtk_dialog_new(); gtk_window_set_title(GTK_WINDOW(dialog), "Dialog"); GtkWidget *action_area = gtk_dialog_get_action_area(GTK_DIALOG(dialog)); GtkWidget *ok_button = gtk_button_new_with_label("OK"); GtkWidget *cancel_button = gtk_button_new_with_label("Cancel"); gtk_container_add(GTK_CONTAINER(action_area), cancel_button); gtk_container_add(GTK_CONTAINER(action_area), ok_button); gtk_widget_show_all(dialog); #ifndef DEFAULT_FOCUS gtk_widget_grab_focus(ok_button); #endif #endif g_signal_connect(dialog, "destroy", G_CALLBACK(gtk_main_quit), NULL); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_main(); return 0; } 

Hope this helps!

+3
source

Source: https://habr.com/ru/post/1389282/


All Articles