带换行符的字符串 - 复制到Qtextview

时间:2014-07-22 09:45:27

标签: c++ xml qt

我正在尝试读取xml文件。文件已正确加载。
我正在读取xml文件的第一个节点(即0节点)的文本。在文本编辑中加载。

文本已正确加载,但qtextedit中\n newline characternot converted into Actual newline

如何在qt文本节点中保存字符串,以便在QTextView上显示新行字符时将其转换为实际换行符?

qtextedit上的输出是:

\n\n I am a boy \n\n From Town

XML文件:

<MyMenu>
 <Index IndexName="About Me"> \n\n &lt;b> I am a boy &lt;/b> \n\n From Town </Index>
 <Index IndexName="My Education"> \n\n graduation : BSC \n\n Post graduation : MSC </Index>
</MyMenu>

阅读代码&amp; display xml:

#define FILE_NAME              "HelpContent.xml"

QString exePath = QCoreApplication::applicationDirPath();
QString helpFileCompletePath = exePath + QDir::separator() + FILE_NAME;

//set the name of the XML Help file
xmlFile.setFileName(helpFileCompletePath);
ret = xmlFile.open(QIODevice::ReadOnly|QIODevice::Text);

xmlDomDocument.clear();
xmlDomDocument.setContent(&xmlFile);
nn = xmlDomDocument.firstChild();

list = nn.childNodes();

QDomNode e = list.at(0);
rootElementText = e.toElement().text();
ui->helpTextEdit->setText(rootElementText);

=================编辑:将字符串的一部分设置为粗体====================== =======

 <Index IndexName="About Me"> \n\n &lt;b> I am a boy &lt;/b> \n\n From Town </Index>

这个是弦乐的一部分&#34;我是男孩&#34;如果我使用BartoszKP建议的逻辑,则不会插入粗体,但不插入换行符。

现在,如果我从小镇&#34;制作字符串&#34;在这种情况下,如果我使用BartoszKP建议的逻辑,则插入新行。但是#34;来自城镇&#34;没有大胆。

 <Index IndexName="About Me"> \n\n  I am a boy \n\n &lt;b> From Town &lt;/b>  </Index>

任何建议,如何删除此限制。

1 个答案:

答案 0 :(得分:0)

您的文件中没有新行,只有两个字符&#34; \&#34;和&#34; n&#34; C ++编译器以特殊的方式一起解释这些问题。没有理由将此约定强加于所有C ++程序,因此Qt的类不会解释这些字符。所以&#34; \ n&#34;在你的文件中,内容不是C ++新行&#34;字符&#34;正如你的建议(这表明你是以错误的方式思考它) - 在C ++中,它等同于字符串:"\\n"

在这种情况下,您可以尝试使用Qt&#39; QString::replace来实现此目标:

rootElementText = e.toElement().text().replace("\\n", "\n");

然而,需要更多的工作来解释所有特殊字符。

另一个直截了当的解决方案是不使用&#34; \ n&#34;文件中的字符 - 只需将实际的新行(例如点击&#34;输入&#34;键)放在那里:

<Index IndexName="About Me"> 

 I am a boy 

 From Town </Index>