c++ - 仅允许在 QDoubleValidator 的范围内进入 QLineEdit

标签 c++ qt validation qlineedit

我有一组 QLineEdits 应该接受一定范围内的 double 值(例如,-15 到 15)。

在设置每个时,我有一些类似的东西:

lineEdit->setValidator(new QDoubleValidator(minVal, maxVal, 5, lineEdit));

理想情况下,行编辑可以只输入范围内的值。当我尝试这个时,我注意到只能按需要输入数字,但它们仍然可能超出范围。

我如何动态地强制输入适合范围(例如,如果范围是 -15 到 15 并且用户键入 1,然后尝试键入 9,它不起作用/显示 9...但是输入 1 然后输入 2 确实有效/显示 2.) ?

我是否需要在某处连接并调用 validate() 函数?

最佳答案

这是因为 QDoubleValidator 在值超出范围时返回 QValidator::Intermediate 并且 QLineEdit 接受 QValidator::Intermediate 值。

要实现您想要的行为,您可以创建自己的 QDoubleValidator 子类,如下所示:

class MyValidator : public QDoubleValidator
{
public:
    MyValidator(double bottom, double top, int decimals, QObject * parent) :
        QDoubleValidator(bottom, top, decimals, parent)
    {
    }

    QValidator::State validate(QString &s, int &i) const
    {
        if (s.isEmpty()) {
            return QValidator::Intermediate;
        }

        bool ok;
        double d = s.toDouble(&ok);

        if (ok && d > 0 && d < 15) {
            return QValidator::Acceptable;
        } else {
            return QValidator::Invalid;
        }
    }
};

更新:这将解决负号问题,并且还将接受语言环境 double 格式:

class MyValidator : public QDoubleValidator
{
public:
    MyValidator(double bottom, double top, int decimals, QObject * parent) :
        QDoubleValidator(bottom, top, decimals, parent)
    {
    }

    QValidator::State validate(QString &s, int &i) const
    {
        if (s.isEmpty() || s == "-") {
            return QValidator::Intermediate;
        }

        QChar decimalPoint = locale().decimalPoint();

        if(s.indexOf(decimalPoint) != -1) {
            int charsAfterPoint = s.length() - s.indexOf(decimalPoint) - 1;

            if (charsAfterPoint > decimals()) {
                return QValidator::Invalid;
            }
        }

        bool ok;
        double d = locale().toDouble(s, &ok);

        if (ok && d >= bottom() && d <= top()) {
            return QValidator::Acceptable;
        } else {
            return QValidator::Invalid;
        }
    }
};

关于c++ - 仅允许在 QDoubleValidator 的范围内进入 QLineEdit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571033/

相关文章:

c++ - 获取 4 位整数的倒数第二个值

python - 如何切换到外部应用程序?

multithreading - XInitThreads() 的缺点是什么?

asp.net-mvc - 验证失败后重新填充嵌套 ViewModel

javascript - 使用 jQuery 检查 4 个数字和 2 个字母的输入

c++ - 为什么具有两个元素的初始化语法将一个元素而不是两个元素放入字符串 vector ?

c++ - 使用自定义着色器的 OpenGL/ES 渲染 = 网格上的伪影

c++ - Linux UDP 服务器 - 目标 IP 错误

qt - 如何更改 Qml 中 ListView 滚动条的位置

asp.net - asp.net 中的高级搜索表单验证