QDoubleValidator完善版

  使用过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);

  暂未验证,貌似有的同学说有效,有的说无效,聊以附记。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值