I have a Qt C++ app where I need to save the contents of a QTextEdit to disk as plain text if it contains plain text, and as html if the QTextEdit contains rich text.
Is there any way to tell if its contents are rich text or plain text?
In the case of plain text, that would mean its contents has no formatting, and all text has no specified font or is using the default font.
There's no way to distinguish, since QTextDocument
doesn't track that information. The following two calls produce exactly the same state in the document:
QTextDocument doc;
doc.setPlainText("lorem ipsum\ndolor sit amet\nconsectetur adipiscing elit");
doc.setHtml("<p style=\"margin-top:0;margin-bottom:0;\">lorem ipsum</p>"
"<p style=\"margin-top:0;margin-bottom:0;\">dolor sit amet</p>"
"<p style=\"margin-top:0;margin-bottom:0;\">consectetur adipiscing elit</p>");
Because of that, the best solution is to maintain a separate variable to record which format we have.
If we can't (or won't) to do that, there's a reasonably good heuristic we can use - if we convert the plain text to HTML, do we get the same result as HTML direct from the document?
That test looks like this:
#include <QTextDocument>
bool isPlainText(QTextDocument const *doc)
{
return QTextDocument{doc->toRawText()}.toHtml() == doc->toHtml();
}
Demo:
int main()
{
QTextDocument doc;
doc.setPlainText("lorem ipsum\ndolor sit amet\nconsectetur adipiscing elit");
assert(isPlainText(&doc));
doc.setHtml("<p>lorem ipsum</p>"
"<p>dolor sit amet</p>"
"<p>consectetur adipiscing elit</p>");
assert(!isPlainText(&doc));
}