diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp index 9e630f37876..03da4a4c100 100644 --- a/src/gui/text/qtextdocument_p.cpp +++ b/src/gui/text/qtextdocument_p.cpp @@ -349,8 +349,10 @@ int QTextDocumentPrivate::insert_block(int pos, uint strPos, int format, int blo QTextBlockGroup *group = qobject_cast(objectForFormat(blockFormat)); if (group) { group->blockInserted(QTextBlock(this, b)); - docChangeOldLength--; - docChangeLength--; + if (command != QTextUndoCommand::BlockDeleted) { + docChangeOldLength--; + docChangeLength--; + } } QTextFrame *frame = qobject_cast(objectForFormat(formats.format(format))); diff --git a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp index f6527fbff6d..a059648eee5 100644 --- a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp +++ b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp @@ -181,6 +181,7 @@ private slots: void insertHtmlWithComments(); void delayedLayout(); + void undoContentChangeIndices(); private: void backgroundImage_checkExpectedHtml(const QTextDocument &doc); @@ -3981,5 +3982,61 @@ void tst_QTextDocument::delayedLayout() QCOMPARE(layout->lineCount(), 1); // layout happened } +void tst_QTextDocument::undoContentChangeIndices() // QTBUG-113865 +{ + QTextDocument doc; + QTestDocumentLayout *layout = new QTestDocumentLayout(&doc); + QString content = QString("" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""); + doc.setDocumentLayout(layout); + doc.setHtml(content); + + // Select the entire document content + QTextCursor cursor(&doc); + cursor.select(QTextCursor::Document); + cursor.removeSelectedText(); + + // Undo above operation + doc.undo(); + + // Move the cursor to the end + cursor.movePosition(QTextCursor::End); + cursor.insertHtml(content); + + // Select the whole document and remove the content + cursor.select(QTextCursor::Document); + cursor.removeSelectedText(); + + int documentLength = 0; + int changeRemoved = 0; + int changeAdded = 0; + int changePos = 0; + connect(&doc, &QTextDocument::contentsChange, this, [&](int pos, int removed, int added){ + documentLength = doc.characterCount(); + changeRemoved = removed; + changeAdded = added; + changePos = pos; + }); + + // Undo above operation + doc.undo(); + + const int changeEnd = changeAdded + changeRemoved; + + QVERIFY(documentLength > 0); + QCOMPARE(changePos, 0); + QVERIFY(changeRemoved >= 0); + QVERIFY(documentLength >= changeEnd); +} + QTEST_MAIN(tst_QTextDocument) #include "tst_qtextdocument.moc"