PDA

View Full Version : selectAll in QLineEdit does not work



Ishmael
16th June 2010, 23:01
I have subclassed QLineEdit in order to handle a focus event, and I would like all existing text to be highlighted as soon as I click in the textbox. The selectAll() method does not work. What am I missing?


// --------------------------------------------------------------------
class MyLineEdit : public QLineEdit
{
Q_OBJECT

protected:
void focusInEvent(QFocusEvent *);

};

void MyLineEdit::focusInEvent(QFocusEvent *e) {

this->selectAll(); // THIS DOESN'T WORK
//this->clear(); // <-- THIS WORKS!

}

squidge
16th June 2010, 23:09
It most likely is working. What your getting is that you are selecting all the text, and then click a character in the box with your mouse, and so clearing the selection. Try it yourself - select all the text and then click in the box with your mouse.

One solution would be to wait until the mouse button is released before doing the selectAll. Another would be to use a timer.

Ishmael
17th June 2010, 01:04
Hmm, I didn't quite understand your answer. I must be missing something. Here's a complete example. I would like the text to be highlighted as soon as I click in the textbox.


#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H

#include <QtGui>

class MyLineEdit : public QLineEdit
{
Q_OBJECT

protected:
void focusInEvent(QFocusEvent *);
};

#endif // MYLINEEDIT_H



#include "mylineedit.h"

void MyLineEdit::focusInEvent(QFocusEvent *) {
//this->clear();
this->selectAll();
}



#include "mylineedit.h"
#include <QtGui>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QFrame *f = new QFrame();
MyLineEdit *tmp = new MyLineEdit();
tmp->setText("test this");
QHBoxLayout *flayout = new QHBoxLayout(f);
flayout->addWidget(tmp);
f->setFocus();
f->show();
return app.exec();
}

wysota
17th June 2010, 01:43
I would surely call the base class implementation of the event handler as it does some useful things.


void MyLineEdit::focusInEvent(QFocusEvent *e) {
QLineEdit::focusInEvent(e);
this->selectAll();
}

If you want to select contents of the line edit upon receiving focus (and focusInEvent doesn't work, remember about the base class implementation call!) then connect QApplication::focusChanged() signal to a custom slot, check if the widget receiving the focus is your line edit and call selectAll() on it.

Michal Fapso
25th May 2015, 05:26
Hi, in case someone comes across this thread, this solution worked for me:


void MyCustomSpinBox::focusInEvent(QFocusEvent *event)
{
QTimer::singleShot(0, [this](){
selectAll();
});
}