12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #ifndef __COMMONFUNC_H__
- #define __COMMONFUNC_H__
- #include <QDoubleValidator>
- /*--------------------------------------------------------------------------
- * 公共小函数,解决一些通用的bug
- *--------------------------------------------------------------------------*/
- /* 严格范围限制的 QDoubleValidator 解决原有的不是限制范围的bug */
- class StrictDoubleValidator : public QDoubleValidator
- {
- public:
- StrictDoubleValidator(double bottom, double top, int decimals, QObject *parent = nullptr)
- : QDoubleValidator(bottom, top, decimals, parent) {}
- State validate(QString &input, int &pos) const override
- {
- // 允许空输入(方便编辑)
- if (input.isEmpty() || input == "-" || input == "." || input == "-.")
- return Intermediate;
- bool ok = false;
- double val = input.toDouble(&ok);
- if (!ok)
- return Invalid;
- // 检查小数位数
- int dot = input.indexOf('.');
- if (dot >= 0 && input.length() - dot - 1 > decimals())
- return Invalid;
- // 范围检查
- if (val < bottom() || val > top())
- return Invalid;
- return Acceptable;
- }
- };
- /* 限制Int范围 */
- class StrictIntValidator : public QIntValidator
- {
- public:
- StrictIntValidator(int bottom, int top, QObject *parent = nullptr)
- : QIntValidator(bottom, top, parent) {}
- State validate(QString &input, int &pos) const override
- {
- // 允许空输入(方便编辑)
- if (input.isEmpty() || input == "-")
- return Intermediate;
- bool ok = false;
- int val = input.toInt(&ok);
- if (!ok)
- return Invalid;
- /* 如果范围都是正数,只检查最大值 */
- if(bottom() > 0)
- {
- if(val > top())
- return Invalid;
- }
- else if(top() < 0) // 如果范围都是负数,只检查最小值
- {
- if(val < bottom())
- return Invalid;
- }
- else // 范围有正有负,检查上下限
- {
- if(val < bottom() || val > top())
- return Invalid;
- }
- return Acceptable;
- }
- };
- #endif // __COMMONFUNC_H__
|