Copy formatting attributes when cloning an empty QTextDocument

When cloning a QTextDocument, the text fragment of the original document
is copied into the new one, which results into copying also the
formatting attributes. However, when the text document is empty, the
corresponding text fragment is also empty, so nothing is copied.

If we want to transfer the formatting attributes for an empty document,
we need to set them explicitly.

Fixes: QTBUG-80399
Change-Id: I382cd0821723436120af47c06ec7bfa849636307
Reviewed-by: Cristian Maureira-Fredes <cristian.maureira-fredes@qt.io>
Reviewed-by: Eirik Aavitsland <eirik.aavitsland@qt.io>
This commit is contained in:
Sona Kurazyan 2019-12-04 10:57:08 +01:00
parent 1f592da7f1
commit 81459dd9c0
2 changed files with 40 additions and 1 deletions

View File

@ -347,7 +347,19 @@ QTextDocument *QTextDocument::clone(QObject *parent) const
{
Q_D(const QTextDocument);
QTextDocument *doc = new QTextDocument(parent);
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
if (isEmpty()) {
const QTextCursor thisCursor(const_cast<QTextDocument *>(this));
const auto blockFormat = thisCursor.blockFormat();
if (blockFormat.isValid() && !blockFormat.isEmpty())
QTextCursor(doc).setBlockFormat(blockFormat);
const auto blockCharFormat = thisCursor.blockCharFormat();
if (blockCharFormat.isValid() && !blockCharFormat.isEmpty())
QTextCursor(doc).setBlockCharFormat(blockCharFormat);
} else {
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
}
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
QTextDocumentPrivate *priv = doc->d_func();
priv->title = d->title;

View File

@ -125,6 +125,7 @@ private slots:
void clonePreservesResources();
void clonePreservesUserStates();
void clonePreservesIndentWidth();
void clonePreservesFormatsWhenEmpty();
void blockCount();
void defaultStyleSheet();
@ -2342,6 +2343,32 @@ void tst_QTextDocument::clonePreservesIndentWidth()
delete clone;
}
void tst_QTextDocument::clonePreservesFormatsWhenEmpty()
{
QTextDocument document;
QTextCursor cursor(&document);
// Change a few char format attributes
QTextCharFormat charFormat;
charFormat.setFontPointSize(charFormat.fontPointSize() + 1);
charFormat.setFontWeight(charFormat.fontWeight() + 1);
cursor.setBlockCharFormat(charFormat);
// Change a few block format attributes
QTextBlockFormat blockFormat;
blockFormat.setAlignment(Qt::AlignRight); // The default is Qt::AlignLeft
blockFormat.setIndent(blockFormat.indent() + 1);
cursor.setBlockFormat(blockFormat);
auto clone = document.clone();
QTextCursor cloneCursor(clone);
QCOMPARE(cloneCursor.blockCharFormat().fontPointSize(), charFormat.fontPointSize());
QCOMPARE(cloneCursor.blockCharFormat().fontWeight(), charFormat.fontWeight());
QCOMPARE(cloneCursor.blockFormat().alignment(), blockFormat.alignment());
QCOMPARE(cloneCursor.blockFormat().indent(), blockFormat.indent());
}
void tst_QTextDocument::blockCount()
{
QCOMPARE(doc->blockCount(), 1);