Select text of QLineEdit on focus

Viewed 15368

I have created a dialog using QtDesigner. There is a QLineEdit object in the dialog with some default content. When the dialog initializes and the focus goes to the QLineEdit, I want the default content to be auto selected, so once the user start writing, the previous content will be overwritten.

EDIT:

In constructor:

dialog->accept(); 

and

connect( dialog, SIGNAL(accepted()), QlineObj, SLOT( selectAll() ) );
4 Answers

This is an older question, but nevertheless, I ended up here searching for a solution this exact problem. It can be solved in the following way:

Create a class derived from QLineEdit and override the focusInEvent in the header:

void focusInEvent(QFocusEvent *event) override;

Then implement it like so:

void MyLineEdit::focusInEvent(QFocusEvent *event)
{
    // First let the base class process the event
    QLineEdit::focusInEvent(event);
    // Then select the text by a single shot timer, so that everything will
    // be processed before (calling selectAll() directly won't work)
    QTimer::singleShot(0, this, &QLineEdit::selectAll);
}

Just in case anybody else wonders how this can be done ;-)

You can use QApplication::focusChanged along with QTimer::singleShot to select all the text on a changed focus.

Normally your QApplication is declared in main, so use QObject::connect there, eg:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    My_Main_Window w();
    QObject::connect(&a, SIGNAL(focusChanged(QWidget*, QWidget*)),
                     &w, SLOT(my_focus_changed_slot(QWidget*, QWidget*)));
    w.show();

    return a.exec();
}

Remember to make the public slot in the My_Main_Window class:

public slots:
void my_focus_changed_slot(QWidget*, QWidget*);

Then in your definition of my_focus_changed_slot, check if the second QWidget* (which points to the newly focused widget) is the same as the QLineEdit you wish to select all of, and do so using QTimer::singleShot so that the event loop gets called, then the QLineEdit has the selectAll slot called immediately after, eg

void My_Main_Window::focus_changed(QWidget*, QWidget* new_widget) {
    if (new_widget == my_lineedit) {
        QTimer::singleShot(0, my_lineedit, &QLineEdit::selectAll);
    }
}

where my_lineedit is a pointer to a QLineEdit and is part of the My_Main_Window class.

Related