How to serialize and deserialize rich text in QTextEdit?

大城市里の小女人 提交于 2019-11-29 15:45:35

QTextEdit is a widget, and it doesnt make much sense to write a widget to a file, but we can write the content of the widget (QTextEdit::toHtml()) to the file. When reading from file, we can create a new widget object and initialize it with the contents of the file (QTextEdit::setHtml()).

I must add that it would probably be a better design to store just the richtext data in BBB (as a html QString) as opposed to the QTextEdit itself.

I have already compleated this task. I have saved the images in a QVector. Serialized the vector and the HTML code. Then deserialized the code and the QVector. Added all the images as a resource with this function:

for(int i = 0; i < vectorOfImages.size(); i++ )
{
    QUrl url(QString("image_%1").arg(i));
    textEdit->document()->addResource(QTextDocument::ImageResource, url,  vectorOfImages.at(i));
}

Then Does the following

int count = 0;
int pos = 0;

QRegExp rx("<img src=\".+/>");
while ((pos = rx.indexIn(htmlCode, pos)) != -1)
{
    QString strToReplace(QString("<img src=\"image_%1\" />").arg(count));
    htmlCode.replace(pos, rx.matchedLength(), strToReplace);
    pos += rx.matchedLength();
    count++;
}

textEdit->setText(htmlCode);

Works fine! And I will have my former rating :)))!

Here is what I would do :

First (as roop said), you shouldn't store the QTextEdit widget itself, but the underlying text document (QTextDocument). You can get it from the QTextEdit widget with QTextEdit::document().

QTextDocument* pTextDoc = m_textEdit->document();

Then, I would get the html string from this document and from this string, get a QByteArray :

QString MyText = pTextDoc->toHtml();
QByteArray TextAsByteArray = MyText.toUtf8();

Once you have a QByteArray object containing your document, you can use the << and >> operators.

For reading back the QByteArray, store it into a QString(see QString::fromUtf8()), and use QTextDocument::setHtml() to display the content into the QTextEdit widget.

UPDATE

Following jpalecek comment, I'm overcomplicating the solution. Once you have a QString containing your text document as HTML, you can use QString::operator<<() and QString::operator>>() without using a QByteArray.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!