|  | Home · All Classes · Modules

# QTextDocument Class Reference
[QtGui module]

The QTextDocument class holds formatted text that can be viewed and edited using a QTextEdit. More...

Inherits QObject.

### Types

- enum FindFlag { FindBackward, FindCaseSensitively, FindWholeWords }
- class FindFlags
- enum MetaInformation { DocumentTitle, DocumentUrl }
- enum ResourceType { HtmlResource, ImageResource, StyleSheetResource, UserResource }

### Methods

- __init__ (self, QObject parent = None)
- __init__ (self, QString text, QObject parent = None)
- addResource (self, int type, QUrl name, QVariant resource)
- adjustSize (self)
- QTextFormat-list allFormats (self)
- QTextBlock begin (self)
- int blockCount (self)
- clear (self)
- QTextDocument clone (self, QObject parent = None)
- QTextObject createObject (self, QTextFormat f)
- QFont defaultFont (self)
- QString defaultStyleSheet (self)
- QTextOption defaultTextOption (self)
- QAbstractTextDocumentLayout documentLayout (self)
- drawContents (self, QPainter painter, QRectF rect = QRectF())
- QTextBlock end (self)
- QTextCursor find (self, QString expr, int from = 0, FindFlags options = 0)
- QTextCursor find (self, QRegExp expr, int from = 0, FindFlags options = 0)
- QTextCursor find (self, QString expr, QTextCursor from, FindFlags options = 0)
- QTextCursor find (self, QRegExp expr, QTextCursor from, FindFlags options = 0)
- QTextBlock findBlock (self, int pos)
- QTextBlock findBlockByNumber (self, int blockNumber)
- QTextBlock firstBlock (self)
- float idealWidth (self)
- float indentWidth (self)
- bool isEmpty (self)
- bool isModified (self)
- bool isRedoAvailable (self)
- bool isUndoAvailable (self)
- bool isUndoRedoEnabled (self)
- QTextBlock lastBlock (self)
- QVariant loadResource (self, int type, QUrl name)
- markContentsDirty (self, int from, int length)
- int maximumBlockCount (self)
- QString metaInformation (self, MetaInformation info)
- QTextObject object (self, int objectIndex)
- QTextObject objectForFormat (self, QTextFormat)
- int pageCount (self)
- QSizeF pageSize (self)
- print_ (self, QPrinter printer)
- redo (self)
- redo (self, QTextCursor cursor)
- QVariant resource (self, int type, QUrl name)
- int revision (self)
- QTextFrame rootFrame (self)
- setDefaultFont (self, QFont font)
- setDefaultStyleSheet (self, QString sheet)
- setDefaultTextOption (self, QTextOption option)
- setDocumentLayout (self, QAbstractTextDocumentLayout layout)
- setHtml (self, QString html)
- setIndentWidth (self, float width)
- setMaximumBlockCount (self, int maximum)
- setMetaInformation (self, MetaInformation info, QString)
- setModified (self, bool m = True)
- setPageSize (self, QSizeF size)
- setPlainText (self, QString text)
- setTextWidth (self, float width)
- setUndoRedoEnabled (self, bool enable)
- setUseDesignMetrics (self, bool b)
- QSizeF size (self)
- float textWidth (self)
- QString toHtml (self, QByteArray encoding = QByteArray())
- QString toPlainText (self)
- undo (self)
- undo (self, QTextCursor cursor)
- bool useDesignMetrics (self)

### Qt Signals

- void blockCountChanged (int)
- void contentsChange (int,int,int)
- void contentsChanged ()
- void cursorPositionChanged (const QTextCursor&)
- void documentLayoutChanged ()
- void modificationChanged (bool)
- void redoAvailable (bool)
- void undoAvailable (bool)
- void undoCommandAdded ()

## Detailed Description

The QTextDocument class holds formatted text that can be viewed and edited using a QTextEdit.

QTextDocument is a container for structured rich text documents, providing support for styled text and various types of document elements, such as lists, tables, frames, and images. They can be created for use in a QTextEdit, or used independently.

Each document element is described by an associated format object. Each format object is treated as a unique object by QTextDocuments, and can be passed to objectForFormat() to obtain the document element that it is applied to.

A QTextDocument can be edited programmatically using a QTextCursor, and its contents can be examined by traversing the document structure. The entire document structure is stored as a hierarchy of document elements beneath the root frame, found with the rootFrame() function. Alternatively, if you just want to iterate over the textual contents of the document you can use begin(), end(), and findBlock() to retrieve text blocks that you can examine and iterate over.

The layout of a document is determined by the documentLayout(); you can create your own QAbstractTextDocumentLayout subclass and set it using setDocumentLayout() if you want to use your own layout logic. The document's title can be obtained by calling the documentTitle() function.

The toPlainText() and toHtml() convenience functions allow you to retrieve the contents of the document as plain text and HTML. The document's text can be searched using the find() functions.

Undo/redo of operations performed on the document can be controlled using the setUndoRedoEnabled() function. The undo/redo system can be controlled by an editor widget through the undo() and redo() slots; the document also provides contentsChanged(), undoAvailable(), and redoAvailable() signals that inform connected editor widgets about the state of the undo/redo system.

See also QTextCursor, QTextEdit, and Rich Text Processing.

## Type Documentation

### QTextDocument.FindFlag

This enum describes the options available to QTextDocument's find function. The options can be OR-ed together from the following list:

Constant | Value | Description
--- | --- | ---
`QTextDocument.FindBackward` | `0x00001` | Search backwards instead of forwards.
`QTextDocument.FindCaseSensitively` | `0x00002` | By default find works case insensitive. Specifying this option changes the behaviour to a case sensitive find operation.
`QTextDocument.FindWholeWords` | `0x00004` | Makes find match only complete words.

The FindFlags type is a typedef for QFlags<FindFlag>. It stores an OR combination of FindFlag values.

### QTextDocument.MetaInformation

This enum describes the different types of meta information that can be added to a document.

Constant | Value | Description
--- | --- | ---
`QTextDocument.DocumentTitle` | `0` | The title of the document.
`QTextDocument.DocumentUrl` | `1` | The url of the document. The loadResource() function uses this url as the base when loading relative resources.

See also metaInformation() and setMetaInformation().

### QTextDocument.ResourceType

This enum describes the types of resources that can be loaded by QTextDocument's loadResource() function.

Constant | Value | Description
--- | --- | ---
`QTextDocument.HtmlResource` | `1` | The resource contains HTML.
`QTextDocument.ImageResource` | `2` | The resource contains image data. Currently supported data types are QVariant.Pixmap and QVariant.Image. If the corresponding variant is of type QVariant.ByteArray then Qt attempts to load the image using QImage.loadFromData. QVariant.Icon is currently not supported. The icon needs to be converted to one of the supported types first, for example using QIcon.pixmap.
`QTextDocument.StyleSheetResource` | `3` | The resource contains CSS.
`QTextDocument.UserResource` | `100` | The first available value for user defined resource types.

See also loadResource().

## Method Documentation

### QTextDocument.__init__ (self, QObject parent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs an empty QTextDocument with the given parent.

### QTextDocument.__init__ (self, QString text, QObject parent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs a QTextDocument containing the plain (unformatted) text specified, and with the given parent.

### QTextDocument.addResource (self, int type, QUrl name, QVariant resource)

Adds the resource resource to the resource cache, using type and name as identifiers. type should be a value from QTextDocument.ResourceType.

For example, you can add an image as a resource in order to reference it from within the document:

         document->addResource(QTextDocument.ImageResource,
             QUrl("mydata://image.png"), QVariant(image));

The image can be inserted into the document using the QTextCursor API:

         QTextImageFormat imageFormat;
         imageFormat.setName("mydata://image.png");
         cursor.insertImage(imageFormat);

Alternatively, you can insert images using the HTML `img` tag:

         editor->append("<img src=\"mydata://image.png\" />");

### QTextDocument.adjustSize (self)

Adjusts the document to a reasonable size.

This function was introduced in Qt 4.2.

See also idealWidth(), textWidth, and size.

### QTextFormat-list QTextDocument.allFormats (self)

Returns a vector of text formats for all the formats used in the document.

### QTextBlock QTextDocument.begin (self)

Returns the document's first text block.

See also firstBlock().

### int QTextDocument.blockCount (self)

### QTextDocument.clear (self)

Clears the document.

### QTextDocument QTextDocument.clone (self, QObject parent = None)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Creates a new QTextDocument that is a copy of this text document. parent is the parent of the returned text document.

### QTextObject QTextDocument.createObject (self, QTextFormat f)

Creates and returns a new document object (a QTextObject), based on the given format.

QTextObjects will always get created through this method, so you must reimplement it if you use custom text objects inside your document.

### QFont QTextDocument.defaultFont (self)

### QString QTextDocument.defaultStyleSheet (self)

### QTextOption QTextDocument.defaultTextOption (self)

### QAbstractTextDocumentLayout QTextDocument.documentLayout (self)

Returns the document layout for this document.

See also setDocumentLayout().

### QTextDocument.drawContents (self, QPainter painter, QRectF rect = QRectF())

Draws the content of the document with painter p, clipped to rect. If rect is a null rectangle (default) then the document is painted unclipped.

This function was introduced in Qt 4.2.

### QTextBlock QTextDocument.end (self)

This function returns a block to test for the end of the document while iterating over it.

         for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next())
             cout << it.text().toStdString() << endl;

The block returned is invalid and represents the block after the last block in the document. You can use lastBlock() to retrieve the last valid block of the document.

See also lastBlock().

### QTextCursor QTextDocument.find (self, QString expr, int from = 0, FindFlags options = 0)

Finds the next occurrence of the string, subString, in the document. The search starts at the position of the given cursor, and proceeds forwards through the document unless specified otherwise in the search options. The options control the type of search performed.

Returns a cursor with the match selected if subString was found; otherwise returns a null cursor.

If the given cursor has a selection, the search begins after the selection; otherwise it begins at the cursor's position.

By default the search is case-sensitive, and can match text anywhere in the document.

### QTextCursor QTextDocument.find (self, QRegExp expr, int from = 0, FindFlags options = 0)

This is an overloaded member function, provided for convenience.

Finds the next occurrence, matching the regular expression, expr, in the document. The search starts at the position of the given cursor, and proceeds forwards through the document unless specified otherwise in the search options. The options control the type of search performed. The FindCaseSensitively option is ignored for this overload, use QRegExp.caseSensitivity instead.

Returns a cursor with the match selected if a match was found; otherwise returns a null cursor.

If the given cursor has a selection, the search begins after the selection; otherwise it begins at the cursor's position.

By default the search is case-sensitive, and can match text anywhere in the document.

### QTextCursor QTextDocument.find (self, QString expr, QTextCursor from, FindFlags options = 0)

This is an overloaded member function, provided for convenience.

Finds the next occurrence of the string, subString, in the document. The search starts at the given position, and proceeds forwards through the document unless specified otherwise in the search options. The options control the type of search performed.

Returns a cursor with the match selected if subString was found; otherwise returns a null cursor.

If the position is 0 (the default) the search begins from the beginning of the document; otherwise it begins at the specified position.

### QTextCursor QTextDocument.find (self, QRegExp expr, QTextCursor from, FindFlags options = 0)

This is an overloaded member function, provided for convenience.

Finds the next occurrence, matching the regular expression, expr, in the document. The search starts at the given position, and proceeds forwards through the document unless specified otherwise in the search options. The options control the type of search performed. The FindCaseSensitively option is ignored for this overload, use QRegExp.caseSensitivity instead.

Returns a cursor with the match selected if a match was found; otherwise returns a null cursor.

If the position is 0 (the default) the search begins from the beginning of the document; otherwise it begins at the specified position.

### QTextBlock QTextDocument.findBlock (self, int pos)

Returns the text block that contains the pos-th character.

### QTextBlock QTextDocument.findBlockByNumber (self, int blockNumber)

Returns the text block with the specified blockNumber.

This function was introduced in Qt 4.4.

See also QTextBlock.blockNumber().

### QTextBlock QTextDocument.firstBlock (self)

Returns the document's first text block.

This function was introduced in Qt 4.4.

### float QTextDocument.idealWidth (self)

Returns the ideal width of the text document. The ideal width is the actually used width of the document without optional alignments taken into account. It is always <= size().width().

This function was introduced in Qt 4.2.

See also adjustSize() and textWidth.

### float QTextDocument.indentWidth (self)

### bool QTextDocument.isEmpty (self)

Returns true if the document is empty; otherwise returns false.

### bool QTextDocument.isModified (self)

### bool QTextDocument.isRedoAvailable (self)

Returns true if redo is available; otherwise returns false.

### bool QTextDocument.isUndoAvailable (self)

Returns true if undo is available; otherwise returns false.

### bool QTextDocument.isUndoRedoEnabled (self)

### QTextBlock QTextDocument.lastBlock (self)

Returns the document's last (valid) text block.

This function was introduced in Qt 4.4.

### QVariant QTextDocument.loadResource (self, int type, QUrl name)

Loads data of the specified type from the resource with the given name.

This function is called by the rich text engine to request data that isn't directly stored by QTextDocument, but still associated with it. For example, images are referenced indirectly by the name attribute of a QTextImageFormat object.

When called by Qt, type is one of the values of QTextDocument.ResourceType.

If the QTextDocument is a child object of a QTextEdit, QTextBrowser, or a QTextDocument itself then the default implementation tries to retrieve the data from the parent.

### QTextDocument.markContentsDirty (self, int from, int length)

Marks the contents specified by the given position and length as "dirty", informing the document that it needs to be laid out again.

### int QTextDocument.maximumBlockCount (self)

### QString QTextDocument.metaInformation (self, MetaInformation info)

Returns meta information about the document of the type specified by info.

See also setMetaInformation().

### QTextObject QTextDocument.object (self, int objectIndex)

Returns the text object associated with the given objectIndex.

### QTextObject QTextDocument.objectForFormat (self, QTextFormat)

Returns the text object associated with the format f.

### int QTextDocument.pageCount (self)

returns the number of pages in this document.

### QSizeF QTextDocument.pageSize (self)

### QTextDocument.print_ (self, QPrinter printer)

Prints the document to the given printer. The QPrinter must be set up before being used with this function.

This is only a convenience method to print the whole document to the printer.

If the document is already paginated through a specified height in the pageSize() property it is printed as-is.

If the document is not paginated, like for example a document used in a QTextEdit, then a temporary copy of the document is created and the copy is broken into multiple pages according to the size of the QPrinter's paperRect(). By default a 2 cm margin is set around the document contents. In addition the current page number is printed at the bottom of each page.

Note that QPrinter.Selection is not supported as print range with this function since the selection is a property of QTextCursor. If you have a QTextEdit associated with your QTextDocument then you can use QTextEdit's print() function because QTextEdit has access to the user's selection.

See also QTextEdit.print().

### QTextDocument.redo (self)

This method is also a Qt slot with the C++ signature `void redo()`.

Redoes the last editing operation on the document if redo is available.

The provided cursor is positioned at the end of the location where the edition operation was redone.

This function was introduced in Qt 4.2.

### QTextDocument.redo (self, QTextCursor cursor)

This is an overloaded member function, provided for convenience.

Redoes the last editing operation on the document if redo is available.

### QVariant QTextDocument.resource (self, int type, QUrl name)

Returns data of the specified type from the resource with the given name.

This function is called by the rich text engine to request data that isn't directly stored by QTextDocument, but still associated with it. For example, images are referenced indirectly by the name attribute of a QTextImageFormat object.

Resources are cached internally in the document. If a resource can not be found in the cache, loadResource is called to try to load the resource. loadResource should then use addResource to add the resource to the cache.

### int QTextDocument.revision (self)

Returns the document's revision (if undo is enabled).

The revision is guaranteed to increase when a document that is not modified is edited.

This function was introduced in Qt 4.4.

See also QTextBlock.revision() and isModified().

### QTextFrame QTextDocument.rootFrame (self)

Returns the document's root frame.

### QTextDocument.setDefaultFont (self, QFont font)

### QTextDocument.setDefaultStyleSheet (self, QString sheet)

### QTextDocument.setDefaultTextOption (self, QTextOption option)

### QTextDocument.setDocumentLayout (self, QAbstractTextDocumentLayout layout)

The layout argument has it's ownership transferred to Qt.

Sets the document to use the given layout. The previous layout is deleted.

See also documentLayoutChanged().

### QTextDocument.setHtml (self, QString html)

Replaces the entire contents of the document with the given HTML-formatted text in the html string.

The HTML formatting is respected as much as possible; for example, "<b>bold</b> text" will produce text where the first word has a font weight that gives it a bold appearance: "bold text".

Note: It is the responsibility of the caller to make sure that the text is correctly decoded when a QString containing HTML is created and passed to setHtml().

See also setPlainText() and Supported HTML Subset.

### QTextDocument.setIndentWidth (self, float width)

### QTextDocument.setMaximumBlockCount (self, int maximum)

### QTextDocument.setMetaInformation (self, MetaInformation info, QString)

Sets the document's meta information of the type specified by info to the given string.

See also metaInformation().

### QTextDocument.setModified (self, bool m = True)

This method is also a Qt slot with the C++ signature `void setModified(bool = 1)`.

### QTextDocument.setPageSize (self, QSizeF size)

### QTextDocument.setPlainText (self, QString text)

Replaces the entire contents of the document with the given plain text.

See also setHtml().

### QTextDocument.setTextWidth (self, float width)

### QTextDocument.setUndoRedoEnabled (self, bool enable)

### QTextDocument.setUseDesignMetrics (self, bool b)

### QSizeF QTextDocument.size (self)

### float QTextDocument.textWidth (self)

### QString QTextDocument.toHtml (self, QByteArray encoding = QByteArray())

Returns a string containing an HTML representation of the document.

The encoding parameter specifies the value for the charset attribute in the html header. For example if 'utf-8' is specified then the beginning of the generated html will look like this:

         <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>...

If no encoding is specified then no such meta information is generated.

If you later on convert the returned html string into a byte array for transmission over a network or when saving to disk you should specify the encoding you're going to use for the conversion to a byte array here.

See also Supported HTML Subset.

### QString QTextDocument.toPlainText (self)

Returns the plain text contained in the document. If you want formatting information use a QTextCursor instead.

See also toHtml().

### QTextDocument.undo (self)

This method is also a Qt slot with the C++ signature `void undo()`.

Undoes the last editing operation on the document if undo is available. The provided cursor is positioned at the end of the location where the edition operation was undone.

See the Qt Undo Framework documentation for details.

This function was introduced in Qt 4.2.

See also undoAvailable() and isUndoRedoEnabled().

### QTextDocument.undo (self, QTextCursor cursor)

This is an overloaded member function, provided for convenience.

### bool QTextDocument.useDesignMetrics (self)

## Qt Signal Documentation

### void blockCountChanged (int)

This signal is emitted when the total number of text blocks in the document changes. The value passed in newBlockCount is the new total.

This function was introduced in Qt 4.3.

### void contentsChange (int,int,int)

This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied.

Information is provided about the position of the character in the document where the change occurred, the number of characters removed (charsRemoved), and the number of characters added (charsAdded).

The signal is emitted before the document's layout manager is notified about the change. This hook allows you to implement syntax highlighting for the document.

See also QAbstractTextDocumentLayout.documentChanged() and contentsChanged().

### void contentsChanged ()

This signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied.

See also contentsChange().

### void cursorPositionChanged (const QTextCursor&)

This signal is emitted whenever the position of a cursor changed due to an editing operation. The cursor that changed is passed in cursor. If you need a signal when the cursor is moved with the arrow keys you can use the cursorPositionChanged() signal in QTextEdit.

### void documentLayoutChanged ()

This signal is emitted when a new document layout is set.

This function was introduced in Qt 4.4.

See also setDocumentLayout().

### void modificationChanged (bool)

This signal is emitted whenever the content of the document changes in a way that affects the modification state. If changed is true, the document has been modified; otherwise it is false.

For example, calling setModified(false) on a document and then inserting text causes the signal to get emitted. If you undo that operation, causing the document to return to its original unmodified state, the signal will get emitted again.

### void redoAvailable (bool)

This signal is emitted whenever redo operations become available (available is true) or unavailable (available is false).

### void undoAvailable (bool)

This signal is emitted whenever undo operations become available (available is true) or unavailable (available is false).

See the Qt Undo Framework documentation for details.

See also undo() and isUndoRedoEnabled().

### void undoCommandAdded ()

This signal is emitted every time a new level of undo is added to the QTextDocument.

This function was introduced in Qt 4.4.