How to grab and keep focus on a widget?

But if I replace the word ent with wid in signal handler, it doesn’t work.

In this case you needed to connect to wid.connect(“notify::is-active”, lambda _: ent.grab_focus()) - so Entry ent object would grab focus when Window wid object would get “is-active” property changed.

In my real app, the widget is a page in a stack. So whenever the page is visible the widget must be focused. How to do it?

See this Emmanuele comment - you need to connect stack signal “notify::visible-child-name”, and then in callback function check if name is page you want it to show, if yes, then grab focus for Entry object within that page. Something like this:

stack.connect("notify::visible-child-name", callback_func)
 def callback_func():
    if stack.get_property("visible-child-name") == page_which_contains_entry:
        ent.grab_focus()
1 Like