您可以编写自己的验证器,从QValidator
. 您所需要的只是实施virtual State validate(QString &input, int &pos) const = 0
.
更新
例子:
MyValidator.h:
class MyValidator : public QValidator
{
Q_OBJECT
public:
MyValidator(double min, double max, QObject *parent = 0);
State validate(QString &input, int &pos) const;
private:
QRegExp mRexp;
double mMin;
double mMax;
};
MyValidator.cpp:
MyValidator::MyValidator(double min, double max, QObject *parent) :
QValidator(parent)
, mRexp("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")
, mMin(min)
, mMax(max)
{}
QValidator::State MyValidator::validate(QString &input, int &pos) const
{
if (input.isEmpty())
return Acceptable;
if (!mRexp.exactMatch(input))
return Invalid;
const double val = input.toDouble();
if (mMin <= val && val <= mMax)
return Acceptable;
return Intermediate;
}