当连接的插槽显示QMessageBox时,为什么editingFinished信号生成两次?

2024-10-02 02:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

from PySide2 import QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.lineEdit = QtWidgets.QLineEdit()
        self.lineEdit.setText("1")
        self.lineEdit.editingFinished.connect(self.check)
        self.lineEdit2 = QtWidgets.QLineEdit()
        vlay = QtWidgets.QVBoxLayout(self)
        vlay.addWidget(self.lineEdit)
        vlay.addWidget(self.lineEdit2)

    def check(self):
        if self.lineEdit.text() == "1":
            popup = QtWidgets.QMessageBox(self)
            popup.setWindowTitle("why")
            popup.show()
            print("test")


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

因此,在这个脚本中,如果在编辑“lineEdit”时按“Enter”,则“check”槽将被调用两次。但是,如果单击“lineEdit2”,插槽将只调用一次,这是应该的。这是因为QMessageBox,但是为什么呢


Tags: importselfinitdefchecksyswidgetparent
1条回答
网友
1楼 · 发布于 2024-10-02 02:29:18

如果选中the docs

void QLineEdit::editingFinished()

This signal is emitted when the Return or Enter key is pressed or the line edit loses focus. Note that if there is a validator() or inputMask() set on the line edit and enter/return is pressed, the editingFinished() signal will only be emitted if the input follows the inputMask() and the validator() returns QValidator::Acceptable.

(我的重点)

在您的情况下,第一次打印是在按Enter键时进行的,第二次打印是在QLineEdit自QMessageBox获取后失去焦点时进行的


如果要避免此行为,可以在QMessageBox显示前一刻阻止QLineEdit事件的发出,直到它显示后一刻:

self.lineEdit.blockSignals(True)
popup = QtWidgets.QMessageBox(self)
popup.setWindowTitle("why")
QtCore.QTimer.singleShot(100, lambda: self.lineEdit.blockSignals(True))
popup.show()
print("test")

相关问题 更多 >

    热门问题