gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:56:34 24 4
gpt4 key购买 nike

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,但为什么呢?

最佳答案

如果您检查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 事件的发出,直到它显示之后的一会儿:

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

关于python - 为什么当连接的槽显示 QMessageBox 时,editingFinished 信号会生成两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58783280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com