QSpinBox 输入 NaN 作为有效值

2024-05-11

我正在尝试扩展 QSpinBox 以能够输入“NaN”或“nan”作为有效值。根据文档,我应该使用 textFromValue、valueFromText 和 validate 函数来完成此操作,但我无法让它工作,因为它仍然不允许我输入除数字之外的任何文本。这是我的 .h 和 .cpp 文件中的内容:

CPP文件:

#include "CustomIntSpinBox.h"

CustomIntSpinBox::CustomIntSpinBox(QWidget *parent) : QSpinBox(parent)
{
    this->setRange(-32767,32767);
}

QString CustomIntSpinBox::textFromValue(int value) const
{
    if (value == NAN_VALUE)
    {
        return QString::fromStdString("nan");
    }
    else
    {
        return QString::number(value);
    }
}

int CustomIntSpinBox::valueFromText(const QString &text) const
{
    if (text.toLower() == QString::fromStdString("nan"))
    {
        return NAN_VALUE;
    }
    else
    {
        return text.toInt();
    }
}

QValidator::State validate(QString &input, int pos)
{
    return QValidator::Acceptable;
}

H file:

#ifndef CUSTOMINTSPINBOX_H
#define CUSTOMINTSPINBOX_H

#include <QSpinBox>
#include <QWidget>
#include <QtGui>
#include <iostream>

using namespace std;

#define NAN_VALUE 32767

class CustomIntSpinBox : public QSpinBox
{
    Q_OBJECT

public:
    CustomIntSpinBox(QWidget *parent = 0);
    virtual ~CustomIntSpinBox() throw() {}

    int valueFromText(const QString &text) const;
    QString textFromValue(int value) const;
    QValidator::State validate(QString &input, int pos);
};

#endif // CUSTOMINTSPINBOX_H

我缺少什么吗?还是做错了?如果有一种更简单的方法来做到这一点,那就很高兴知道......


的签名QAbstractSpinBox::validate() is:

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

So your validate()方法的签名有两个不同之处:它不是const, 你有int pos代替int& pos。因此它不会覆盖QAbstractSpinBox::validate并且从未被调用过QAbstractSpinBox.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

QSpinBox 输入 NaN 作为有效值 的相关文章

随机推荐