Qt中QLineEdit如何限制小数的范围(QDoubleValidator失效下解决方法)

来源:互联网 发布:php unity3d 编辑:程序博客网 时间:2024/06/07 00:19

限制小数范围,乍看起来很简单,不是有QDoubleValidator吗?一用,没效果,我Qt版本5.6,其他版本什么情况就不知道了。。

百度,解决方法:继承QDoubleValidator,重写validate方法。

在Stackoverflow上看到的demo:

class MyDoubleValidator : public QDoubleValidator{public:    MyDoubleValidator(double bottom, double top, int decimals, QObject *parent = 0)        :QDoubleValidator( bottom, top, decimals, parent) {};    QValidator::State validate(QString &input, int &pos) const    {        /*         * Original Qt Documentation:         * ---------         * QDoubleValidator::validate()         * Returns Intermediate if input contains a double that is         * outside the range or is in the wrong format; e.g. with too many         * digits after the decimal point or is empty.         * ---------         * Problem: Not what the user expects.         * Example: Range 0.0-10.0 with 1 digit (QDoubleValidator( 0, 10, 1, parent ) ):         * QDoubleValidator::validate() reports intermediate for "10.3".         * However we expect invalid instead and QLineEdit to decline input.         * Fix this by overloading the validate() operator.         */        const QValidator::State origState = QDoubleValidator::validate( input, pos );        if( ( origState == QValidator::Intermediate ) && ( input.toDouble() > top() ) )        {            return QValidator::Invalid;        }        else        {            return origState;        }    }};

https://stackoverflow.com/questions/10119310/qdoublevalidator-is-not-working

但有问题,限制不了下限。

继续找:

csdn的blog上看到的:

virtual State validate(QString &str, int &i) const{if (str.isEmpty()){return QValidator::Intermediate;}int a = 1;bool cOK = false;double val = str.toDouble(&cOK);if (!cOK){return QValidator::Invalid;}int dotPos = str.indexOf(".");if (dotPos > 0){if (str.right(str.length() - dotPos-1).length() > decimals()){return QValidator::Invalid;}}if (val< top() && val > bottom()){return QValidator::Acceptable;}return QValidator::Invalid;}};

http://blog.csdn.net/caoqiang2006/article/details/53237188

问题又来了,小数位数限制不了了。

东拼西凑研究了一下,有个不完美的解决方案:

virtual QValidator::State validate(QString &input, int &pos) const    {        const QValidator::State origState = QDoubleValidator::validate( input, pos );        if(input.isEmpty())        {            return QValidator::Intermediate;        }        if( ( origState == QValidator::Intermediate ) && (input.toDouble() > top())  )        {            return QValidator::Invalid;        }        if(( origState == QValidator::Intermediate ) && ( input.toDouble() < bottom())  )        {            return QValidator::Intermediate;        }        else        {            return origState   /*QValidator::Acceptable*/;        }    }


不完美之处:如果下限设置为0.5,输入的时候0就无法输入了,也就是说[0.51-1)之间的数字都输入不了了。

解决了:1、能处理上下限;

               2、可清空输入

由于我的需求里面小数都是0.5的整数倍,所以刚好能用,但还是有改善的空间。

尚待改善。。如果有更好的解决方法后续再更新。

Qt萌新一枚,如有不合理之处或有更好的解决方案,还望不吝教正。



阅读全文
1 0
原创粉丝点击