stackname
stackname

Reputation: 111

How to change the focus of QLineEdit automatically to another QLineEdit after input satisfy a criterion?

I have two QLineEdit widgets, edt1 and edt2. Each QLineEdit can only accept two digits. After I input xx (e.g. 10) in edt1, which can satisfy the input criterion, how to change the focus from edt1 to edt2 automatically.

Is there built in function to use to make this happen? Or, can anyone provide something about how to do this? Thank you.

Upvotes: 0

Views: 1374

Answers (1)

Mike
Mike

Reputation: 8355

You need to check if edt1.hasAcceptableInput() every time textChanged() signal is emitted, and call edt2.setFocus() if it does.

#include <QtWidgets>

int main(int argc, char** argv)
{
    QApplication a{argc, argv};

    QWidget w;
    QLineEdit lineEdit1;
    QLineEdit lineEdit2;
    //validator to accept two digits
    QRegExpValidator validator{QRegExp{"\\d{2}"}};
    lineEdit1.setValidator(&validator);
    lineEdit2.setValidator(&validator);
    QVBoxLayout layout{&w};
    layout.addWidget(&lineEdit1);
    layout.addWidget(&lineEdit2);
    w.show();

    QObject::connect(&lineEdit1, &QLineEdit::textChanged, [&](){
        if(lineEdit1.hasAcceptableInput())
            lineEdit2.setFocus();
    });

    return a.exec();
}

Upvotes: 2

Related Questions