C++ 使用NaN值子类化QDoubleSpinBox
我将QDoubleSpinBox子类化,以创建一个QDoubleSpinBox,允许用户输入NaN作为有效输入。现在,如果用户在spinbox中输入“nan”,控件将自动将文本更改为DBL_MAX的值,而不是保持为nan。在开始使用math.h库和nan和isnan函数之前,我刚刚定义nan_值为1000,范围为-1000到1000。然后在我的文本FromValue中,我检查值是否等于NAN_值。同样,在valueFromText函数中,我返回的是NAN_值。当我这样做时,它工作了,但我希望能够使用nan和isnan函数。现在,我添加了nan和isnan函数调用,它停止了工作。有人知道为什么吗?另外,当我使用DBL_MIN和DBL_MAX作为范围时,我注意到我的早期实现有这个问题。对于控制来说,这些数字的范围是否太大?如果我把范围缩小,比如-1000和1000,效果很好 以下是我的实现: CustomDoubleSpinBox.hC++ 使用NaN值子类化QDoubleSpinBox,c++,qt,nan,math.h,C++,Qt,Nan,Math.h,我将QDoubleSpinBox子类化,以创建一个QDoubleSpinBox,允许用户输入NaN作为有效输入。现在,如果用户在spinbox中输入“nan”,控件将自动将文本更改为DBL_MAX的值,而不是保持为nan。在开始使用math.h库和nan和isnan函数之前,我刚刚定义nan_值为1000,范围为-1000到1000。然后在我的文本FromValue中,我检查值是否等于NAN_值。同样,在valueFromText函数中,我返回的是NAN_值。当我这样做时,它工作了,但我希望能够
#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
我很好奇。什么是阻止你使用的?不要紧,特殊值文本不允许用户键入Nan,它只会为所选值显示它。如果键入inf和-inf会发生什么情况?因为它不是有效的双精度字符且不是“Nan”,所以它会将文本更改回以前的值或0。
#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;
}