Search code examples
c++qtsignals-slotsqlineeditqmessagebox

How to prevent double slot invocation when showing a QMessageBox?


I've connected the editingFinished signal of a QLineEdit to a slot in my application showing a QMessageBox if the input is in some way unexpected. Strangely enough the message box is shown twice, so I put a breakpoint where it is executed and had a look at the stack trace. There QMessageBox.exec() calls QApplication::processEvents() which seems to somehow forward and process the same event again.

My stack trace the first time looks sth like this:

MyApp::mySlot()
QLineEdit::editingFinished()
QGuiApplicationPrivate::processMouseEvent()
QEventLoop::processEvents()
QApplication::exec()

and the 2nd time like this:

MyApp::mySlot()
QLineEdit::editingFinished()
QGuiApplicationPrivate::processWindowSystemEvent()
QEventLoop::processEvents()
QDialog::exec()
// stack trace of run #1 here
// [...]

I've already checked for double signal connections or different events being connected to this slot but this doesn't seem to be the problem. Can someone explain what happens here and how to prevent it?


Solution

  • It is a Qt bug that editingFinished is emitted twice, you can read about it here:

    https://forum.qt.io/topic/39141/qlineedit-editingfinished-signal-is-emitted-twice

    There is also a workaround for it described.

    if(lineEdit->text().toDouble()<1000) {
    lineEdit->blockSignals(true);
    QMessageBox::information(this, "Information", "Incorrect value");
    lineEdit->blockSignals(false);
    }