Deactivating keyboard focus

Can I make a TextEditor to grab focus only if it is clicked on with mouse?

I don’t need keyboard focus traversal on my UI elements, so I’d like to turn it off, but I’d like to allow the user to click on a TextEditor and type text into that.
Maybe it’s some obvious solution, but even if I turn the focus grab off on every component one by one (but the TextEditor), the TextEditor will automatically grab the focus with the first keystroke and use the second keystroke as an input (probably because it is the only component that I can’t disable keyboard focus).

Any suggestion what would be the best practice to solve this?

I think I asked this before and the easiest solution was to use a Label that shows a TextEditor when clicked on.

1 Like

I did this as a workaround. The only problem here is that it does not remove the focus automatically after you entered the text.

#pragma once

class TalTextEditorFocus : public juce::TextEditor
{
public:
    TalTextEditorFocus()
    {
        setWantsKeyboardFocus(false);
    }

    virtual ~TalTextEditorFocus()
    {
    }

private:
    void mouseEnter(const MouseEvent &event) override
    {
        setWantsKeyboardFocus(true);
    }

    void mouseExit(const MouseEvent &event) override
    {
        setWantsKeyboardFocus(false);
    }
};

One or more of these juce::Component methods may be of use:

setMouseClickGrabsKeyboardFocus()
giveAwayKeyboardFocus()
unfocusAllComponents()
createFocusTraverser()
createKeyboardFocusTraverser()

Note that you could even create your own keyboard focus traverser with its own custom logic (to disable keyboard traversal beyond what you need).

1 Like