PDA

View Full Version : Accept/Not accept symbols in QLineEdit



naturalpsychic
28th March 2012, 14:42
I have got a class MyLineEdit : QLineEdit

All I want is it to accept symbols if acceptSymbol() returns true and not accept it if it returns false. Has anybody got any idea why my implementation not working?


void MyLineEdit::keyPressEvent(QKeyEvent *key)
{

if (key->key()==Qt::Key_Escape)
emit escapePressed();
else
{
if ((key->key() >=48 ) ||
(key->key() <=57) ||
(key->key() >=65 ) ||
(key->key() <= 90) ||
(key->key() >=97) ||
(key->key() <=122))
{
QLineEdit::keyPressEvent(key);
}
else
{

if (acceptSymbols())
{
QLineEdit::keyPressEvent(key);
}
}
}
}

wysota
28th March 2012, 15:36
Your complex if statement is always true.

naturalpsychic
28th March 2012, 16:26
Thanks :) nice spotted

Added after 19 minutes:

Found a better way




#include "mylineedit.h"
#include <QKeyEvent>
#include <QRegExpValidator>
MyLineEdit::MyLineEdit(QWidget *parent) :
QLineEdit(parent)
{
setMinimumHeight(kDefaultHeight);
setAcceptSymbols(true);
}

void MyLineEdit::keyPressEvent(QKeyEvent *key)
{
if (key->key()==Qt::Key_Escape)
emit escapePressed();
else

QLineEdit::keyPressEvent(key);
}
void MyLineEdit::setAcceptSymbols(const bool val)
{
this->acceptSymbols_=val;
if (!acceptSymbols())
{
QRegExp validNickname("^[a-zA-Z0-9_]*$"); //alpha-numeric + underscore

QValidator *validator=new QRegExpValidator(validNickname,this);
setValidator(validator);

}
}
bool MyLineEdit::acceptSymbols(void) const
{
return this->acceptSymbols_;
}