Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize and deserialize rich text in QTextEdit?

Say I have a structure like this:

class AAA
{
    BBB      bb_member;
    double   dbl_member;
    ....................
}

class BBB
{
    int             int_member;
    QString         QStr_member;

    .................
    QTextEdit       m_textEdit;
}

And for AAA I define this operators:

QDataStream &operator<<(QDataStream &out, const AAA &aa)
{
    out << aa.bb_member
        << aa.dbl_member;
    return out;
}

QDataStream &operator>>(QDataStream &in, AAA &aa)
{
    BBB bb_memb;
    double dbk_memb;

    in >> bb_memb
       >> dbk_memb;

    aa = AAA(bb_memb, dbk_memb);

    return in;
}

Then I call this:

QFile file("myFileName");
file.open(QIODevice::WriteOnly))
QDataStream out(&file);
out << AAA_object;

in order to serialize AAA object to a file.

Now the question. How I should define QDataStream operators for BBB class in order to serialize BBB object (int, QString and QTextEdit reach text content), while calling out << AAA_object; ???

like image 799
Narek Avatar asked Dec 06 '25 15:12

Narek


2 Answers

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.

like image 182
roop Avatar answered Dec 08 '25 08:12

roop


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 :)))!

like image 23
Narek Avatar answered Dec 08 '25 07:12

Narek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!