QTextEdit Class
The QTextEdit class provides a widget that is used to edit and display both plain and rich text. More...
| Header: | #include <QTextEdit> |
| qmake: | QT += widgets |
| Inherits: | QAbstractScrollArea |
| Inherited By: |
Public Types
| struct | ExtraSelection |
| enum | AutoFormattingFlag { AutoNone, AutoBulletList, AutoAll } |
| enum | LineWrapMode { NoWrap, WidgetWidth, FixedPixelWidth, FixedColumnWidth } |
Properties
|
|
Public Functions
| bool | acceptRichText() const |
| QTextEdit::AutoFormatting | autoFormatting() const |
| int | cursorWidth() const |
| QTextDocument * | document() const |
| QString | documentTitle() const |
| bool | isReadOnly() const |
| bool | isUndoRedoEnabled() const |
| int | lineWrapColumnOrWidth() const |
| QTextEdit::LineWrapMode | lineWrapMode() const |
| bool | overwriteMode() const |
| QString | placeholderText() const |
| void | setAcceptRichText(bool accept) |
| void | setAutoFormatting(QTextEdit::AutoFormatting features) |
| void | setCursorWidth(int width) |
| void | setDocument(QTextDocument *document) |
| void | setDocumentTitle(const QString &title) |
| void | setLineWrapColumnOrWidth(int w) |
| void | setLineWrapMode(QTextEdit::LineWrapMode mode) |
| void | setOverwriteMode(bool overwrite) |
| void | setPlaceholderText(const QString &placeholderText) |
| void | setReadOnly(bool ro) |
| void | setTabChangesFocus(bool b) |
| void | setTabStopDistance(qreal distance) |
| void | setTextInteractionFlags(Qt::TextInteractionFlags flags) |
| void | setUndoRedoEnabled(bool enable) |
| void | setWordWrapMode(QTextOption::WrapMode policy) |
| bool | tabChangesFocus() const |
| qreal | tabStopDistance() const |
| Qt::TextInteractionFlags | textInteractionFlags() const |
| QString | toHtml() const |
| QString | toMarkdown(QTextDocument::MarkdownFeatures features = QTextDocument::MarkdownDialectGitHub) const |
| QString | toPlainText() const |
| QTextOption::WrapMode | wordWrapMode() const |
Public Slots
| void | setHtml(const QString &text) |
| void | setMarkdown(const QString &markdown) |
| void | setPlainText(const QString &text) |
Signals
| void | textChanged() |
Detailed Description
Introduction and Concepts
QTextEdit is an advanced WYSIWYG viewer/editor supporting rich text formatting using HTML-style tags, or Markdown format. It is optimized to handle large documents and to respond quickly to user input.
QTextEdit works on paragraphs and characters. A paragraph is a formatted string which is word-wrapped to fit into the width of the widget. By default when reading plain text, one newline signifies a paragraph. A document consists of zero or more paragraphs. The words in the paragraph are aligned in accordance with the paragraph's alignment. Paragraphs are separated by hard line breaks. Each character within a paragraph has its own attributes, for example, font and color.
QTextEdit can display images, lists and tables. If the text is too large to view within the text edit's viewport, scroll bars will appear. The text edit can load both plain text and rich text files. Rich text can be described using a subset of HTML 4 markup; refer to the Supported HTML Subset page for more information.
If you just need to display a small piece of rich text use QLabel.
The rich text support in Qt is designed to provide a fast, portable and efficient way to add reasonable online help facilities to applications, and to provide a basis for rich text editors. If you find the HTML support insufficient for your needs you may consider the use of Qt WebKit, which provides a full-featured web browser widget.
The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default. It can be changed through the viewport()'s cursor property.
Using QTextEdit as a Display Widget
QTextEdit can display a large HTML subset, including tables and images.
The text can be set or replaced using setHtml() which deletes any existing text and replaces it with the text passed in the setHtml() call. If you call setHtml() with legacy HTML, and then call toHtml(), the text that is returned may have different markup, but will render the same. The entire text can be deleted with clear().
Text can also be set or replaced using setMarkdown(), and the same caveats apply: if you then call toMarkdown(), the text that is returned may be different, but the meaning is preserved as much as possible. Markdown with some embedded HTML can be parsed, with the same limitations that setHtml() has; but toMarkdown() only writes "pure" Markdown, without any embedded HTML.
Text itself can be inserted using the QTextCursor class or using the convenience functions insertHtml(), insertPlainText(), append() or paste(). QTextCursor is also able to insert complex objects like tables or lists into the document, and it deals with creating selections and applying changes to selected text.
By default the text edit wraps words at whitespace to fit within the text edit widget. The setLineWrapMode() function is used to specify the kind of line wrap you want, or NoWrap if you don't want any wrapping. Call setLineWrapMode() to set a fixed pixel width FixedPixelWidth, or character column (e.g. 80 column) FixedColumnWidth with the pixels or columns specified with setLineWrapColumnOrWidth(). If you use word wrap to the widget's width WidgetWidth, you can specify whether to break on whitespace or anywhere with setWordWrapMode().
The find() function can be used to find and select a given string within the text.
If you want to limit the total number of paragraphs in a QTextEdit, as for example it is often useful in a log viewer, then you can use QTextDocument's maximumBlockCount property for that.
Read-only Key Bindings
When QTextEdit is used read-only the key bindings are limited to navigation, and text may only be selected with the mouse:
| Keypresses | Action |
|---|---|
| Up | Moves one line up. |
| Down | Moves one line down. |
| Left | Moves one character to the left. |
| Right | Moves one character to the right. |
| PageUp | Moves one (viewport) page up. |
| PageDown | Moves one (viewport) page down. |
| Home | Moves to the beginning of the text. |
| End | Moves to the end of the text. |
| Alt+Wheel | Scrolls the page horizontally (the Wheel is the mouse wheel). |
| Ctrl+Wheel | Zooms the text. |
| Ctrl+A | Selects all text. |
The text edit may be able to provide some meta-information. For example, the documentTitle() function will return the text from within HTML <title> tags.
Note: Zooming into HTML documents only works if the font-size is not set to a fixed size.
Using QTextEdit as an Editor
All the information about using QTextEdit as a display widget also applies here.
The current char format's attributes are set with setFontItalic(), setFontWeight(), setFontUnderline(), setFontFamily(), setFontPointSize(), setTextColor() and setCurrentFont(). The current paragraph's alignment is set with setAlignment().
Selection of text is handled by the QTextCursor class, which provides functionality for creating selections, retrieving the text contents or deleting selections. You can retrieve the object that corresponds with the user-visible cursor using the textCursor() method. If you want to set a selection in QTextEdit just create one on a QTextCursor object and then make that cursor the visible cursor using setTextCursor(). The selection can be copied to the clipboard with copy(), or cut to the clipboard with cut(). The entire text can be selected using selectAll().
When the cursor is moved and the underlying formatting attributes change, the currentCharFormatChanged() signal is emitted to reflect the new attributes at the new cursor position.
The textChanged() signal is emitted whenever the text changes (as a result of setText() or through the editor itself).
QTextEdit holds a QTextDocument object which can be retrieved using the document() method. You can also set your own document object using setDocument().
QTextDocument provides an isModified() function which will return true if the text has been modified since it was either loaded or since the last call to setModified with false as argument. In addition it provides methods for undo and redo.
Drag and Drop
QTextEdit also supports custom drag and drop behavior. By default, QTextEdit will insert plain text, HTML and rich text when the user drops data of these MIME types onto a document. Reimplement canInsertFromMimeData() and insertFromMimeData() to add support for additional MIME types.
For example, to allow the user to drag and drop an image onto a QTextEdit, you could the implement these functions in the following way:
bool TextEdit::canInsertFromMimeData( const QMimeData *source ) const { if (source->hasImage()) return true; else return QTextEdit::canInsertFromMimeData(source); }
We add support for image MIME types by returning true. For all other MIME types, we use the default implementation.
void TextEdit::insertFromMimeData( const QMimeData *source ) { if (source->hasImage()) { QImage image = qvariant_cast<QImage>(source->imageData()); QTextCursor cursor = this->textCursor(); QTextDocument *document = this->document(); document->addResource(QTextDocument::ImageResource, QUrl("image"), image); cursor.insertImage("image"); } }
We unpack the image from the QVariant held by the MIME source and insert it into the document as a resource.
Editing Key Bindings
The list of key bindings which are implemented for editing:
| Keypresses | Action |
|---|---|
| Backspace | Deletes the character to the left of the cursor. |
| Delete | Deletes the character to the right of the cursor. |
| Ctrl+C | Copy the selected text to the clipboard. |
| Ctrl+Insert | Copy the selected text to the clipboard. |
| Ctrl+K | Deletes to the end of the line. |
| Ctrl+V | Pastes the clipboard text into text edit. |
| Shift+Insert | Pastes the clipboard text into text edit. |
| Ctrl+X | Deletes the selected text and copies it to the clipboard. |
| Shift+Delete | Deletes the selected text and copies it to the clipboard. |
| Ctrl+Z | Undoes the last operation. |
| Ctrl+Y | Redoes the last operation. |
| Left | Moves the cursor one character to the left. |
| Ctrl+Left | Moves the cursor one word to the left. |
| Right | Moves the cursor one character to the right. |
| Ctrl+Right | Moves the cursor one word to the right. |
| Up | Moves the cursor one line up. |
| Down | Moves the cursor one line down. |
| PageUp | Moves the cursor one page up. |
| PageDown | Moves the cursor one page down. |
| Home | Moves the cursor to the beginning of the line. |
| Ctrl+Home | Moves the cursor to the beginning of the text. |
| End | Moves the cursor to the end of the line. |
| Ctrl+End | Moves the cursor to the end of the text. |
| Alt+Wheel | Scrolls the page horizontally (the Wheel is the mouse wheel). |
To select (mark) text hold down the Shift key whilst pressing one of the movement keystrokes, for example, Shift+Right will select the character to the right, and Shift+Ctrl+Right will select the word to the right, etc.
See also QTextDocument, QTextCursor, Application Example, Syntax Highlighter Example, and Rich Text Processing.
Member Type Documentation
enum QTextEdit::AutoFormattingFlag
| Constant | Value | Description |
|---|---|---|
QTextEdit::AutoNone | 0 | Don't do any automatic formatting. |
QTextEdit::AutoBulletList | 0x00000001 | Automatically create bullet lists (e.g. when the user enters an asterisk ('*') in the left most column, or presses Enter in an existing list item. |
QTextEdit::AutoAll | 0xffffffff | Apply all automatic formatting. Currently only automatic bullet lists are supported. |
enum QTextEdit::LineWrapMode
| Constant | Value |
|---|---|
QTextEdit::NoWrap | 0 |
QTextEdit::WidgetWidth | 1 |
QTextEdit::FixedPixelWidth | 2 |
QTextEdit::FixedColumnWidth | 3 |
Property Documentation
acceptRichText : bool
This property holds whether the text edit accepts rich text insertions by the user
When this propery is set to false text edit will accept only plain text input from the user. For example through clipboard or drag and drop.
This property's default is true.
This property was introduced in Qt 4.1.
Access functions:
| bool | acceptRichText() const |
| void | setAcceptRichText(bool accept) |
autoFormatting : AutoFormatting
This property holds the enabled set of auto formatting features
The value can be any combination of the values in the AutoFormattingFlag enum. The default is AutoNone. Choose AutoAll to enable all automatic formatting.
Currently, the only automatic formatting feature provided is AutoBulletList; future versions of Qt may offer more.
Access functions:
| QTextEdit::AutoFormatting | autoFormatting() const |
| void | setAutoFormatting(QTextEdit::AutoFormatting features) |
cursorWidth : int
This property specifies the width of the cursor in pixels. The default value is 1.
This property was introduced in Qt 4.2.
Access functions:
| int | cursorWidth() const |
| void | setCursorWidth(int width) |
document : QTextDocument*
This property holds the underlying document of the text editor.
Note: The editor does not take ownership of the document unless it is the document's parent object. The parent object of the provided document remains the owner of the object. If the previously assigned document is a child of the editor then it will be deleted.
Access functions:
| QTextDocument * | document() const |
| void | setDocument(QTextDocument *document) |
documentTitle : QString
This property holds the title of the document parsed from the text.
By default, for a newly-created, empty document, this property contains an empty string.
Access functions:
| QString | documentTitle() const |
| void | setDocumentTitle(const QString &title) |
html : QString
This property provides an HTML interface to the text of the text edit.
toHtml() returns the text of the text edit as html.
setHtml() changes the text of the text edit. Any previous text is removed and the undo/redo history is cleared. The input text is interpreted as rich text in html format. currentCharFormat() is also reset, unless textCursor() is already at the beginning of the document.
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().
By default, for a newly-created, empty document, this property contains text to describe an HTML 4.0 document with no body text.
Access functions:
| QString | toHtml() const |
| void | setHtml(const QString &text) |
Notifier signal:
| void | textChanged() |
See also Supported HTML Subset and plainText.
lineWrapColumnOrWidth : int
This property holds the position (in pixels or columns depending on the wrap mode) where text will be wrapped
If the wrap mode is FixedPixelWidth, the value is the number of pixels from the left edge of the text edit at which text should be wrapped. If the wrap mode is FixedColumnWidth, the value is the column number (in character columns) from the left edge of the text edit at which text should be wrapped.
By default, this property contains a value of 0.
Access functions:
| int | lineWrapColumnOrWidth() const |
| void | setLineWrapColumnOrWidth(int w) |
See also lineWrapMode.
lineWrapMode : LineWrapMode
This property holds the line wrap mode
The default mode is WidgetWidth which causes words to be wrapped at the right edge of the text edit. Wrapping occurs at whitespace, keeping whole words intact. If you want wrapping to occur within words use setWordWrapMode(). If you set a wrap mode of FixedPixelWidth or FixedColumnWidth you should also call setLineWrapColumnOrWidth() with the width you want.
Access functions:
| QTextEdit::LineWrapMode | lineWrapMode() const |
| void | setLineWrapMode(QTextEdit::LineWrapMode mode) |
See also lineWrapColumnOrWidth.
markdown : QString
This property provides a Markdown interface to the text of the text edit.
toMarkdown() returns the text of the text edit as "pure" Markdown, without any embedded HTML formatting. Some features that QTextDocument supports (such as the use of specific colors and named fonts) cannot be expressed in "pure" Markdown, and they will be omitted.
setMarkdown() changes the text of the text edit. Any previous text is removed and the undo/redo history is cleared. The input text is interpreted as rich text in Markdown format.
Parsing of HTML included in the markdown string is handled in the same way as in setHtml; however, Markdown formatting inside HTML blocks is not supported.
Some features of the parser can be enabled or disabled via the features argument:
| Constant | Description |
|---|---|
MarkdownNoHTML | Any HTML tags in the Markdown text will be discarded |
MarkdownDialectCommonMark | The parser supports only the features standardized by CommonMark |
MarkdownDialectGitHub | The parser supports the GitHub dialect |
The default is MarkdownDialectGitHub.
This property was introduced in Qt 5.14.
Access functions:
| QString | toMarkdown(QTextDocument::MarkdownFeatures features = QTextDocument::MarkdownDialectGitHub) const |
| void | setMarkdown(const QString &markdown) |
Notifier signal:
| void | textChanged() |
See also plainText, html, QTextDocument::toMarkdown(), and QTextDocument::setMarkdown().
overwriteMode : bool
This property holds whether text entered by the user will overwrite existing text
As with many text editors, the text editor widget can be configured to insert or overwrite existing text with new text entered by the user.
If this property is true, existing text is overwritten, character-for-character by new text; otherwise, text is inserted at the cursor position, displacing existing text.
By default, this property is false (new text does not overwrite existing text).
This property was introduced in Qt 4.1.
Access functions:
| bool | overwriteMode() const |
| void | setOverwriteMode(bool overwrite) |
placeholderText : QString
This property holds the editor placeholder text
Setting this property makes the editor display a grayed-out placeholder text as long as the document() is empty.
By default, this property contains an empty string.
This property was introduced in Qt 5.2.
Access functions:
| QString | placeholderText() const |
| void | setPlaceholderText(const QString &placeholderText) |
See also document().
plainText : QString
This property gets and sets the text editor's contents as plain text. Previous contents are removed and undo/redo history is reset when the property is set. currentCharFormat() is also reset, unless textCursor() is already at the beginning of the document.
If the text edit has another content type, it will not be replaced by plain text if you call toPlainText(). The only exception to this is the non-break space, nbsp;, that will be converted into standard space.
By default, for an editor with no contents, this property contains an empty string.
This property was introduced in Qt 4.3.
Access functions:
| QString | toPlainText() const |
| void | setPlainText(const QString &text) |
See also html.
readOnly : bool
This property holds whether the text edit is read-only
In a read-only text edit the user can only navigate through the text and select text; modifying the text is not possible.
This property's default is false.
Access functions:
| bool | isReadOnly() const |
| void | setReadOnly(bool ro) |
tabChangesFocus : bool
This property holds whether Tab changes focus or is accepted as input
In some occasions text edits should not allow the user to input tabulators or change indentation using the Tab key, as this breaks the focus chain. The default is false.
Access functions:
| bool | tabChangesFocus() const |
| void | setTabChangesFocus(bool b) |
tabStopDistance : qreal
This property holds the tab stop distance in pixels
By default, this property contains a value of 80 pixels.
This property was introduced in Qt 5.10.
Access functions:
| qreal | tabStopDistance() const |
| void | setTabStopDistance(qreal distance) |
textInteractionFlags : Qt::TextInteractionFlags
Specifies how the widget should interact with user input.
The default value depends on whether the QTextEdit is read-only or editable, and whether it is a QTextBrowser or not.
This property was introduced in Qt 4.2.
Access functions:
| Qt::TextInteractionFlags | textInteractionFlags() const |
| void | setTextInteractionFlags(Qt::TextInteractionFlags flags) |
undoRedoEnabled : bool
This property holds whether undo and redo are enabled
Users are only able to undo or redo actions if this property is true, and if there is an action that can be undone (or redone).
Access functions:
| bool | isUndoRedoEnabled() const |
| void | setUndoRedoEnabled(bool enable) |
wordWrapMode : QTextOption::WrapMode
This property holds the mode QTextEdit will use when wrapping text by words
By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
Access functions:
| QTextOption::WrapMode | wordWrapMode() const |
| void | setWordWrapMode(QTextOption::WrapMode policy) |
See also QTextOption::WrapMode.