TextEditor highlight not working properly

Hi everyone,

I’m having trouble getting the highlight of TextEditors to work properly.
I would like the text editors to highlight all the text when a user clicks on it.

To do that, I tried initialising the editors with setSelectAllWhenFocused(true).
But, when the editor gains focus, it doesn’t highlight any text, so that doesn’t work.
I did some debugging and under the hood it seems that the texts is highlighted for a short time in TextEditor::focusGained, but quickly after that a mouseDown callback removes the highlighted range.

I looked into the projucer code and found that instead of using TextEditor, the projucer uses TextPropertyComponent to edit single line settings. Isn’t the TextEditor designed editing single line properties?

Another issue I have is that the texteditor stays highlighted even when it loses focus.
Here is a code example that shows these problems, I hope someone can help me out.

class MainComponent  : public juce::Component
{
public:  
    MainComponent()
    {
        addAndMakeVisible(editor1_);
        addAndMakeVisible(editor2_);
        
        editor1_.setMultiLine(true);
        editor2_.setMultiLine(true);
        
        editor1_.setTextToShowWhenEmpty("Click should highlight", juce::Colours::grey);
        editor2_.setTextToShowWhenEmpty("Click should highlight", juce::Colours::grey);
    
        editor1_.setSelectAllWhenFocused(true);
        editor2_.setSelectAllWhenFocused(true);
        
        addAndMakeVisible(button_);
        
        setSize (600, 400);
    }
    
    ~MainComponent() override {}
    
    void paint (juce::Graphics& g) override
    {
        g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
    }
    
    void resized() override
    {
        editor1_.setBounds(10, 10, 200, 30);
        editor2_.setBounds(10, 50, 200, 30);
        
        button_.setBounds(10, 90, 150, 30);
    }
    
private:
    juce::TextEditor editor1_;
    juce::TextEditor editor2_;
    
    juce::TextButton button_ {"Lose focus"};
    
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent)
};

Thanks for reporting. We’ve pushed a fix for the setSelectAllWhenFocused() bug in 56252ca.

I looked into the projucer code and found that instead of using TextEditor, the projucer uses TextPropertyComponent to edit single line settings. Isn’t the TextEditor designed editing single line properties?

TextPropertyComponent uses a TextEditor internally for text input, the class is just a wrapper around managing the text value and allows it to be added to PropertyPanels in the UI.

the texteditor stays highlighted even when it loses focus.

This is intentional behaviour. You could modify this by clearing the selection on focus loss if you wanted.

2 Likes