Question

I need a QLineEdit which must represent a range. F.E. (1,2] , and for this representation I want to set a validation checker for user not to write other symbols. In this case I have char + int + char + int + char as shown in example below. Does Qt have any feature to handle this? Thanks in advance.

Was it helpful?

Solution 2

QRegExp expr("^[[,(]{1,1}(0|[1-9]{1,1}[0-9]{0,9})[,]{1,1}(0|[1-9]{1,1}[0-9]{0,9})[],)]{1,1}$");

This is what I wanted! I must allow more then one leading 0-s.

OTHER TIPS

You can use Qt's Input Validator feature to achieve this goal.

The following snippet will restrict the input on a line edit as you specified.

QRegExp re("^[[,(]{1,1}(0|[1-9]{1,1}[0-9]{0,9})[,]{1,1}(0|[1-9]{1,1}[0-9]{0,9})[],)]{1,1}$");
QRegExpValidator *validator = new QRegExpValidator(re, this);
ui->lineEdit->setValidator(validator);

Edit Updated the regex

It is not possible to write a regexp accepting only valid ranges, the reason is that you can check the syntax but not the numeric value (unless e regexp engine has some extensions). The difference between

[1234,5678)

and

[5678,1234)

is not in the syntax (what regexps are about), but in the semantics (where regexps are not that powerful).

For checking just the syntax a regexp could be

\[\d+,\d+\)

or, if you also allow other types of interval boundary conditions:

[\[)]\d+,\d+[\])]

I would recommend not allowing all chars but only the needed ones. Example:

QRegExp("[\\\\\\(\\)\\{\\}]\\d[\\\\\\(\\)\\{\\}]\\d[\\\\\\(\\)\\{\\}]");

I'll explain:

[] these contain the matchin characters for your char: \\ (this is actually matching the \ sign, as you need to escape it once for your Regular Expression \ and once more for Qt String makes it \\), \( is for opening bracket and so on. You can add all chars you would like to be matched. A good help is the Regular Expression Cheat Sheet for this.

\d is matching a single digit, if you want to have more than one digit you could use \d+ for at least one or \d{3} for exactly 3 digits. (+ 1 or more, ? 0 or 1, * 0 or more)

Another example would be:

QRegExp("[\\\\\\(\\)\\{\\}]\\d[,\\.]\\d[\\\\\\(\\)\\{\\}]");

for having the center character to be a . or a , sign.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top