PDA

View Full Version : HOWTO: make a QLineEdit select all the text when clicked on?



scarleton
30th August 2010, 03:29
On both the QEvent::Enter and QEvent::FocusIn of the QLineEdit, I am calling selectAll(), but it isn't working as desired...

Everything gets selected ( because of QEvent::FocusIn, I think), but on the mouse down or something the selectAll is lost.

Any thoughts on how to safely do a selectAll so I can simply type over the existing value?

tbscope
30th August 2010, 05:32
connect(this, SIGNAL(clicked()), this, SLOT(selectAll()));

aamer4yu
30th August 2010, 05:38
Does QLineEdit have a clicked() signal :rolleyes:

tbscope
30th August 2010, 05:42
Apparently no :-)
Monday morning I guess. I assumed all widgets had a clicked signal. Why don't they?

Anyway, here's the signal:

class MyLineEdit : public QLineEdit
{
...
signals:
void clicked();
...
};

// Edit: or mouseReleaseEvent(...) according to your taste
void MyLineEdit::mousePressEvent(...)
{
emit clicked();
}


I think, but I guess I need to get some more cafeine to wake up.

wysota
30th August 2010, 15:23
but on the mouse down or something the selectAll is lost.
To prevent such behaviour, you'd have to filter out all unwanted events. But then you won't be able to do things as selecting parts of the input from the widget with the mouse and stuff. I think that what you really want is something like this:


class MagicLineEdit : public QLineEdit {
public:
MagicLineEdit(QWidget *parent = 0) : QLineEdit(parent), m_firstChar(false) {}
protected:
void focusInEvent(QFocusEvent *e) {
m_firstChar = true;
QLineEdit::focusInEvent(e);
}
void keyPressEvent(QKeyEvent *ke) {
if(m_firstChar /* && !ke->text().isEmpty() */) { // the commented part is optional
clear();
m_firstChar = false;
}
QLineEdit::keyPressEvent(ke);
}
private:
bool m_firstChar;
};