QLineEdit
-
Hi,
I'm trying to read and validate the entry in QLineEdit when it loses focus either by pressing TAB, ENTER or the user clicks on an other widget.
I have the following code so far (which is not working):while((ui->lineEdit->hasFocus ()== (true) )) { QString string; if(string.length ()<2) { ui->label_2->setText ("The name is too short!"); ui->label_2->setStyleSheet ("color: red"); QPixmap pix ("C:/Programming/Projects/FolkFriends/icons/angry.png"); ui->label_3->setScaledContents (true); ui->label_3->setPixmap (pix); } else { ui->label_2->setText (""); QPixmap pix2("C:/Programming/Projects/FolkFriends/icons/Check-icon.png"); ui->label_3->setScaledContents (true); ui->label_3->setPixmap (pix2); } } QString Name; Name = ui->lineEdit->text (); qDebug() << "Name: " << Name;
Please help me to figure out how to do it correctly.
Thank you. -
Hi
A while loop is not the way :)as @Charby suggest might be the fastest!
Alternatively You can use
http://doc.qt.io/qt-5.5/qwidget.html#focusOutEvent
Using a subclassclass LineEdit : public QLineEdit { virtual void focusOutEvent( QFocusEvent* ) { /// focus is lost. do stuff } };
-
I came up with the following (not working) code:
setFocusPolicy (Qt::StrongFocus); if((ui->lineEdit->QFocusEvent::lostFocus())==true ) { QString string; string = ui->lineEdit->text (); if(string.length ()<2) { ui->label_4->setText ("The name is too short!"); ui->label_4->setStyleSheet ("color: red"); QPixmap pix ("C:/Programming/Projects/FolkFriends/icons/angry.png"); ui->label_3->setScaledContents (true); ui->label_3->setPixmap (pix); } else { ui->label_4->setText (""); QPixmap pix2("C:/Programming/Projects/FolkFriends/icons/Check-icon.png"); ui->label_3->setScaledContents (true); ui->label_3->setPixmap (pix2); } QString Name; Name = ui->lineEdit->text (); qDebug() << "Name: " << Name; }
When I run it I get the following error message:
C:\Programming\Projects\Folkfriends\additem.cpp:-1: In constructor 'Additem::Additem(QWidget*)':
C:\Programming\Projects\Folkfriends\additem.cpp:51: error: 'QFocusEvent' is not a base of 'QLineEdit'
if((ui->lineEdit->QFocusEvent::lostFocus())==true )
^
What am I doing wrong?
Thank you for all your help. -
This is a C++ error, not an issue with Qt, and the compiler is pretty explicit.
There is no lostFocus() method in QLineEdit class. And adding QFocusEvent is not the solution. Instead, consider implementing what @Charby suggested: connect your ui->lineEdit editingFinished() signal to your custom slot:connect(ui->lineEdit, SIGNAL(editingFinished()), this, SLOT(readAndValidate()));
Add this connect in your the constructor of the widget that contains the ui.
-
connect(ui->lineEdit, SIGNAL(editingFinished()), this, SLOT(readAndValidate()));
The 'this' means that readAndValidate() is a slot that belongs to 'this'.