how to judge there is content in QTextEdit in QT?

3.7k views Asked by At

I have written a notepad which looks like notepad in Windows. How to set to make the find action disabled when the QTextEdit empty but enabled when something in it

2

There are 2 answers

4
E4z9 On

You connect a function that enables/disables the action based on the text edits plainText(), to the textChanged() signal of the text edit.

For example:

void MyWidget::someSetupMethod()
{
    // ... some code that sets up myTextEdit and myFindAction here
    connect(myTextEdit, &QTextEdit::textChanged, myFindAction, [myTextEdit, myFindAction]() {
        myFindAction->setEnabled(!myTextEdit->plainText().isEmpty());
    });
    // ...
}

or, if you cannot or do not want to use C++11, something like

void MyWidget::someSetupMethod()
{
    // ... some code that sets up m_myTextEdit and m_myFindAction here
    connect(m_myTextEdit, &QTextEdit::textChanged, this, &MyWidget::updateFindAction);
    // ...
}

void MyWidget::updateFindAction()
{
    m_myFindAction->setEnabled(!m_myTextEdit->plainText().isEmpty());
}
1
tistolz On

The myTextEdit->plainText().isEmpty() procedure does not seem to be very efficient: The plainText method needs to convert the full QTextEdit contents into a new QString buffer, which is expensive if the QTextEdit contains a large amount of text.

I suggest to use myTextEdit->document()->isEmpty() instead, which queries the QTextDocument storage, i.e. the original data structure.

In my use case, the QTextEdit contains an error log, and before appending a line I check if the text is empty; if not, I insert a newline(*). Converting the log buffer to a QString each time a line is appended would be a bad idea.

(*) I cannot insert a newline together with each log entry, because the entries themselves are comma-separated lists. Roughly speaking I have a newEntry(...) and a newLine(...) function, and newEntry does not know if newLine or newEntry will be called next.