commonFunc.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. /* 限制Int范围 */
  33. class StrictIntValidator : public QIntValidator
  34. {
  35. public:
  36. StrictIntValidator(int bottom, int top, QObject *parent = nullptr)
  37. : QIntValidator(bottom, top, parent) {}
  38. State validate(QString &input, int &pos) const override
  39. {
  40. // 允许空输入(方便编辑)
  41. if (input.isEmpty() || input == "-")
  42. return Intermediate;
  43. bool ok = false;
  44. int val = input.toInt(&ok);
  45. if (!ok)
  46. return Invalid;
  47. /* 如果范围都是正数,只检查最大值 */
  48. if(bottom() > 0)
  49. {
  50. if(val > top())
  51. return Invalid;
  52. }
  53. else if(top() < 0) // 如果范围都是负数,只检查最小值
  54. {
  55. if(val < bottom())
  56. return Invalid;
  57. }
  58. else // 范围有正有负,检查上下限
  59. {
  60. if(val < bottom() || val > top())
  61. return Invalid;
  62. }
  63. return Acceptable;
  64. }
  65. };
  66. #endif // __COMMONFUNC_H__