我有一组 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/