How is GtkWidget.focus-on-click supposed to work?

Given a focussable widget with focus-on-click set, I’d assume that clicking (MB1) on said widget should result in it getting has-focus, but that is seemingly not the case.

Given the following demo:

#include <gtk/gtk.h>
#include <adwaita.h>

GtkWidget* create_widget(void) {
	GtkWidget* bin = adw_bin_new();
	gtk_widget_set_hexpand(bin, TRUE);
	gtk_widget_set_focusable(bin, TRUE);
	gtk_widget_set_focus_on_click(bin, TRUE);
	gtk_widget_add_css_class(bin, "fz");
	return bin;
}

void activate(GtkApplication* app, gpointer) {
	g_autoptr(GtkCssProvider) style = gtk_css_provider_new();
	gtk_css_provider_load_from_string(style, ".fz:focus { background-color: red; }");
	gtk_style_context_add_provider_for_display(
		gdk_display_get_default(),
		GTK_STYLE_PROVIDER(style),
		GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
	);

	GtkWidget* window = gtk_application_window_new(app);
	GtkWidget* container = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0.);
	gtk_window_set_child(GTK_WINDOW(window), container);

	gtk_box_append(GTK_BOX(container), create_widget());
	gtk_box_append(GTK_BOX(container), create_widget());

	gtk_window_present(GTK_WINDOW(window));
}

int main(int argc, char** argv) {
	g_autoptr(GtkApplication) app = gtk_application_new("arpa.sp1rit.gtk.focus-test", G_APPLICATION_DEFAULT_FLAGS);
	g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
	return g_application_run(G_APPLICATION(app), argc, argv);
}

I can change the focus as expected using tab or the left/right arrow keys but not using the mouse. Can someone explain to me how focus-on-click is supposed to work and/or how I get the widget from the demo to accept focus by clicking on it?

Looking at the code, there’s no implementation for focus-on-click in GtkWidget. It’s only used as an opt-out in widgets that would normally focus on click, e.g. GtkButton:

  if (gtk_widget_get_focus_on_click (widget) && !gtk_widget_has_focus (widget))
    gtk_widget_grab_focus (widget);

The default value of the property is true anyway.

If you want it to focus on click, you’ll need to add your own GtkGestureClick.

1 Like

Thanks for the reply

If you want it to focus on click, you’ll need to add your own GtkGestureClick.

I feared this being the case, but I it seems work (obviously) :).

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.