Shatodor
Shatodor

Reputation: 101

QlineEdit selectAll doesn't work?

I use folowing code. In it lineEdit->selectAll() works called by pushButton and only at first launch called by eventFilter. Although label->setText works all time propperly. Why?

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->lineEdit->installEventFilter(this);
}

void Widget::on_pushButton_clicked()
{
    ui->lineEdit->selectAll();
}

bool Widget::eventFilter(QObject *object, QEvent *event)
{
    if (object == ui->lineEdit && event->type() == QEvent::FocusIn )
    {
        ui->lineEdit->selectAll();
        ui->label->setText("Focused!");
        return false;
    }
    if (object == ui->lineEdit && event->type() == QEvent::FocusOut )
    {
        ui->label->setText("unFucused!");
        return false;
    }
    return false;
}

UPD: Did what Ilya recomended. Still have same problem.

void myLine::focusInEvent(QFocusEvent* event)
{
    setText("Focused!");
    selectAll();
}

void myLine::focusOutEvent(QFocusEvent* event)
{
    setText("UnFocused!");
}

Upvotes: 4

Views: 3590

Answers (3)

Shatodor
Shatodor

Reputation: 101

Found answer here Select text of QLineEdit on focus

Instead ui->lineEdit->selectAll() should use QTimer::singleShot(0,ui->lineEdit,SLOT(selectAll())), because mousePressEvent trigers right after focusInEvent so text selected in focusInEvent unselects by mousePressEvent.

Upvotes: 6

Ilya
Ilya

Reputation: 5557

Not really answering the question, but there's a more "standard" way of customizing these events.

  • Create a QLineEdit subclass and define your own focusInEvent / focusOutEvent handlers.

  • If you're using the UI Designer, promote your lineEdit to your subclass (right-click > "Promote to").

Upvotes: 0

RazrFalcon
RazrFalcon

Reputation: 807

Because you use eventFilter in a wrong way:

bool Widget::eventFilter(QObject *object, QEvent *event)
{
    if (object == ui->lineEdit && event->type() == QEvent::FocusIn )
    {
        ui->lineEdit->selectAll();
        ui->label->setText("Focused!");
    }
    if (object == ui->lineEdit && event->type() == QEvent::FocusOut )
    {
        ui->label->setText("unFucused!");
    }
    return QWidget::eventFilter(object, event);
}

Upvotes: -1

Related Questions