使用过QDoubleValidator的同学都知道,QDoubleValidator在Qt中实现并不完善,导致使用时存在bug,但是幸好,Qt提供了validate的虚函数,让我们可以重写它,以下是我实现的一个QDoubleValidator版本,暂时没有发现什么问题。
//***********************QDoubleValidator.h*************************//
#ifndef QTVEDITORDOUBLEVALIDATOR_H
#define QTVEDITORDOUBLEVALIDATOR_H
#include <QDoubleValidator>
class QtVEditorDoubleValidator : public QDoubleValidator
{
public:
explicit QtVEditorDoubleValidator(QObject * parent = Q_NULLPTR);
QtVEditorDoubleValidator(double bottom, double top, int decimals, QObject *parent = Q_NULLPTR);
QValidator::State validate(QString &str, int &i) const;
};
#endif // QTVEDITORDOUBLEVALIDATOR_H
//***********************QDoubleValidator.cpp*************************//
#include "QtVEditorDoubleValidator.h"
#include <QString>
QtVEditorDoubleValidator::QtVEditorDoubleValidator(QObject *parent)
:QDoubleValidator(parent)
{
}
QtVEditorDoubleValidator::QtVEditorDoubleValidator(double bottom, double top, int decimals, QObject *parent)
:QDoubleValidator(bottom,top,decimals,parent)
{
}
QValidator::State QtVEditorDoubleValidator::validate(QString &str, int &i) const
{
if(str.isEmpty())
return QValidator::Intermediate;
if (bottom() >= 0 && str.startsWith('-'))
return Invalid;
int dotPos = str.indexOf(".");
if(dotPos > 0 && str.right(str.length() - dotPos - 1).length() > decimals()) //判断小数点位数
return Invalid;
bool ok = false;
double val = str.toDouble(&ok);
if(!ok)
return (bottom() < 0 && !str.compare("-")) ? Intermediate : Invalid;
if(val <= top() && val >= bottom())
return Acceptable;
if (val >= 0)
return (val > top() && -val < bottom()) ? Invalid : Intermediate;
else
return (val < bottom()) ? Invalid : Intermediate;
}
附记:
偶然翻了下网上的其他博客,发现有一种解决方式如下:
speedValidator.setRange(0, 2000, 2);
speedValidator.setNotation(QDoubleValidator::StandardNotation);
ui.setSpeedEdt->setValidator(&speedValidator);
暂未验证,貌似有的同学说有效,有的说无效,聊以附记。