Giving focus to another Component


#1

Hi,

Is there a generic way to handle giving focus to another Component B when Component A is clicked and has “done its job”? For example, I have a main Component (MainComponent) which I want to always have the keyboard focus. When clicking on a Button, I want the focus to be given back to MainComponent.

So far I have managed to do that by overriding the focusOfChildComponentChanged method of such Button:

void UnfocusableSlider::focusOfChildComponentChanged(FocusChangeType)
{
	if ((mainComponentToFocus != nullptr) && (hasKeyboardFocus(true))) {
		mainComponentToFocus->grabKeyboardFocus();
	}
}

It seems to work fine in most cases, but looks hacky to me. Plus, in the case of a slider, this prevents me from clicking on the text to edit it, because the focus is directly given to my “mainComponentToFocus”.

Is there a clean way to do what I want? Thanks.

Julien.


#2

Hi Julien,
I think the solution is described here: Component::grabFocus() (forwarded from Component::setWantsKeyboardFocus(bool) )

So I would probably do:

a->setWantsKeyboardFocus (false);
a->setExplicitFocusOrder (10);
b->setWantsKeyboardFocus (true);
b->setExplicitFocusOrder (11);

Eventually by reading around these methods, you find more ideas on how to adapt the focus traversal…

Good Luck…


#3

Late reply (only had time now to experiment on this again!).

I ended up having specific EditTexts calling moveKeyboardFocusToSibling(true) when the field has finished being edited. The parent has a KeyboardFocusTraverser which getDefaultComponent/getNextComponent refers to the Component I want the focus to be given to. So far it seems to work right.

Thanks for your ideas!