QAbstractSpinBox的功能验证

时间:2019-03-20 10:53:53

标签: qt qdoublespinbox

我正在QT Docu中阅读此功能

它说

  

QValidator::State QAbstractSpinBox::validate(QString &input, int &pos) const [virtual]

     

QAbstractSpinBox调用此虚拟函数以确定 input 是否有效。 pos 参数指示字符串中的位置。在各个子类中重新实现。

我有一个奇怪的问题,因为我不太了解这份文件。这里的 input 是一个字符串,我们确定 input 是否有效。那么,为什么我们需要字符串中的位置呢?我以为 pos 在这里是字符串的长度,但是当我调试时,它不是真的。那么 pos 是什么意思?

更新:

感谢@mohabouje。在我的情况下,我使用从QAbstractSpinBox继承的类,我重写了此方法,并希望在更改字符串后对其进行验证。我如何更新此pos进行验证?

QValidator::State MySpinBox::validate( QString &input, int &pos ) const
{
    QString pureValue = stripped( input, &tmpPos, prefix(), suffix() );  //this is my function, i just want to remove also prefix and suffix 
    //I want to add group separator into the pureValue and validate it after that
    //I want to add group separator here, not in the constructor with setGroupSeparatorShown(true);
    //When i add group separator here, the separator appears simultaneously when we type
    //When i set setGroupSeparatorShown(true) in the constructor, it appears after we finish editing and move to another thing (this element loses focus) 
    pureValue.insert(3, locale().groupSeparator());
    input = pureValue;

     // I think now 'pos' has changed, how could I update 'pos' to call the following function?
     QValidator::State state = QDoubleSpinBox::validate( input, pos );
     return state;
}

1 个答案:

答案 0 :(得分:1)

我很好奇底层的实现。我检查了github中的源代码。

QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
                                                     QValidator::State &state) const
{
    if (cachedText == input && !input.isEmpty()) {
        state = cachedState;
        QSBDEBUG() << "cachedText was '" << cachedText << "' state was "
                   << state << " and value was " << cachedValue;
        return cachedValue;
    }
    const double max = maximum.toDouble();
    const double min = minimum.toDouble();

    QString copy = stripped(input, &pos);
    QSBDEBUG() << "input" << input << "copy" << copy;
    int len = copy.size();
    ...
}

参数在称为stripped的私有函数中使用。这是源代码:

QString QAbstractSpinBoxPrivate::stripped(const QString &t, int *pos) const
{
    QString text = t;
    if (specialValueText.size() == 0 || text != specialValueText) {
        int from = 0;
        int size = text.size();
        bool changed = false;
        if (prefix.size() && text.startsWith(prefix)) {
            from += prefix.size();
            size -= from;
            changed = true;
        }
        if (suffix.size() && text.endsWith(suffix)) {
            size -= suffix.size();
            changed = true;
        }
        if (changed)
            text = text.mid(from, size);
    }

    const int s = text.size();
    text = text.trimmed();
    if (pos)
        (*pos) -= (s - text.size());
    return text;

}

因此,如果我正确理解,给定字符串和前缀/后缀配置,该函数将使用字符串并计算要验证的数据的实际大小,而忽略前缀和后缀。

该函数返回已验证的数据,可以对其进行分析以计算数值。

pos的原始值,该函数减去要验证的文本大小与执行修剪操作后的文本大小之差。