TextEdit: Richtext to Standard text conversion problem
-
I have noticed that when I convert Richtext to normal string in TextEdit using
getText()
method, Carriage Returns are not converted properly to a new line character, like\r\n
. Hence the console is unable to print them properly and displays?
instead of\r\n
. If you run the code below, it will give you a?
in the console as you press enter.What is the correct way to convert Richtext to standard string or is this a bug?
I have the following
QT version: 5.15.0 ( MSVC 2019)
OS: Windows 10 x86_64import QtQuick 2.15 Rectangle { function onTextChanging(){ let str = xText.getText(0, xText.text.length) console.log(str) } TextEdit{ id: xText height:300 width: 500 textFormat:TextEdit.RichText onTextChanged: onTextChanging() } }
-
When converted to Hex I get the correct hex value though. Shouldn't this be built-in feature?
import QtQuick 2.15 Rectangle { function onTextChanging(){ let str = xText.getText(0, xText.text.length) console.log(str) var arr = []; for (var n = 0, l = str.length; n < l; n ++) { var hex = Number(str.charCodeAt(n)).toString(16); arr.push(hex); } console.log(arr) } TextEdit{ id: xText height:300 width: 500 textFormat:TextEdit.RichText onTextChanged: onTextChanging() } }
-
If I need more than simple manipulation of the text in QML then I drop to C++ by getting the https://doc.qt.io/qt-5/qtextdocument.html. There is a method to do this in the QML text items. Then you have much more control of what you get out of the document. It is really useful for when you need to do high resolution printing of the document.
-
If I need more than simple manipulation of the text in QML then I drop to C++ by getting the https://doc.qt.io/qt-5/qtextdocument.html. There is a method to do this in the QML text items. Then you have much more control of what you get out of the document. It is really useful for when you need to do high resolution printing of the document.
@fcarney yes you are right. QTextDocument did do the job far better than the one provided on the QML side. I just had to write the following on C++ side
Q_INVOKABLE QString returnPlainText(QString s) { QTextDocument td; td.setHtml(s); return td.toPlainText(); }
and invoke the function from QML like this
import QtQuick 2.15 Rectangle { function onTextChanging(){ console.log(QtTest2.returnPlainText(xText.text)) } TextEdit{ id: xText height:300 width: 500 textFormat:TextEdit.RichText onTextChanged: onTextChanging() } }
I will raise the QML part issue to the bugs though