How to restrict the user from entering alphabets in LineEdit
-
install an EventFilter in which you check if the event is coming from the lineEdit. If this is true check for every key press event if the pressed key is not part of the alphabet, and if this is true you forward the event to the parents eventFilter.
like so:
@
bool YourWidgetClass::eventFilter(QObject* obj, QEvent* event)
{
if(obj == yourLineEdit)
{
QKeyEvent* keyEvent;
switch(event->type())
{
case QEvent::KeyEvent: keyEvent = dynamic_cast<QKeyEvent*>(event);
if(keyEvent->key() == (Qt::Key_1 || Qt::Key_2)
{
return QObject::eventFilter(obj, event);
}
break;default: break;
}
}
}
@beware this code will most likely not compile its just pseudo code to help you get the idea.
-
The text can be arbitrarily constrained using a "validator":http://doc.qt.nokia.com/stable/qvalidator.html or an "inputMask":http://doc.qt.nokia.com/stable/qlineedit.html#inputMask-prop
-
[quote author="cincirin" date="1319102685"]The text can be arbitrarily constrained using a "validator":http://doc.qt.nokia.com/stable/qvalidator.html or an "inputMask":http://doc.qt.nokia.com/stable/qlineedit.html#inputMask-prop[/quote]
Which should be the preferred way. There already exist validators for that
- "QIntValidator":http://doc.qt.nokia.com/stable/qintvalidator.html
- "QDoubleValidator":http://doc.qt.nokia.com/stable/qdoublevalidator.html
-
[quote author="Rajveer" date="1320815229"]Hi
I am calling a function in my constructor like this
mylineedit->installEventFilter();
installEventFilter(QObject*) takes QObject* as a parameter in my case what should i pass as argument.
[/quote]
Whatever QObject derived class you reimplemented the eventFilter() method in, of course. But, why doesn't the QValidator based solution satisfy you? -
I think its related to "this":http://developer.qt.nokia.com/forums/viewthread/11376/ thread Andre.
We're in a loop. ^^