I have a set of QLineEdits that are supposed to accept double values within a certain range, (e.g., -15 to 15).
I have something along these lines when
The answer of VVV works great for the orignal question of nicole. This is when the range is from negative to positive.
However as a general solution for QDoubleValidator it has one side effect when the range is from positive to positive:
Example: Range: [87.5 ... 1000.0], Input: "15" (as intermediate to reach the value 150)
The input will be declined when the QLineEdit goes under the lower limit (or starts empty). Hence I extended the solution of VVV for a general solution:
/*
* Empty string and the negative sign are intermediate
*/
if( input.isEmpty() || input == "-" )
{
return QValidator::Intermediate;
}
/*
* Check numbers of decimals after the decimal point
* and the number of decimal points
*/
QChar decimalPoint = locale().decimalPoint();
if( input.count( decimalPoint, Qt::CaseInsensitive ) > 1 )
{
return QValidator::Invalid;
}
else if( input.indexOf( decimalPoint ) != -1)
{
const int charsAfterPoint = input.length() - input.indexOf( decimalPoint) - 1;
if( charsAfterPoint > decimals() )
{
return QValidator::Invalid;
}
}
/*
* Check for valid double conversion and range
*/
bool ok;
const double d = locale().toDouble( input, &ok );
if( ok && d <= top() )
{
if( d >= bottom() )
{
return QValidator::Acceptable;
}
else
{
return QValidator::Intermediate;
}
}
else
{
return QValidator::Invalid;
}