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

时间:2013-03-14 05:40:55

标签: c++ qt qtextdocument

我需要制作非常大的QTextDocument的预览版本(在富文本模式下)。 所以,我需要类似它的clone()函数,但能够指定限制。 即clone (int maxChars)。 据我所知clone()源代码,它只是将一个文档复制到另一个文档作为单个QTextDocumentFragment。所以,我无法以我需要的方式修改这个过程。

有任何想法如何实现这个?

2 个答案:

答案 0 :(得分:3)

您可能希望执行以下操作:

  1. 使用QTextCursor作为父级
  2. 创建QTextDocument
  3. 致电cursor.movePosition(QTextCursor::Start)。这会将光标的位置设置为文档的开头
  4. 致电cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, n),其中n是您想要选择的字词数。
  5. 致电cursor.selection()。此方法将返回选定的QTextDocumentFragment

答案 1 :(得分:0)

如果使用富文本(通过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字符串的整数索引。