首先, 什么是rtf 格式, rtf称为富文本格,具体的内容如下 :
rtf格式是又叫富文本格式或者多文本格式,RTF是Rich Text Format的缩写,意即丰富的文本格式。在rtf文档中可以嵌入图像等文件,RTF是word为了与其他字处理软件兼容而能够保存的文档格式,类似 DOC格式(Word文档)的文件,有很好的兼容性。 用什么软件可以打开?使用Windows“附件”中的“写字板”就能打开并进行编辑。 使用“写字板”打开一个RTF格式文件时,将看到文件的内容;如果要查看RTF格式文件的源代码,只要使用“记事本”将它打开就行了。 这就是说,你完全可以像编辑HTML文件一样,使用“记事本”来编辑RTF格式文件。 许多软件都能够识别rtf文件格式。比如Word2003、WPS Office、Excel等都可以打开RTF格式的文件,例如如将WPS文件另存为RTF格式,用Word进行编辑处理,原WPS下设置的字形、字号保持不变,这说明这种格式是较为通用的。 rft格式的优点和缺点: 对普通用户而言,RTF格式是一个很好的文件格式转换工具,用于在不同应用程序之间进行格式化文本文档的传送。
下面讲一下实例内容
1. 需要添加有的模块。 在.pro 文件里面加入 QT += xml
2.rft文件生成需要的头文件为 #include <QtXml/QDomDocument> 本实例还需要用到,
#include <QFileDialog> // 用户自定义保存路径#include <QTextStream> // 文件流保存所需内容
3.实例代码:
#include "widget.h"#include "ui_widget.h"#include <QFileDialog>#include <QtXml/QDomDocument>#include <QTextStream>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget){ui->setupUi(this);}Widget::~Widget(){delete ui;}void Widget::on_toolButton_clicked(){QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(), tr("Rich Text Files (*.rtf);;"));if (fileName.isEmpty())return;if (!fileName.endsWith(QLatin1String(".rtf")))fileName += QLatin1String(".rtf");// 上面那块代码,主要用于用户手动选择保存路径, 以及输入文件名后, 如果用户没有加上后缀,自动加上文件后缀。QFile file(fileName);if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {return;}
// 上面这一小段,以文本的方式,打开并读写文件。QDomDocument doc; //xml,rtf 等多种文本格式生成所需要的类。doc.setContent(&file);
QDomElement root = doc.documentElement();QDomElement body;if (!root.isNull()) {body = root.firstChildElement(QLatin1String("body")); //如果用户保存的文件里面有内容, 查找是否是rtf格式的相关元素。}
if (body.isNull()) {root = doc.createElement(QLatin1String("html"));QDomElement head = doc.createElement(QLatin1String("head"));QDomElement meta = doc.createElement(QLatin1String("meta"));meta.setAttribute(QLatin1String("http-equiv"), QLatin1String("Content-Type"));meta.setAttribute(QLatin1String("content"), QLatin1String("text/html; charset=utf-8"));//rtf格式就是一个html格式文件, 一样的结构, 需要文件头, body内容。head.appendChild(meta);
root.appendChild(head);
body = doc.createElement(QLatin1String("body"));root.appendChild(body);
doc.appendChild(root);
}
// 上面这一小块主要写文件的文件头部内容。if (body.isNull())return;QDomElement subtitleParagraph = doc.createElement(QLatin1String("p"));QDomText subtitleText = doc.createTextNode(tr("Subtitle:")+QLatin1String("this is a test"));// 上面这一小块, 通过一个普通的p标签,来实现body 的一部份。subtitleParagraph.appendChild(subtitleText);
QDomElement tempLabel = doc.createElement(QLatin1String("span"));tempLabel.setAttribute(QLatin1String("style"), QLatin1String("color:red"));QDomText tempNode = doc.createTextNode(QLatin1String(" this is red"));tempLabel.appendChild(tempNode);
subtitleParagraph.appendChild(tempLabel);
// 上面这一段内容,则是在p标签后, 加入一个有文本样式的字<span>标签 , 把里面的字符串内容变为红色。
body.appendChild(subtitleParagraph);
QTextStream out(&file);doc.save(out, 4);file.close();}
4.运行效果:
a.用普通写字板, 记事本打开效果为:
用wps 或word打开的效果为: