TextEdit 以编程方式设置文本而不触发 textChanged 事件?

Jes*_*_mw 3 python pyqt pyqt5

我使用 pyQt 在 textEdit 中显示数据,然后使用连接的 textChanged 方法将文本发送到服务器应用程序。我需要 QLineEdit.textEdited 表现出的相同行为,因为 QLineEdit 中的 textEdited 不会在 setText 上触发。

有什么解决方案吗?可能是一种检测更改是否是程序化的方法?提前致谢。

eyl*_*esc 5

您可以使用blockSignals()方法阻止 textChanged 信号的发射:

from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.text_edit = QtWidgets.QTextEdit(
            textChanged=self.on_textChanged
        )
        self.setCentralWidget(self.text_edit)

        timer = QtCore.QTimer(
            self, 
            timeout=self.on_timeout
        )
        timer.start()

    @QtCore.pyqtSlot()
    def on_textChanged(self):
        print(self.text_edit.toPlainText())

    @QtCore.pyqtSlot()
    def on_timeout(self):
        self.text_edit.blockSignals(True)
        self.text_edit.setText(QtCore.QDateTime.currentDateTime().toString())
        self.text_edit.blockSignals(False)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)