PyQt5中如何让QTextEdit自动保存文本?

How to make QTextEdit automatically save text in PyQt5?

如何让 QTextEdit 保存我输入的任何内容自动而无需单击按钮?可以在 PyQt5 中实现吗?到目前为止,我只能通过按钮绑定来做到这一点。

def save_text():
    text=textedit.toPlainText()
    with open('mytextfile.txt', 'w') as f:
        f.write(text)

button.clicked.connect(save_text)

如果您希望每次更改 QTextEdit 中的文本时都调用您的方法,只需使用 "textChanged" 信号。我认为将文本存储到您的文件中没有意义,但这是您所要求的工作代码:

import sys
from PyQt5.QtWidgets import *


class MyMainWindow(QMainWindow):

    def __init__(self):
        super(MyMainWindow, self).__init__()

        layout = QHBoxLayout()
        centralWidget = QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

        self.textedit = QTextEdit()
        self.textedit.textChanged.connect(self.save_text)
        layout.addWidget(self.textedit)

    def save_text(self):
        text = self.textedit.toPlainText()
        with open('mytextfile.txt', 'w') as f:
            f.write(text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = MyMainWindow()
    form.show()
    sys.exit(app.exec_())