PDA

View Full Version : QLineEdit: how to avoid characters insertion?



QAlex
18th January 2010, 09:54
Hi,
I would like to control the input of a QlineEdit in order to avoid the insertion of some characters.
I've written down the subsequent code that every time the user insert a new element in the QLineEdit, controls the input and erase the last character of the line if it is not valid!



void ElaborationOffset::ElaborationOffset()
{
[...]
par2 = new QLineEdit;
connect(par2,SIGNAL(textChanged(QString)),this,SLO T(updateGraph(QString)));
[...]
}

void ElaborationOffset::updateGraph(QString dummy)
{
bool ok;
int pos=0;
QString par2Str = par2->text();

QRegExp expr("[-,+]{0,1}[0-9]+[.,,][0-9]+");
QRegExpValidator v(expr, 0);

if(v.validate(par2Str,pos) == QValidator::Invalid)
{
par2->backspace();
return;
}

[...]
}


It works... But the problem is that when I try to insert a non valid char, the updateGraph slot is called 2 times, because of the par2->backspace(); instruction that triggers another signal--->slot call !!!
I think there is no mask that I can use to avoid this problem, because I cannot know the number format (it depends on the particular value)...! For example I can insert -0.0002, but also 12900!!!
Any hints to solve this problem?

Thank you all. :)
Alex

wagmare
18th January 2010, 10:17
just a little suggestion .. use editingFinished() signal instead of textChanged() if user only edits the lineEdit ...

boudie
18th January 2010, 10:32
Have a look at QLineEdit::setValidator.

QAlex
18th January 2010, 10:46
just a little suggestion .. use editingFinished() signal instead of textChanged() if user only edits the lineEdit ...

Yes... could be a solution, but I'd like to avoid completely the insertion of letters (I mean A-Z, a-z).
I want that the user is completely unable to insert the avoided characters!

QAlex
18th January 2010, 11:04
Have a look at QLineEdit::setValidator.

OK!! This is the solution. I tried before, but It didn't function because I wrote the subsequent code:


par2 = new QLineEdit;
QRegExp expr("[-,+]{0,1}[0-9]+[.,,][0-9]+");
QRegExpValidator v(expr, 0);
par2->setValidator(&v);


instead of:



par2 = new QLineEdit;
QRegExp expr("[-,+]{0,1}[0-9]+[.,,][0-9]+");
QRegExpValidator *v = new QRegExpValidator(expr, 0);
par2->setValidator(v);


Well... thank you for your hint...
Another question: Could you please explain why the first solution doesn't work, while the second works?
I have encountered this problem other times, but I've not clear the real cause of this problem!

Thank you very much!
:)