user9889635
user9889635

Reputation: 123

How do I unfocus all other widgets in GTK when I click on a widget?

In my GTK program I have a TextEntry widget and a TreeView widget. When I click on the TextEntry widget and select some text, then click on the TreeView widget, it doesn't deselect the text in the TextEntry widget. How do I get it to deselect the text in the TextEntry widget when I click on the TreeView widget?

Upvotes: 1

Views: 612

Answers (1)

AndreLDM
AndreLDM

Reputation: 2198

You can bind gtk_editable_select_region to the entry's "focus-out-event" signal, see the sample below:

#include <gtk/gtk.h>

gboolean unselect_on_focus_lost (GtkWidget *widget)
{
    gtk_editable_select_region (GTK_EDITABLE (widget), 0, 0);
    return FALSE;
}

int main (int argc, char *argv[])
{
    GtkWidget *window, *box, *entry, *button;

    gtk_init (&argc, &argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER);
    gtk_container_set_border_width (GTK_CONTAINER (window), 5);
    gtk_window_set_default_size (GTK_WINDOW (window), 400, 130);

    box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 8);
    gtk_container_add (GTK_CONTAINER (window), box);

    entry = gtk_entry_new ();
    gtk_entry_set_placeholder_text (GTK_ENTRY (entry), "I will lose my selection when you click the button below");
    g_signal_connect (G_OBJECT (entry), "focus-out-event", G_CALLBACK (unselect_on_focus_lost), NULL);
    gtk_container_add (GTK_CONTAINER (box), entry);

    entry = gtk_entry_new ();
    gtk_entry_set_placeholder_text (GTK_ENTRY (entry), "I will NOT lose my selection when you click the button below");
    gtk_container_add (GTK_CONTAINER (box), entry);

    /* I used a button instead of a treeview to keep the code short */
    button = gtk_button_new_with_label("Click me");
    gtk_container_add (GTK_CONTAINER (box), button);
    gtk_widget_grab_focus (button);

    g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (gtk_main_quit), NULL);
    gtk_widget_show_all (window);
    gtk_main ();

    return 0;
}

Upvotes: 1

Related Questions