Properly emit "focus" or "move-focus" signals

I have a GTK3 dialog with a multi-line text widget where users should be able to insert a tab character by pressing “Ctrl+Tab” as well as moving focus to the next/previous widget by pressing Tab/Shift+Tab key. The events “key-pressed” and “focus” have a custom callback where I can successfully detect tab presses and modifier keys while the multi-line widget is focused as well as control which widget of the dialog should get focus next. For all non-multi-line widgets, this works fine because the focus callback is called from GTK with the correct parameters

However, I’m failing to emit the signal that calls my “focus” callback correctly from within the “key-pressed” callback where I want to control the behavior of the tab-key. I tried:

g_signal_emit_by_name(dialog, "focus");

This one directly crashes the program. So I also tried:

g_signal_emit_by_name(dialog, "move-focus");

This one actually calls the “focus” callback, but the parameter GtkDirectionType direction will have the bits GTK_DIR_UP and GTK_DIR_RIGHT set instead of GTK_DIR_TAB_FORWARD.

Furhtermore, I wonder how I could make the emitted signal to communicate a GTK_DIR_TAB_BACKWARD.

You need to emit the signals with the required arguments! Otherwise, yes, crashes will result, because other people handling those signals will read junk or protected memory off the stack, instead of the expected arguments.

See the docs and add to your emit call, the relevant types of argument with the value you want to send to signal handlers.

The instance argument (in your case dialog) will be included for you, but you need to specify any subsequent ones in the call to emit.

1 Like

Thank you so much! I didn’t realize before that the g_signal_emit_by_name function can take more than two parameters and that I’d had to add the GtkDirectionType as third and the userData pointer as fourth argument.

1 Like

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