Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text of QLineEdit on focus

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() ) );
like image 704
GG. Avatar asked Aug 08 '10 11:08

GG.


People also ask

How do I read text in QLineEdit?

As mentioned in the documentation, the text of a QLineEdit can be retrieved with its method text . Note that it's a QString , not a regular string, but that shouldn't be a problem as you format it with your "%s" % text .

How do I get text from line edit in Qt?

You use QLineEdit::setText() to change the text and QLineEdit::text() to read. Your questions are very basic and show a clear lack of studying the documentation and experimenting thing yourself. Qt is one of the better documented frameworks out there and with lots of examples.

How do I edit text in QLineEdit?

You can change the text with setText() or insert() .

What is QLineEdit?

The QLineEdit widget is a one-line text editor. A line edit allows the user to enter and edit a single line of plain text with a useful collection of editing functions, including undo and redo, cut and paste, and drag and drop.


1 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 ;-)

like image 84
Tobias Leupold Avatar answered Oct 14 '22 08:10

Tobias Leupold