如何将一个QTextDocument部分复制到另一个QTextDocument的所有格式

How to partially copy one QTextDocument to another with all of it's formatting

本文关键字:QTextDocument 复制 另一个 有格式 所有格 一个      更新时间:2023-10-16

我需要制作一个非常大的QTextDocument的预览版本副本(在富文本模式下(。所以,我需要一些类似于它的clone()函数的东西,但能够指定限制。即clone (int maxChars)。正如我从clone()源代码中了解到的,它只是将一个文档作为单个QTextDocumentFragment复制到另一个文档。所以,我不能以我需要的方式修改这个过程。

有什么想法可以实现吗?

您可能想要执行以下操作:

  1. QTextDocument为父对象创建QTextCursor
  2. 致电cursor.movePosition(QTextCursor::Start)。这将把光标的位置设置为文档的开头
  3. 调用cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, n),其中n是您希望在选择中使用的单词数量
  4. 致电cursor.selection()。此方法将返回选定的QTextDocumentFragment

如果使用富文本(通过html标记指定(,请执行以下操作:

// assuming some QTextDocument named 'source', return rich text as html QString object
QString html = source.toHtml();
// pass substring to new QTextDocument instance
QTextDocument dest(html.mid(startChar,endChar));

其中startChar和endChar是源QTextDocument的html字符串的整数索引。