Search code examples
c++qtqspinbox

QSpinBox enter NaN as a valid value


I am trying to extend the QSpinBox to be able to enter "NaN" or "nan" as a valid value. According to the documentation i should use the textFromValue, valueFromText, and validate functions to accomplish this but i cant get it to work since its still not allowing me to enter any text besides numbers. Here is what i have in my .h and .cpp files:

CPP file:

#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

Is there something im missing? or doing wrong? If theres and easier way to do this also that would be great to know...


Solution

  • The signature of QAbstractSpinBox::validate() is:

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

    So your validate() method's signature differs in two ways: its not const, and you have int pos instead of int& pos. Thus it doesn't override QAbstractSpinBox::validate and is never called by QAbstractSpinBox.