Reputation: 4872
I have a QLineEdit that a user is able to give input to using a keyboard. The line edit must only accept hexadecimal characters. The line edit must automatically put a delimiter character between every set of 2 hex characters The last delimiter character should be automatically removed when the user deletes the last hex characters.
I have tried this: ui->mTextEdit->setInputMask("Hh,hh,hh,hh,hh");
But unfortunately all of the commas are displayed when there is no text, and you have to know how many sets of hex numbers you want in advance (which I don't know/can't restrict).
Could I use a QValidator to do this for me?
Upvotes: 1
Views: 7146
Reputation: 3835
You can use a custom subclass of QValidator
, with validate()
e.g. like this:
QValidator::State HexValidator::validate(QString &input, int &pos) const
{
// remove trailing comma
if (input.endsWith(',')) {
input.chop(1);
}
// insert comma when third hex in a row was entered
QRegExp rxThreeHexAtTheEnd("(?:[0-9a-fA-F]{2},)*[0-9a-fA-F]{3}");
if (rxThreeHexAtTheEnd.exactMatch(input)) {
input.insert(input.length()-1, ',');
pos = input.length();
}
// match against needed regexp
QRegExp rx("(?:[0-9a-fA-F]{2},)*[0-9a-fA-F]{0,2}");
if (rx.exactMatch(input)) {
return QValidator::Acceptable;
}
return QValidator::Invalid;
}
Upvotes: 4