[Solved] QDoubleValidator, allow to enter ".00..." and to disable ",00"

  • Hi!

    I am using QDoubleValidator which works fine, except two things:

    1. If someone would like to enter ".001", it is required to type "0."

    Isn't there a solution, where the user could just type ".001" and miss out the "0" before the point?

    I have:

    QValidator *validator = new QDoubleValidator(.0, 1.0, 10, lineedit);
    1. It is also possible to enter ",00...". This option with a "comma" I would like to disable.

    Therefore, I would like to enable to enter a number with decimal places, that the user can

    1. directly start with "." (or optional with "0.") and
    2. to disable the possibility to enter a "comma" (e.g. "," and "0,").

    I'd appreciate any useful ideas!

  • @newe12
    Probably QRegExpValidator provides the extended flexibility you need.
    Another possibility is the inputMask

  • @newe12 As koahnig says you need a QRegExpValidator. You have to be carefull with dot (.) so u have to scape it. I let u an example to see how it works:

     QRegExp rx("[\\.]\\d{0,30}"); // See that I don't put "." but "\\."
        QValidator *validator7 = new QRegExpValidator(rx, this);

    In this case this will accept a dot and then from 0 to 30 numbers p.e: .0 / .123 / .12345678912346579 /

  • Hi @koahnig and @roseicollis!

    thank you very much!

    It nearly works:

    QRegExp rx("[\\.]\\d{0,10}");
    QValidator *validator = new QRegExpValidator(rx, this);

    But, how can I enable to type additionally "0."?

  • @newe12

    It was just an example to let you see how it works because I had so much problems with that issue too and all help was so apreciated. I'm not an expert on this and I don't know if this is best way but maybe you need something like this:

        QRegExp rx7("[0-9\\.\\0-9]{0,7}"); // 0,7 allows you to write from 0 to 7 numbers like 0.2 or 0.23568 or 123.56

    As I don't know exactly what u need u will have to play whith this on your own and find which is your best combination. Here you can read more about QRegExp: Documentation

  • @roseicollis

    thank you very much!

    Well, nearly!

    If I use

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

    I can enter ".xy" as intended, but also "0xy" as not intended, instead of "0.xy" as planned.


  • Lifetime Qt Champion


    It's rather "0?\\.\\d{0,10}"
    Optional 0, mandatory point, then from 0 to 10 number

  • Perfect! That's it! Solved!

    @SGaist Thanks very much!

Log in to reply