Serious Sammy Serious Sammy - 2 months ago 20
C++ Question

Using QRegExValidator for QLineEdit

I have a problem with using the QRegExValidator to validate a QLineEdit. It's supposed to only acept first and last name with a space between. I pretty much followed the example from here:

http://doc.qt.digia.com/4.6/qregexpvalidator.html

the code compiles and i can run the programm but I can't type any letter into the lineedit field. Why?

QString name_rx = "[A-z]+\\S[A-z]+";
QRegExp rx;
QValidator *validator = new QRegExpValidator(rx, this); // this means mainwindow

rx.setPattern(name_rx);
ui->nameEdit->setValidator(validator);
ui->nameEdit->setMaxLength(32);


Is this is all it takes to check the input field?

Answer

Two minor problems...

QString name_rx = "([A-Z]|[a-z])+\\s([A-Z]|[a-z])+";// Note, \\s not \\S
QRegExp rx;
rx.setPattern(name_rx);// Note, happens BEFORE use in the validator

Another acceptable method would be:

QString name_rx = "[a-z]+\\s[a-z]";// Note, \\s not \\S
QRegExp rx;
rx.setCaseSensitivity(Qt::CaseInsensitive);
rx.setPattern(name_rx);// Note, happens BEFORE use in the validator

And here it is added to the validator

QValidator *validator =  new QRegExpValidator(rx, this); // this means mainwindow

ui->nameEdit->setValidator(validator);
ui->nameEdit->setMaxLength(32);

Also a good example for what works, check out this page:

http://doc.qt.digia.com/4.6/tools-settingseditor-variantdelegate-cpp.html

It has all of these examples specifically for using QRegEx with QRegExValidator with line edits:

 boolExp.setPattern("true|false");
 boolExp.setCaseSensitivity(Qt::CaseInsensitive);

 byteArrayExp.setPattern("[\\x00-\\xff]*");
 charExp.setPattern(".");
 colorExp.setPattern("\\(([0-9]*),([0-9]*),([0-9]*),([0-9]*)\\)");
 doubleExp.setPattern("");
 pointExp.setPattern("\\((-?[0-9]*),(-?[0-9]*)\\)");
 rectExp.setPattern("\\((-?[0-9]*),(-?[0-9]*),(-?[0-9]*),(-?[0-9]*)\\)");
 signedIntegerExp.setPattern("-?[0-9]*");
 sizeExp = pointExp;
 unsignedIntegerExp.setPattern("[0-9]*");

 dateExp.setPattern("([0-9]{,4})-([0-9]{,2})-([0-9]{,2})");
 timeExp.setPattern("([0-9]{,2}):([0-9]{,2}):([0-9]{,2})");
 dateTimeExp.setPattern(dateExp.pattern() + "T" + timeExp.pattern());

Hope that helps.