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...
The signature of
QAbstractSpinBox::validate()
is:So your
validate()
method's signature differs in two ways: its notconst
, and you haveint pos
instead ofint& pos
. Thus it doesn't overrideQAbstractSpinBox::validate
and is never called byQAbstractSpinBox
.If you can extend the lower bound of your range by -1 and use a normal
QSpinBox
orQDoubleSpinBox
and callspinbox->specialValueText("nan")
, which will show the stringnan
whenvalue() == minimum()
. The user won't be able to enter the string "nan" manually, but you can always accompany the spinbox with a button that executesspinbox->setValue(spinbox->minimum())
. Here's a compilable example:Maybe QSpinBox sets a lineEdit wich has a QIntValidator as QValidator. At least the docs of QAbstractSpinBox::setLineEdit suggest that the validator of the lineEdit has priority over the QAbstractSpinBox::validate function.