Skip to content

Instantly share code, notes, and snippets.

@mpiannucci
Last active July 17, 2017 19:21
Show Gist options
  • Save mpiannucci/54fbec858c1e8af724cb to your computer and use it in GitHub Desktop.
Save mpiannucci/54fbec858c1e8af724cb to your computer and use it in GitHub Desktop.
A custom implementation of QDoubleValidator to allow comma-seperated numerical values
#include "vectordoublevalidator.h"
// VectorDoubleValidator Constructor
VectorDoubleValidator::VectorDoubleValidator ( double bottom, double top, int decimals,
QObject* parent = 0 )
: QDoubleValidator ( bottom, top, decimals, parent ) {
}
// Custom validate function to allow comma seperated values
QValidator::State VectorDoubleValidator::validate ( QString& input, int& ) const {
const double b = bottom();
const double t = top();
const int d = decimals();
// Check if the input has a comma
if ( input.contains ( "," ) ) {
QStringList numList;
numList = input.split ( "," );
bool ok = false;
// It does so iterate through it and parse out the values
for ( QString num : numList ) {
double entered = num.toDouble ( &ok );
if ( !ok && !num.size() ) {
// Allow the user to delete or leave an area blank
ok = true;
} else if ( !ok && ( num == "." ) ) {
// All the user to enter a decimal first
ok = true;
} else if ( !ok && ( num == " " ) ) {
// Allow the user to have a space in between the comma and the dumber or decimal.
// Allows deletion you couldn't do before.
ok = true;
}
if ( !ok || entered > t || entered < b ) {
// its either out of range or not a number, so invalid
return Invalid;
} else if ( num.contains ( "." ) ) {
QStringList dec = num.split ( "." );
if ( dec[1].size() > d ) {
// Too many decimal points
return Invalid;
}
}
}
} else {
// There are no commas, so make sure numbers are valid doubles
bool ok;
double entered = input.toDouble ( &ok );
if ( !ok && !input.size() ) {
// Handle an edge case where there are no characters left.
ok = true;
} else if ( !ok && ( input == "." ) ) {
// If the only character is a decimal, then it is fine.
ok = true;
}
if ( !ok || entered > t || entered < b ) {
// Not a number or out of range, so invalid
return Invalid;
} else if ( input.contains ( "." ) ) { // If it cant, check for a decimal point and how many numbers follow
QStringList dec = input.split ( "." );
if ( dec[1].size() > d ) {
// Too many decimals
return Invalid;
}
}
}
// Its Acceptable!
return Acceptable;
}
#ifndef _VECTOR_DOUBLE_VALIDATOR_H
#define _VECTOR_DOUBLE_VALIDATOR_H
#include <QValidator.h>
#include <QString>
class VectorDoubleValidator : public QDoubleValidator {
public:
VectorDoubleValidator ( double bottom, double top, int decimals, QObject* parent );
QValidator::State validate ( QString& input, int& ) const;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment