Grab focus on buttons created during game

Godot Version

4.7

Question

Hello again!

I’m working on menus, specifically an inventory menu. Now made it to making sure keyboard/controller navigation works fine.

On static parts of the menu it functions well with having “grab_focus” move the active button when I go from one part of the menu to another. The problem is when I get to the list of items themselves, as they are duplicates of one single “item slot” scene holding a button, image and name label, that are filled in when inventory is opened. The button is bound to variable “button”.

So my question is: How do I move the focus to the first item in this list, when opening it?

The item slots are added to a grid container like this:

I’ve then tried to get the first scene’s button to grab focus like this, but all I see is that focus disappears from where it was, but it doesn’t go to the new buttons (I don’t know where it went):

Any idea on how to get focus on the first of a set of identical buttons spawned into a grid container at runtime?

Bonus Question:

On the static buttons, I can decide where the focus moves to Focus Neighbour in the editor. How would I tell the code here that it should only move to the identical neighbouring item slots in the list? Picking the button itself, just means it goes nowhere.

Hope this all makes sense!

I have made some progress, in realising I was accessing the child all wrong. I had to go one deeper, as the button was a child of the child…

But now I have a new issue that mystifies me.

I tried going a direct path for the button instead:

billede

Through this, I found out that it only gets the newly spawned button every other time, in spite of the populate inventory function using queue_free on every child whenever its run. Which means grab_focus only works every other time I press the button, too.

Case in point, the print for the path:

How come this happens? And how do I get it to get the actual newly instanced button instead?

Edit:
Nvm, found the solution here immediately afterwards - which is to use remove_child as well: