Search code examples
c++qtqt4qt-designerqtextedit

Form input validation, multiple focus issues


I am having an issue trying to validate some input in QT4.

I have a form with 2 textEdit fields. When one field loses focus, I want it to check if the field is empty, and if so, alert the user.

Here is my code:

void newconsole::on_nameEdit_lostFocus()
{
    if (this->ui->nameEdit->text().size() < 1)
    {
        QMessageBox b;
        b.setText("Name must be longer than 0 characters.");
        b.setIcon(QMessageBox::Information);
        b.setStandardButtons(QMessageBox::Ok);
        b.show();
    }
}

void newconsole::on_fileextensionEdit_lostFocus()
{
    if (this->ui->fileextensionEdit->text().size() < 1)
    {
        QMessageBox b;
        b.setText("File extension must be longer than 0 characters.");
        b.setIcon(QMessageBox::Information);
        b.setStandardButtons(QMessageBox::Ok);
        b.show();
    }
}

My issue is that when I run the form and lose focus on the first textEdit (nameEdit) I get a MessageBox from BOTH signals. Any suggestions?


Solution

  • my guess would be:

    1. your edit boxes are positioned close to each other on the form or/and next to each other in the tab order;
    2. both edit boxes are empty by default;
    3. when you're moving focus from the empty nameEdit to the next widget which is fileextensionEdit, first message box pops up;
    4. this message box causes fileextensionEdit also to lose focus and since it's empty a second message box gets displayed.

    hope this helps, regards