I have a QLineEdit
with a QDoubleValidator
, calling QDoubleValidator::setRange
will not validate the current text of the QLineEdit
.
How could I programmatically validate (focusing and unfocusing it with the mouse work )
Here is the code of my inherited QDoubleValidator
DoubleValidator::DoubleValidator( QObject* parent ) :
Superclass( parent )
{
}
DoubleValidator::~DoubleValidator()
{
}
void DoubleValidator::fixup ( QString & input ) const
{
if( input.toDouble() > top() )
{
input = QString::number( top() , 'f' );
}
else if( input.toDouble() < bottom() )
{
input = QString::number( bottom() , 'f' );
}
}
And the code of my inherited QLineEdit
:
DoubleLineEdit::DoubleLineEdit( QWidget* parent ) :
Superclass( parent )
{
_validator = new DoubleValidator( this );
this->setValidator( _validator );
}
DoubleLineEdit::~DoubleLineEdit()
{
}
void DoubleLineEdit::setRange( double min, double max )
{
_validator->setRange( min, max, 1000 );
validate();
}
void DoubleLineEdit::setTop( double top )
{
_validator->setTop( top );
validate();
}
void DoubleLineEdit::setBottom( double bottom )
{
_validator->setBottom( bottom );
validate();
}
void DoubleLineEdit::validate()
{
if( !hasAcceptableInput() )
{
cout<<"Validation needed"<<endl;
}
}
When I call DoubleLineEdit::setRange()
, the current text of the DoubleLineEdit
is not validated and fixed.
DoubleLineEdit* edit = new DoubleLineEdit( this );
edit->setText("100");
edit->setRange( 0, 10);
With this code, edit->text()
will still be 100, I would like it to change automatically to 10.
I've implemented a working DoubleLineEdit::validate
method:
void DoubleLineEdit::validate()
{
if( !hasAcceptableInput() )
{
QFocusEvent* e = new QFocusEvent( QEvent::FocusOut );
this->focusOutEvent( e );
delete e;
}
}
But it is more of a trick, and there is maybe a better solution.
Try changing your validate()
function to:
void DoubleLineEdit::validate()
{
if (!hasAcceptableInput())
{
QString t = text();
_validator->fixUp(t);
setText(t);
}
}