如何在输入满足条件后自动将QLineEdit的焦点更改为另一个QLineEdit?

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

我有两个 QLineEdit 小部件,edt1edt2。每个 QLineEdit 只能接受两位数字。我在edt1中输入xx(如10)后,可以满足输入条件,如何自动将焦点从edt1切换到edt2

是否有内置函数可用于实现此目的?或者,任何人都可以提供有关如何执行此操作的信息吗?谢谢。

您需要检查 edt1.hasAcceptableInput() every time textChanged() signal is emitted, and call edt2.setFocus() 如果是。

#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();
}