I can still insert numbers outside the range specified with a QDoubleValidator on a QLineEdit, is this a bug?

The validator will return an Intermediate [doc.qt.nokia.com] value for text that is a double but outside the range. The line edit will accept the intermediate values since it means that only a bit of editing is required to fix the value. This is because you might want to do something like pasting a number with 10 decimals with a validator that only allows 2 and then remove some of them.

The example below reimplements validate() [qt.nokia.com] to make the validator more strict:

  1. #include <qapplication.h>
  2. #include <qmainwindow.h>
  3. #include <qvalidator.h>
  4. #include <qlineedit.h>
  5.  
  6. class MyDoubleValidator : public QDoubleValidator
  7. {
  8. public:
  9.     MyDoubleValidator( double bottom, double top, int decimals, QObject*
  10.         parent = 0, const char* name = 0 )
  11.         : QDoubleValidator( bottom, top, decimals, parent, name )
  12.     {}
  13.  
  14.     QValidator::State validate ( QString & input, int &pos ) const
  15.     {
  16.         if ( input.isEmpty() || input == "." )
  17.             return Intermediate;
  18.         if ( QDoubleValidator::validate( input, pos ) != Acceptable ) {
  19.             return Invalid;
  20.         }
  21.         return Acceptable;
  22.     }
  23. };
  24.  
  25. class Widget : public QMainWindow
  26. {
  27.     Q_OBJECT
  28. public:
  29.     Widget( QWidget* parent = 0, const char* name = 0 )
  30.         : QMainWindow( parent, name )
  31.     {
  32.         QLineEdit* edit = new QLineEdit( this );
  33.         setCentralWidget( edit );
  34.         edit->setValidator( new MyDoubleValidator( 0.0, 1.0, 3, edit ) );
  35.     }
  36. };
  37.  
  38. #include "main.moc"
  39.  
  40. int main( int argc, char **argv )
  41. {
  42.     QApplication a( argc, argv );
  43.     Widget w;
  44.     w.show();
  45.     return a.exec();
  46. }

2 comments

July 7, 2010

Picture of liviuo liviuo

Lab Rat

to accept negative numbers one should replace:

  1. if ( input.isEmpty() || input == "." )

with:
  1. if ( input.isEmpty() || input == "." || input == "-" || input == "-." )

March 22, 2011

Picture of bamboo bamboo

Lab Rat

I changed to the following to allow either positive or negative, depending on the set bounds:

  1. if (this->bottom() < 0 && (input.isEmpty() || input == "." || input == "-" || input == "-.")
  2.             || this->bottom() >= 0 && (input.isEmpty() || input == "."))

Write a comment

Sorry, you must be logged in to post a comment.