commonFunc.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #ifndef __COMMONFUNC_H__
  2. #define __COMMONFUNC_H__
  3. #include <QDoubleValidator>
  4. /*--------------------------------------------------------------------------
  5. * 公共小函数,解决一些通用的bug
  6. *--------------------------------------------------------------------------*/
  7. /* 严格范围限制的 QDoubleValidator 解决原有的不是限制范围的bug */
  8. class StrictDoubleValidator : public QDoubleValidator
  9. {
  10. public:
  11. StrictDoubleValidator(double bottom, double top, int decimals, QObject *parent = nullptr)
  12. : QDoubleValidator(bottom, top, decimals, parent) {}
  13. State validate(QString &input, int &pos) const override
  14. {
  15. // 允许空输入(方便编辑)
  16. if (input.isEmpty() || input == "-" || input == "." || input == "-.")
  17. return Intermediate;
  18. bool ok = false;
  19. double val = input.toDouble(&ok);
  20. if (!ok)
  21. return Invalid;
  22. // 检查小数位数
  23. int dot = input.indexOf('.');
  24. if (dot >= 0 && input.length() - dot - 1 > decimals())
  25. return Invalid;
  26. // 范围检查
  27. if (val < bottom() || val > top())
  28. return Invalid;
  29. return Acceptable;
  30. }
  31. };
  32. #endif // __COMMONFUNC_H__