如何防止显示 QMessageBox 时出现双槽调用

How to prevent double slot invocation when showing a QMessageBox?

本文关键字:调用 何防止 显示 QMessageBox      更新时间:2023-10-16

>我已经将QLineEdit的editFinish信号连接到应用程序中的一个插槽,如果输入以某种方式出乎意料,则显示QMessageBox。奇怪的是,消息框显示两次,所以我在执行它的位置放置了一个断点并查看了堆栈跟踪。在那里,QMessageBox.exec()调用QApplication::p rocessEvents(),它似乎以某种方式再次转发和处理相同的事件。

我第一次的堆栈跟踪看起来像这样:

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

第二次像这样:

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

我已经检查了双信号连接或连接到此插槽的不同事件,但这似乎不是问题。有人可以解释一下这里发生了什么以及如何预防它吗?

这是一个 Qt 错误,编辑完成被发出两次,你可以在这里阅读它:

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

还有一个解决方法。

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