SIMEL
SIMEL

Reputation: 8941

QTextBrowser doesn't properly show backslashed characters

I'm creating a widget that will display XML strings in a pretty formatted way. To do this I'm using a QXmlStreamReader and a QXmlStreamWriter (based on the answer from Format XML file in c++ or Qt) and feed the text to a 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)

But the resulting text doesn't convert \n to new lines:

enter image description here

If I input manually a string with \n in it, they are converted to new lines:

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

enter image description here

I've checked the exact content of byteArray to make sure that the \n is passed as one character and not as two separate '\' and 'n' characters:

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

prints out the XML string as expected:

<?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>

I'm using python 3.6 with PyQt5

Upvotes: 1

Views: 293

Answers (1)

ekhumoro
ekhumoro

Reputation: 120628

You need to decode the data in the QByteArray. This can be done using a QTextStream, which then allows you to easily set the right codec:

    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())

Upvotes: 1

Related Questions