QDoubleValidator设置上下限无效的解决方法

采用如下方法对QLineEdit设置浮点数上下限值时,实际运行时会发现不启作用。

QDoubleValidator* v = new QDoubleValidator(-9999,9999,6,this);

QLineEdit  *pLineEdit = new QLineEdit;
pLineEdit->setValidator(v);

解决方法有2:

  方法1:继承重新写

class MyDoubleValidator: public QDoubleValidator
{
public:
	explicit MyDoubleValidator(QObject * parent = 0)
		:QDoubleValidator(parent)
	{

	}

	MyDoubleValidator(double bottom, double top, int decimals, QObject *parent = 0):QDoubleValidator(bottom, top,decimals, parent)
	{
	}

	~MyDoubleValidator() 
	{

	}

	virtual State validate(QString &str, int &i) const
	{
		if (str.isEmpty())
		{
			return QValidator::Intermediate;
		}
		int a = 1;
		bool cOK = false;
		double val = str.toDouble(&cOK);

		if (!cOK)
		{
			return QValidator::Invalid;
		}

		int dotPos = str.indexOf(".");
		if (dotPos > 0)
		{
			if (str.right(str.length() - dotPos-1).length() > decimals())
			{
				return QValidator::Invalid;
			}
		}
		if (val< top() && val > bottom())
		{
			return QValidator::Acceptable;
		}

		return QValidator::Invalid;
	}

	virtual void fixup(QString &s) const
	{
		if( s.toDouble() < bottom() )
		{
			s = QString::number( bottom() );
		}
		else if ( s.toDouble() > top() )
		{
			s = QString::number( top() );
		}
	}
};

方法2:

QDoubleValidator* v = new QDoubleValidator(-9999,9999,6,this);
v->setNotation(QDoubleValidator::StandardNotation);

QLineEdit  *pLineEdit = new QLineEdit;
pLineEdit->setValidator(v);

即增加了“v->setNotation(QDoubleValidator::StandardNotation);”设置。

 

QIntValidator设置方法如上。

你可能感兴趣的:(QT)