[gtkmm-4.0] how to check if a Gtk::Entry has focus

I use gtkmm-4.0 on ubuntu 22.04 LTS.

For example create 2 entries and test them if they are focused with is_focus() or has_focus(). It always answer false even if i use grab_focus().
If i test another focus widget it answers true.

So how to check and know which entry is used by a user ?

Better describe what you really intend, not what you do. I have no idea why someone may want to query focus for a widget. For your task, maybe Gtk.Widget.get_state_flags would help, I played with that function myself recently. But maybe what you desire is just connecting to a signal?

Thanks for your answer.

For example you have many entries, user set text in an entry.
How to know in which entry the user is typing text?

Generally we connect to the “activate” or the “changed” signal for a GtkEntry. “activate” is emitted, when the user pressed RETURN or another meta key, changed is emited for every keystroke. Most of the time “activate” is what we want – if the user is done with his input, we get the new string. I can not tell you how you connect to signals in gtkmm, I have used only C, Python, Ruby, Nim. But you should find that in the gtkmm tutorials, or just ask here again.

With GTK4 it’s best to use the following method to determine whether a widget has focus:

util_widget_is_focused (const Gtk::Widget& widget)
  const Gtk::Root *root = widget.get_root ();
  if (!root)
    return false;

  const Gtk::Widget *focused = root->get_focus ();
  if (!focused)
    return false;

  return focused->is_ancestor (widget);

NOTE: not sure if an overload of Gtk::Widget::is_ancestor() taking a const reference as an argument exists. If you find issues, remove all the const qualifiers from the sample above.

1 Like

That is an interesting idea. But I have the strong feeling, that the initial poster just is new to GTK and has to learn how one connect widget signals to callback functions. :slight_smile:

1 Like

Exactly what i need.
You are right don’t use const because of

error: binding reference of type ‘Gtk::Widget&’ to ‘const Gtk::Widget’ discards qualifiers
60 | return focused->is_ancestor(widget);

1 Like

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