我将QDoubleSpinBox子类化,以便创建一个允许用户输入NaN作为有效输入的QDoubleSpinBox。现在,如果用户在旋转框中输入“nan”,则控件会自动将文本更改为DBL_MAX的值,而不是保持为nan。在我开始使用带有nan和isnan函数的math.h库之前,我刚刚将NAN_VALUE定义为1000,范围为-1000到1000.然后在我的textFromValue中,我检查了值是否等于NAN_VALUE。同样在valueFromText函数中,我返回NAN_VALUE。当我这样做它有效但我希望能够使用nan和isnan函数。现在我添加了nan和isnan函数调用它停止工作。有谁知道那是为什么?另外,当我使用DBL_MIN和DBL_MAX作为范围时,我注意到我在早期实现中遇到了这个问题。这些数字是否超出控制范围?如果我使范围变小,如-1000和1000,它工作得很好..
这是我的实施:
CustomDoubleSpinBox.h
#ifndef CUSTOMDOUBLESPINBOX_H
#define CUSTOMDOUBLESPINBOX_H
#include <QDoubleSpinBox>
#include <QWidget>
#include <QtGui>
#include <iostream>
#include <math.h>
#include <float.h>
#include <limits>
#define NUMBER_OF_DECIMALS 2
using namespace std;
class CustomDoubleSpinBox : public QDoubleSpinBox
{
Q_OBJECT
public:
CustomDoubleSpinBox(QWidget *parent = 0);
virtual ~CustomDoubleSpinBox() throw() {}
double valueFromText(const QString &text) const;
QString textFromValue(double value) const;
QValidator::State validate ( QString & input, int & pos ) const;
};
#endif // CUSTOMDOUBLESPINBOX_H
CustomDoubleSpinBox.cpp
#include "CustomDoubleSpinBox.h"
CustomDoubleSpinBox::CustomDoubleSpinBox(QWidget *parent) : QDoubleSpinBox(parent)
{
this->setRange(DBL_MIN, DBL_MAX);
this->setDecimals(NUMBER_OF_DECIMALS);
}
QString CustomDoubleSpinBox::textFromValue(double value) const
{
if (isnan(value))
{
return QString::fromStdString("NaN");
}
else
{
QString result;
return result.setNum(value,'f', NUMBER_OF_DECIMALS);
}
}
double CustomDoubleSpinBox::valueFromText(const QString &text) const
{
if (text.toLower() == QString::fromStdString("nan"))
{
return nan("");
}
else
{
return text.toDouble();
}
}
QValidator::State CustomDoubleSpinBox::validate ( QString & input, int & pos ) const
{
Q_UNUSED(input);
Q_UNUSED(pos);
return QValidator::Acceptable;
}