Set Keyboardfocus to TextEditor

Im trying to spawn a TextEditor and immediately give it keyboardfocus:

void BrowserEntry::showRenameEditor() {
    m_rename_editor.setVisible(true);
    m_rename_editor.setText(getText());
    m_rename_editor.grabKeyboardFocus();
}

I am doing this in two different locations in my plugin. The first one works fine (is triggered by a button click). The second one does not (is triggered by a PopupMenu).

It will get focus very briefly and then loses it again (the cursor blinks exactly once - then it is gone).

My best bet is that after the PopupMenu closes, there is still a MouseEvent happening that gives focus to the component lying under the PopupMenu.

However TextEditor::onFocusLost() is never called.

Is there a good way to debug this? Or does somebody know what could be the problem here?
Thanks!

I’m struggling with a similar issue, although I haven’t really tried to solve it yet.

Have you tried using a timer to grab focus? If there’s a way to check for focus then you could even have it loop until it succeeds.

Nice idea! I just tried it and delaying the grabKeyboardFocus() by 50 msec does the trick.

Feels pretty hackish a solution though. If I find a “clean” way I’ll post it here. But if no problems arise this will do I guess.

Edit: Also there is bool Component::hasKeyboardFocus(). Although in my case it returned true right after setting it once, so it wasn’t much use.

Yeah, it does seem hackish, although I’m glad it works.
But keyboard focus is quite terrible to manage, I often get assertion faults due to the calls, when components are hidden, etc.
I don’t know of any more elegant implementations. Maybe grabbing focus delayed could be a good thing to add into JUCE…