class MyDoubleValidator : public QDoubleValidator {
public:
MyDoubleValidator(double bottom, double top, int decimals,
QObject *parent = 0)
: QDoubleValidator(bottom, top, decimals, parent) {}
QValidator::State validate(QString &s, int &i) const {
if (s.isEmpty() || s == "-") {
return QValidator::Intermediate;
}
QChar decimalPoint = locale().decimalPoint();
if (s.indexOf(decimalPoint) != -1) {
int charsAfterPoint = s.length() - s.indexOf(decimalPoint) - 1;
if (charsAfterPoint > decimals()) {
return QValidator::Invalid;
}
}
QValidator::State result;
bool ok;
double d = locale().toDouble(s, &ok);
// 上下限都是正数
if (bottom() > 0 && top() > 0) {
if (d > 0 && s.length() < QString("%1").arg(top()).length()) {
result = Intermediate;
} else {
result = Invalid;
}
} // 下限为负数,上限为整数
else if (bottom() < 0 && top() > 0) {
if (d > bottom() && d < top()) {
result = Intermediate;
} else {
result = Invalid;
}
} // 上下限都是负数
if (bottom() < 0 && top() < 0) {
if (d < 0 && s.length() < QString("%1").arg(bottom()).length()) {
result = Intermediate;
} else {
result = Invalid;
}
}
if (ok && d >= bottom() && d <= top()) {
result = QValidator::Acceptable;
}
return result;
}
};
QLineEdit限制浮点数输入
于 2021-08-16 12:11:11 首次发布