2

I'm using a QDoubleValidator for my QLineEdit. The application locale (set in QtCreator) is QLocale::German.

Now when I enter a valid double (either using a dot or a comma as decimal separator) writing to the textedit as well as converting the string to a float works perfectly fine. But the validator also lets me write stuff with multiple decimal separators. Strings like 123.567,890 or ,,03.4... get validated but can't get converted into a float.

Is there a way to tell QDoubleValidator to only validate real numbers and not just strings without alphabetical characters?

I basically want to have a validator, that only validates strings, that can get converted to floats using either the default locale or the german locale.

Uroc327
  • 1,379
  • 2
  • 10
  • 28
  • 1
    Why don't you use a [`QDoubleSpinBox`](http://doc.qt.io/qt-5/qdoublespinbox.html) ? It will automatically use the system locale, and you can [hide the up/down buttons](http://doc.qt.io/qt-5/qabstractspinbox.html#buttonSymbols-prop) if you don't want to see them. – p.i.g. May 26 '15 at 19:06

2 Answers2

4

I have not used the QDoubleValidator so far but I could achieve such behaviour by using a QRegExpValidator:

QRegExpValidator* rxv = new QRegExpValidator(QRegExp("[+-]?\\d*[\\.,]?\\d+"), this);
lineedit->setValidator(rxv);
Bowdzone
  • 3,827
  • 11
  • 39
  • 52
2

If you want only convert your content into the float and you don't want locale specifications, you can use QRegExpValidator with next deep regexp.

ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")));
Jablonski
  • 18,083
  • 2
  • 46
  • 47