2

Hi i'm coding a rich text editor and i want to save my textEdit field text as rich text file. I did that.However,i write my rich text which has different font color, size, bold. but when i save this as rtf file. All changes are gone.(i write toPlainText. i have to write different method) How can i save my text with changes(like fonts, size, colors) ?

def savefl(self):
        try:
            filey = QtWidgets.QFileDialog.getSaveFileName(self,"Save","","Rich Text File (*.rtf);;Text File(*.txt);;All Files (*.*)")
            with open(filey[0], "w", encoding="utf-8") as file2:
                file2.write(self.textEdit.toPlainText())
        except (FileNotFoundError,FileExistsError):
            pass

1 Answers1

3

Rich text and the rich text format, RTF, are not necessarily the same thing. Microsoft Word documents (.doc), Markdown (.md), and Libreoffice documents (.odf) are all rich text file formats.

So is HTML, which is how Qt lets you get the rich text, using the toHtml method. There's no way to get an RTF out of Qt; you'll have to convert the HTML to RTF.

If HTML can suffice for you, use it. As has been written before, RTF is an ancient format and its age is showing more and more. If you absolutely need RTF, you'll need to do a conversion. I'd recommend pandoc if you can call an external program; if not, you'll have to use a library like PyRTF and manually parse the HTML and create a document with PyRTF.

Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61