Congratulations to our 2022 Qt Champions!

Cloned QTextDocument function failure

  • While adding headers and footers to my printouts I ran across the following rather courious problem. When I cloned the clone of a QTextDocument several of the QTextDocument functions failed. The folliwing code fragnent illustrates the problem

    int pmax=5;
    int pc=0;
    QTextEdit *myedit = new QTextEdit;
    myedit->setPlainText(QString("K of N"));
    QTextDocument *firstClone=myedit->document()->clone();
    { // limit the scope of cur for debug
    QTextCursor cur(firstClone);
    qDebug()<<"first clone text:"<<firstClone->toPlainText();
    QTextDocument secondClone=firstClone->clone();
    { //limit the scope of cur for debug
    QTextCursor cur(secondClone);
    qDebug()<<"second clone text:"<<secondClone->toPlainText();

    QTextDocument *secondClone=firstClone->clone();
    QString temp=secondClone->toPlainText();
    qDebug()<<"second clone text:"<<secondClone->toPlainText();

    The find function works perfectly on the first clone of myedit but fails on the second clone of myedit (i.e., the second clone is a clone of the first clone).

    Since I am using plain text the commented out code is a viable work around but that will not always be the case so I'd like to know know if this is a bug or a misunderstanding on my part. I'd appreciate any feedback that can shed some light on this behavior.

  • Oh no, another stupid mistake by me. I accidently used the QTextEdit find() prototype rather than the QTextDocument prototype. Changing the while loop to include the cursor fixed the problem. For example the secondClone while loop should be:

    @ while(!(cur=secondClone->find("K",cur,QTextDocument::FindCaseSensitively)).isNull())@

    rather than
    @ while(!(cur=secondClone->find("K",QTextDocument::FindCaseSensitively)).isNull())@

    Problem solved!

Log in to reply