在QML中指定小数符号
我想让用户只使用小数点符号,无论他的机器是哪个语言环境。 例如,我们支持en_US和nl_NL,但在两种语言设置中,我们都希望将用户限制为仅使用点作为十进制符号。 (与之通信的遗留系统)
我尝试了不同的方法:
QLocale newLanguageLocale = QLocale(QLocale::Dutch, QLocale::Netherlands);
newLanguageLocale.setNumberOptions(QLocale::c().numberOptions());
QLocale::setDefault(newLanguageLocale);
在QML中:
Item
{
property int numberOfDecimals: 3
TextInput
{
validator: doubleChecker
}
DoubleValidator
{
id: doubleChecker
decimals: numberOfDecimals
notation: DoubleValidator.StandardNotation
}
}
所以我尝试使用TextInput
在RegExpValidator
中解决它,但这并不能让我创建正则表达式。我需要的是因为numberOfDecimals
可以更改。
RegExpValidator
{
id: doubleChecker
//regExp: /^-?[0-9]+(\.[0-9]{1,3})?$/ // This works (3 decimals), but I want to be able have a specified numberOfDecimals (some fields have different settings)
regExp: new RegExp('/^-?[0-9]+(\.[0-9]{1,' + numberOfDecimals + '})?$/') // doesn't work, can enter unlimited amount of decimals. Also when field is empty, I cannot type
}
知道怎么办吗?我是否在RegExpValidator
答案 0 :(得分:3)
您需要正确使用构造函数表示法。这意味着:
"\\."
以匹配文字点,或者它将匹配除换行符之外的任何字符),或用{{1}将其括起来},一个字符类[...]
,称为正则表达式分隔符,因为它们用于正则表达式文字表示法。所以,你需要
/
或
new RegExp("^-?[0-9]+([.][0-9]{1," + numberOfDecimals + "})?$")
在这里使用构造函数表示法是正确的,因为只有这种表示法允许将变量传递给正则表达式模式。
详细了解如何使用RegExp
at MDN。