【发布时间】:2012-04-12 23:37:33
【问题描述】:
我正在尝试扩展 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 文件:
#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
我有什么遗漏吗?还是做错了?如果有更简单的方法来做到这一点,那就太好了......
【问题讨论】:
-
关于您的代码的一些建议,与问题无关:(1) 不要使用 throw 规范,除非您必须这样做,因为基类确实如此(Sutter/Alexandrescu,第 75 条)。 (2) 让您的 ctor
explicit(同上,第 40 条)。 (3) 不要在标题中写using namespace(同上,第 59 条)。 (4) 使用static const int NAN_VALUE = 32767;代替#define(同上,第16 项)。 (5) 不要#include <QtGui>(减慢编译速度)。 (6) 使用QLatin1String("nan")代替QString::fromStdString("nan")(更快)。