Reimundo Heluani
Reimundo Heluani

Reputation: 978

QLineEdit InputMask and blanks inserted

I have a QLineEdit with an InputMask set to ">AAAA90", that is, I expect the text to consists of exactly 4 uppercase Ascii letters and between 1-2 digits. If the user types "AA1" however, the QLineEdit will show AA 1, namely it will insert two blanks and print the "1" which is permitted in the 5th position. I would rather want a behavior like with illegal characters at any position, namely if the user types "AA%" then the cursor stays at the third position and does not print the "%" character.

Is this possible in QT5?

Upvotes: 0

Views: 3754

Answers (3)

ano
ano

Reputation: 39

For anyone interested, QRegExpValidator is deprecated in Qt6, but there is a new QRegularExpressionValidator, so @Reimundo's example would be something like this:

QRegularExpression rgx("[a-zA-Z]{4}\\d{1,2}");
QValidator *comValidator = new QRegularExpressionValidator(rgx, this);
comLineEdit->setValidator(comValidator);

Upvotes: 0

frogatto
frogatto

Reputation: 29285

Note that Input Masks don't insert blank spaces in the returned text (i.e. return value of QLineEdit::text() method), although blank spaces are inserted in GUI for better readability.

To more clarify, Input Mask make QLineEdits to work in overwrite mode not insert mode. But setting a QValidator leaves QLineEdit working in insert mode untouched.

For example if you type "AA3", GUI shows "AA 3" but text() method returns AA3. If you now move the cursor back to 3th position and type "B", the GUI shows "AAB 3" (not "AAB 3", because we are in overwite mode) and text() method returns "AAB3".

Upvotes: 0

Reimundo Heluani
Reimundo Heluani

Reputation: 978

Thanks @Mike for the tip on QValidator, I ended up hooking a validator like

 QRegExp rgx("[a-zA-Z]{4}\\d{1,2}");
 QValidator *comValidator = new QRegExpValidator (rgx, this);
 comLineEdit->setValidator(comValidator);

And hooking textEdited with:

void MainWindow::comTextEdited(const QString &arg1)
{
  qobject_cast<QLineEdit*>(sender())->setText(arg1.toUpper());
}

To force the first 4 characters to uppercase.

Upvotes: 1

Related Questions