Search code examples
qtqlineeditselectall

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!");
}

Solution

  • 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.