简体   繁体   English

PyQt5如何保存文本将文本编辑为富文本格式

[英]PyQt5 How to save textEdit text as rich text

Hi i'm coding a rich text editor and i want to save my textEdit field text as rich text file. 嗨,我正在编码一个RTF编辑器,我想将textEdit字段文本另存为RTF文件。 I did that.However,i write my rich text which has different font color, size, bold. 我是这样做的。但是,我写的是带有不同字体颜色,大小,粗体的富文本。 but when i save this as rtf file. 但是当我将其另存为rtf文件时。 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) ? 所有更改都消失了。(我写给PlainText。我必须写不同的方法)如何保存更改后的文本(如字体,大小,颜色)?

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

Rich text and the rich text format , RTF, are not necessarily the same thing. RTF和RTF 格式不一定是同一回事。 Microsoft Word documents (.doc), Markdown (.md), and Libreoffice documents (.odf) are all rich text file formats. Microsoft Word文档(.doc),Markdown(.md)和Libreoffice文档(.odf)都是富文本文件格式。

So is HTML, which is how Qt lets you get the rich text, using the toHtml method. HTML也是如此,这是Qt使用toHtml方法获取富文本的方式。 There's no way to get an RTF out of Qt; 无法使RTF脱离Qt。 you'll have to convert the HTML to RTF. 您必须将HTML转换为RTF。

If HTML can suffice for you, use it. 如果HTML可以满足您的需求,请使用它。 As has been written before , RTF is an ancient format and its age is showing more and more. 如前所述 ,RTF是一种古老的格式,并且其年龄越来越大。 If you absolutely need RTF, you'll need to do a conversion. 如果您绝对需要RTF,则需要进行转换。 I'd recommend pandoc if you can call an external program; 如果可以调用外部程序,我建议使用pandoc if not, you'll have to use a library like PyRTF and manually parse the HTML and create a document with PyRTF. 如果不是,则必须使用PyRTF之类的库并手动解析HTML并使用PyRTF创建文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM