For quick skip the gui code, and go straight to method validate, i dont know, next step to get validate result when login button click. full code in here https://pastecode.io/s/ut3cuq3p
class MainWindow: public QWidget
{
Q_OBJECT
public:
MainWindow(){ ... }
public slots:
void validate(QLineEdit* pUserInput)
{
QRegularExpression rx("^[^_\\W] $");
QValidator* validator = new QRegularExpressionValidator(rx, this);
pUserInput->setValidator(validator);
// what property to get the validate result?
// i need to pass to QMessageBox
QMessageBox message;
message.setText(validateResult);
message.exec();
}
}
CodePudding user response:
When using a validator on a QLineEdit
, you want to look at the value of pUserInput->hasAcceptableInput()
but you can set it up better. You only need to assign the validator to your QLineEdit
when it is created (unless your validation regex is changing every time), then you can use the signals QLineEdit::editingFinished
and QLineEdit::inputRejected
to determine whether the user's input was acceptable - see QLineEdit documentation
MainWindow::MainWindow()
{
...
QValidator* validator = new QRegularExpressionValidator(rx, this);
pUserInput->setValidator(validator);
connect(pUserInput, &QLineEdit::editingFinished, this, &MainWindow::validText);
connect(pUserInput, &QLineEdit::inputRejected, this, &MainWindow::invalidText);
...
}
void MainWindow::validText()
{
// pUserInput has valid input text
...
}
void MainWindow::invalidText()
{
// pUserInput has invalid input text
...
}