from PyQt5.QtGui import QFont, QIcon from tkinter.filedialog import * import sys class Example(QMainWindow): def __init__(self): super().__init__() self.GUI() def GUI(self): self.setGeometry(300,300,300,300) self.setWindowTitle('Hi') textEdit=QTextEdit(self) self.setCentralWidget(textEdit) saveFile=QAction('Save',self) saveFile.triggered.connect(self.save) menu=self.menuBar() fm=menu.addMenu('File') fm.addAction(saveFile) self.show() def save(self): textEdit=QTextEdit(self) name=QFileDialog.getSaveFileName(self) file=open(name[0],'w') text=textEdit.toPlainText() file.write(text) file.close() if __name__=='__main__': app=QApplication(sys.argv) examp=Example() app.exec_() 

Hello, I can't get the text from QTextEdit. If the user entered the text into a text editor and saved it, it turns out an empty file. Please help me correct this error.

  • one
    useful thing .. maybe when not we will be using a code editor named Alice ... - user33274

1 answer 1

The error is that when saving the author created a new QTextEdit and took its value: textEdit=QTextEdit(self)

Try:

 from PyQt5 import Qt import sys class Example(Qt.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Hi') self.text_edit = Qt.QTextEdit() self.setCentralWidget(self.text_edit) menu = self.menuBar().addMenu('File') save_file_action = menu.addAction('Save As ...') save_file_action.triggered.connect(self.save_as) def save_as(self): file_name, ok = Qt.QFileDialog.getSaveFileName(self) if not ok: return with open(file_name, 'w', encoding='utf-8') as f: text = self.text_edit.toPlainText() f.write(text) if __name__ == '__main__': app = Qt.QApplication(sys.argv) example = Example() example.setGeometry(300, 300, 300, 300) example.show() app.exec() 

Ps. QMenu has different addAction method overloads , for example, one of them allows you to transfer: an icon, a name, a function being called and a hot key (for example, Ctrl + S ), but I decided that this would be unnecessary for example.

Pps. QFileDialog.getSaveFileName has parameters for specifying the header, default folder, filters. For example, you can immediately set the name of the saved file.

PPPS. I recommend in python not to use camel notation in the name of methods and variables: textEdit -> text_edit

  • And textEdit doesn't have to specify self as the parent object? - bipll
  • @bipll, widgets automatically get parent when they are added to a form via layout (layout) or via methods like setCentralWidget - gil9red
  • Oh, yes, it is logical. :) - bipll