Search code examples
c++qtqlineedit

QLineEdit doubleValidator starting with point


I have a UI with a QLineEdit which only accepts float/double values with the help of a QDoubleValidator. It only accepts values if I enter a leading number like: 0.234. But I'd prefer to be able to enter values directly without a leading number like .234. Unfortunately the QDoubleValidator does not accept a leading point. Is there any way to archive my goal with the help of the validator, or do I have to check every entered character myself? I'm using Qt 5.9.1 on Windows10.

QDoubleValidator* doubleValidator = new QDoubleValidator();
QLineEdit* lineEdit = new QLineEdit(frame);
lineEdit->setValidator(doubleValidator);
vbox->addWidget(lineEdit);

Solution

  • Unfortunately, QDoubleValidator is pretty limited, but you can use QRegExpValidator to get what you want with a regex describing a number, depending on the notation you expect.

    // non-scientific floating-point numbers
    QRegExp rx("[-+]?[0-9]*\\.?[0-9]+");
    QRegExpValidator v(rx, 0);
    QString s;
    s = ".123";
    v.validate(s, 0);    // Returns Acceptable
    

    This is much more extendable, and allows you to abstract it to any condition, with basic regular expression knowledge.