gpt4 book ai didi

c++ - DoubleValidator 没有正确检查范围

转载 作者:太空狗 更新时间:2023-10-29 23:49:57 26 4
gpt4 key购买 nike

让我用一个例子来解释这个问题。

如果我们有一个这样的 TextField

TextField {
text: "0.0"
validator: DoubleValidator { bottom: -359.9;
top: 359.9;
decimals: 1;
notation: DoubleValidator.StandardNotation }

onEditingFinished: {
console.log("I'm here!");
}
}

我们可以键入诸如 444.9399.9-555.5 之类的数字。如您所见,这些值不在 -359.9359.9 之间。

documentation我们可以找到以下信息:

Input is accepted but invalid if it contains a double that is outside the range or is in the wrong format; e.g. with too many digits after the decimal point or is empty.

我以为 DoubleValidator 不接受这种东西,但不幸的是它接受了。

所以我想解决方案是检查最终输入,但我们又遇到了一个问题:editingFinished 仅在验证器返回可接受的状态时才会发出,但情况并非总是如此。

也许我没有采用好的方法,我不了解如何使用 DoubleValidator 或者我可能需要一些 C++ 代码。

顺便说一下,我正在使用 Qt 5.4。

最佳答案

问题在于QML TextField接受中间输入:

validator : Validator

Allows you to set a validator on the TextField. When a validator is set, the TextField will only accept input which leaves the text property in an intermediate state. The accepted signal will only be sent if the text is in an acceptable state when enter is pressed.

validate()-function of QDoubleValidator描述它何时返回 QValidator::Intermediate:

State QValidator::validate(QString & input, int & pos) const

This virtual function returns Invalid if input is invalid according to this validator's rules, Intermediate if it is likely that a little more editing will make the input acceptable (e.g. the user types "4" into a widget which accepts integers between 10 and 99), and Acceptable if the input is valid.

这意味着,验证器返回 QValidator::Intermediate,只要输入 double 值,并且因为 TextField 可以使用“intermediate”,您可以输入任何内容,只要它是数。

你可以做的是继承 QDoubleValidator 并覆盖 validate(),这样当值是越界:

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

QValidator::State validate(QString & s, int & pos) const {
if (s.isEmpty() || (s.startsWith("-") && s.length() == 1)) {
// allow empty field or standalone minus sign
return QValidator::Intermediate;
}
// check length of decimal places
QChar point = locale().decimalPoint();
if(s.indexOf(point) != -1) {
int lengthDecimals = s.length() - s.indexOf(point) - 1;
if (lengthDecimals > decimals()) {
return QValidator::Invalid;
}
}
// check range of value
bool isNumber;
double value = locale().toDouble(s, &isNumber);
if (isNumber && bottom() <= value && value <= top()) {
return QValidator::Acceptable;
}
return QValidator::Invalid;
}

};

关于c++ - DoubleValidator 没有正确检查范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35178569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com