如何使QTextEdit在不需要单击按钮的情况下自动自动保存中输入的内容?有可能在PyQt5中做到吗?到目前为止,我只能通过按钮绑定来做到这一点。
def save_text():
text=textedit.toPlainText()
with open('mytextfile.txt', 'w') as f:
f.write(text)
button.clicked.connect(save_text)
答案 0 :(得分:0)
如果您希望每次在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_())