QTextBrowser无法正确显示反斜杠字符

时间:2017-10-31 17:26:48

标签: python xml pyqt pyqt5 qbytearray

我正在创建一个小部件,它将以非常格式化的方式显示XML字符串。要执行此操作,我使用QXmlStreamReaderQXmlStreamWriter(基于Format XML file in c++ or Qt的答案)并将文字提供给QTextBrowser

message = "<person><name>John</name><surname>Smith</surname><hobbies><sport>football</sport><sport>tenis</sport><activity>dancing</activity></hobbies></person>"
byteArray = QByteArray()
xmlReader = QXmlStreamReader(message)
xmlWriter = QXmlStreamWriter(byteArray)
xmlWriter.setAutoFormatting(True)
while (not xmlReader.atEnd()):
    xmlReader.readNext();
    if (not xmlReader.isWhitespace()):
        xmlWriter.writeCurrentToken(xmlReader)
prettyMessage = str(byteArray.data())
textBrowser.setText(prettyMessage)

但结果文字未将\n转换为新行:

enter image description here

如果我手动输入一个包含\n的字符串,它们将转换为新行:

textBrowser.setText("1\n2\n3\n4")

enter image description here

我已检查byteArray的确切内容,以确保将\n作为一个字符传递,而不是作为两个单独的'\'和'n'字符传递:

for i in range(0, byteArray.size()):
    sys.stdout.write(byteArray.at(i))

按预期打印出XML字符串:

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>John</name>
    <surname>Smith</surname>
    <hobbies>
        <sport>football</sport>
        <sport>tenis</sport>
        <activity>dancing</activity>
    </hobbies>
</person>

我正在使用python 3.6和PyQt5

1 个答案:

答案 0 :(得分:1)

您需要解码QByteArray中的数据。这可以使用QTextStream来完成,然后您可以轻松设置正确的编解码器:

    byteArray = QByteArray()
    xmlReader = QXmlStreamReader(message)
    xmlWriter = QXmlStreamWriter(byteArray)
    xmlWriter.setAutoFormatting(True)
    while (not xmlReader.atEnd()):
        xmlReader.readNext();
        if (not xmlReader.isWhitespace()):
            xmlWriter.writeCurrentToken(xmlReader)

    stream = QTextStream(byteArray)
    stream.setCodec(xmlWriter.codec())
    textBrowser.setText(stream.readAll())