Search code examples
c++qtqtextdocument

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


I need to make a preview-version copy of very large QTextDocument (in rich text mode). So, i need something like it's clone() function, but with ability to specifying the limit. I.e. clone (int maxChars). As i understand from clone() source code, it just copy one document to another as single QTextDocumentFragment. So, i can't modify this process in the way i need.

Any ideas how to implement this?


Solution

  • Probably you want to do the following:

    1. Create QTextCursor with your QTextDocument as parent
    2. Call cursor.movePosition(QTextCursor::Start). This will set cursor's position to the beginning of the document
    3. Call cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, n), where n is amount of words you want to be in your selection.
    4. Call cursor.selection(). This method will return the selected QTextDocumentFragment.