如何防止PyQt Line Edit和Message Box陷入死循环?

How to prevent PyQt Line Edit and Message Box from being stuck in an infinite loop?

在下面的代码中,在行编辑框中进行任何编辑或完成后,都会调用修改函数。然后,程序会陷入死循环,导致QMessageBox不断弹出和'modifying..'打印语句,最后导致程序崩溃。

我试过把 self.win.processEvents() 放在不同的地方,但没用。

from PyQt5 import QtWidgets


class Test:
    def __init__(self):
        self.app = QtWidgets.QApplication([])
        self.win = QtWidgets.QMainWindow()
        self.le_dwell_filter = QtWidgets.QLineEdit()
        self.le_dwell_filter.editingFinished.connect(self.modify)
        self.win.setCentralWidget(self.le_dwell_filter)
        self.win.show()

    def modify(self):
        print('Modifying...')
        msgbox = QtWidgets.QMessageBox()
        msgbox.setText('modification done!')
        msgbox.show()

    def start(self):
        self.app.exec()


if __name__ == '__main__':
    my_test = Test()
    my_test.start()

我原以为这会打印一个 'Modifying...',但不知何故 QMessageBox 一直弹出并且打印一直在发生。我认为这与 PyQt 事件循环有关?

你想要一个单独的QMessageBox,为什么要在修改方法中新建一个QMessageBox?,你要做的就是复用:

class Test:
    def __init__(self):
        self.app = QtWidgets.QApplication([])
        self.win = QtWidgets.QMainWindow()
        self.le_dwell_filter = QtWidgets.QLineEdit()
        self.le_dwell_filter.editingFinished.connect(self.modify)
        self.win.setCentralWidget(self.le_dwell_filter)
        self.win.show()
        self.msgbox = QtWidgets.QMessageBox()

    def modify(self):
        print('Modifying...')
        self.msgbox.setText('modification done!')
        self.msgbox.show()

    def start(self):
        self.app.exec()