1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qtextedit_p.h"
43 #include "qlineedit.h"
44 #include "qtextbrowser.h"
46 #ifndef QT_NO_TEXTEDIT
52 #include <qclipboard.h>
56 #include "private/qtextdocumentlayout_p.h"
57 #include "qtextdocument.h"
58 #include "private/qtextdocument_p.h"
59 #include "qtextlist.h"
60 #include "private/qwidgettextcontrol_p.h"
62 #include <qtextformat.h>
63 #include <qdatetime.h>
64 #include <qapplication.h>
66 #include <qtexttable.h>
74 #ifndef QT_NO_TEXTEDIT
75 static inline bool shouldEnableInputMethod(QTextEdit *textedit)
77 return !textedit->isReadOnly();
80 class QTextEditControl : public QWidgetTextControl
83 inline QTextEditControl(QObject *parent) : QWidgetTextControl(parent) {}
85 virtual QMimeData *createMimeDataFromSelection() const {
86 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
88 return QWidgetTextControl::createMimeDataFromSelection();
89 return ed->createMimeDataFromSelection();
91 virtual bool canInsertFromMimeData(const QMimeData *source) const {
92 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
94 return QWidgetTextControl::canInsertFromMimeData(source);
95 return ed->canInsertFromMimeData(source);
97 virtual void insertFromMimeData(const QMimeData *source) {
98 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
100 QWidgetTextControl::insertFromMimeData(source);
102 ed->insertFromMimeData(source);
106 QTextEditPrivate::QTextEditPrivate()
108 autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),
109 lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),
110 wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0),
111 textFormat(Qt::AutoText)
113 ignoreAutomaticScrollbarAdjustment = false;
114 preferRichText = false;
115 showCursorOnInitialShow = true;
119 void QTextEditPrivate::createAutoBulletList()
121 QTextCursor cursor = control->textCursor();
122 cursor.beginEditBlock();
124 QTextBlockFormat blockFmt = cursor.blockFormat();
126 QTextListFormat listFmt;
127 listFmt.setStyle(QTextListFormat::ListDisc);
128 listFmt.setIndent(blockFmt.indent() + 1);
130 blockFmt.setIndent(0);
131 cursor.setBlockFormat(blockFmt);
133 cursor.createList(listFmt);
135 cursor.endEditBlock();
136 control->setTextCursor(cursor);
139 void QTextEditPrivate::init(const QString &html)
142 control = new QTextEditControl(q);
143 control->setPalette(q->palette());
145 QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));
146 QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));
147 QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));
148 QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), q, SLOT(_q_ensureVisible(QRectF)));
149 QObject::connect(control, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
150 q, SLOT(_q_currentCharFormatChanged(QTextCharFormat)));
152 QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));
153 QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));
154 QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));
155 QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
156 QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
157 QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged()));
159 QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
161 QTextDocument *doc = control->document();
162 // set a null page size initially to avoid any relayouting until the textedit
163 // is shown. relayoutDocument() will take care of setting the page size to the
164 // viewport dimensions later.
165 doc->setPageSize(QSize(0, 0));
166 doc->documentLayout()->setPaintDevice(viewport);
167 doc->setDefaultFont(q->font());
168 doc->setUndoRedoEnabled(false); // flush undo buffer.
169 doc->setUndoRedoEnabled(true);
172 control->setHtml(html);
174 hbar->setSingleStep(20);
175 vbar->setSingleStep(20);
177 viewport->setBackgroundRole(QPalette::Base);
178 q->setAcceptDrops(true);
179 q->setFocusPolicy(Qt::WheelFocus);
180 q->setAttribute(Qt::WA_KeyCompression);
181 q->setAttribute(Qt::WA_InputMethodEnabled);
184 viewport->setCursor(Qt::IBeamCursor);
187 setSingleFingerPanEnabled(true);
191 void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
193 if (!contentsRect.isValid()) {
197 const int xOffset = horizontalOffset();
198 const int yOffset = verticalOffset();
199 const QRectF visibleRect(xOffset, yOffset, viewport->width(), viewport->height());
201 QRect r = contentsRect.intersected(visibleRect).toAlignedRect();
205 r.translate(-xOffset, -yOffset);
209 void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
211 QTextCursor cursor = control->textCursor();
213 qreal lastY = control->cursorRect(cursor).top();
215 // move using movePosition to keep the cursor's x
217 qreal y = control->cursorRect(cursor).top();
218 distance += qAbs(y - lastY);
220 moved = cursor.movePosition(op, moveMode);
221 } while (moved && distance < viewport->height());
224 if (op == QTextCursor::Up) {
225 cursor.movePosition(QTextCursor::Down, moveMode);
226 vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
228 cursor.movePosition(QTextCursor::Up, moveMode);
229 vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
232 control->setTextCursor(cursor);
235 #ifndef QT_NO_SCROLLBAR
236 static QSize documentSize(QWidgetTextControl *control)
238 QTextDocument *doc = control->document();
239 QAbstractTextDocumentLayout *layout = doc->documentLayout();
243 if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
244 docSize = tlayout->dynamicDocumentSize().toSize();
245 int percentageDone = tlayout->layoutStatus();
246 // extrapolate height
247 if (percentageDone > 0)
248 docSize.setHeight(docSize.height() * 100 / percentageDone);
250 docSize = layout->documentSize().toSize();
256 void QTextEditPrivate::_q_adjustScrollbars()
258 if (ignoreAutomaticScrollbarAdjustment)
260 ignoreAutomaticScrollbarAdjustment = true; // avoid recursion, #106108
262 QSize viewportSize = viewport->size();
263 QSize docSize = documentSize(control);
265 // due to the recursion guard we have to repeat this step a few times,
266 // as adding/removing a scroll bar will cause the document or viewport
268 // ideally we should loop until the viewport size and doc size stabilize,
269 // but in corner cases they might fluctuate, so we need to limit the
270 // number of iterations
271 for (int i = 0; i < 4; ++i) {
272 hbar->setRange(0, docSize.width() - viewportSize.width());
273 hbar->setPageStep(viewportSize.width());
275 vbar->setRange(0, docSize.height() - viewportSize.height());
276 vbar->setPageStep(viewportSize.height());
278 // if we are in left-to-right mode widening the document due to
279 // lazy layouting does not require a repaint. If in right-to-left
280 // the scroll bar has the value zero and it visually has the maximum
281 // value (it is visually at the right), then widening the document
282 // keeps it at value zero but visually adjusts it to the new maximum
283 // on the right, hence we need an update.
284 if (q_func()->isRightToLeft())
287 _q_showOrHideScrollBars();
289 const QSize oldViewportSize = viewportSize;
290 const QSize oldDocSize = docSize;
292 // make sure the document is layouted if the viewport width changes
293 viewportSize = viewport->size();
294 if (viewportSize.width() != oldViewportSize.width())
297 docSize = documentSize(control);
298 if (viewportSize == oldViewportSize && docSize == oldDocSize)
301 ignoreAutomaticScrollbarAdjustment = false;
305 // rect is in content coordinates
306 void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
308 const QRect rect = _rect.toRect();
309 if ((vbar->isVisible() && vbar->maximum() < rect.bottom())
310 || (hbar->isVisible() && hbar->maximum() < rect.right()))
311 _q_adjustScrollbars();
312 const int visibleWidth = viewport->width();
313 const int visibleHeight = viewport->height();
314 const bool rtl = q_func()->isRightToLeft();
316 if (rect.x() < horizontalOffset()) {
318 hbar->setValue(hbar->maximum() - rect.x());
320 hbar->setValue(rect.x());
321 } else if (rect.x() + rect.width() > horizontalOffset() + visibleWidth) {
323 hbar->setValue(hbar->maximum() - (rect.x() + rect.width() - visibleWidth));
325 hbar->setValue(rect.x() + rect.width() - visibleWidth);
328 if (rect.y() < verticalOffset())
329 vbar->setValue(rect.y());
330 else if (rect.y() + rect.height() > verticalOffset() + visibleHeight)
331 vbar->setValue(rect.y() + rect.height() - visibleHeight);
336 \brief The QTextEdit class provides a widget that is used to edit and display
337 both plain and rich text.
339 \ingroup richtext-processing
344 \section1 Introduction and Concepts
346 QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
347 text formatting using HTML-style tags. It is optimized to handle
348 large documents and to respond quickly to user input.
350 QTextEdit works on paragraphs and characters. A paragraph is a
351 formatted string which is word-wrapped to fit into the width of
352 the widget. By default when reading plain text, one newline
353 signifies a paragraph. A document consists of zero or more
354 paragraphs. The words in the paragraph are aligned in accordance
355 with the paragraph's alignment. Paragraphs are separated by hard
356 line breaks. Each character within a paragraph has its own
357 attributes, for example, font and color.
359 QTextEdit can display images, lists and tables. If the text is
360 too large to view within the text edit's viewport, scroll bars will
361 appear. The text edit can load both plain text and HTML files (a
362 subset of HTML 3.2 and 4).
364 If you just need to display a small piece of rich text use QLabel.
366 The rich text support in Qt is designed to provide a fast, portable and
367 efficient way to add reasonable online help facilities to
368 applications, and to provide a basis for rich text editors. If
369 you find the HTML support insufficient for your needs you may consider
370 the use of QtWebKit, which provides a full-featured web browser
373 The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default.
374 It can be changed through the viewport()'s cursor property.
376 \section1 Using QTextEdit as a Display Widget
378 QTextEdit can display a large HTML subset, including tables and
381 The text is set or replaced using setHtml() which deletes any
382 existing text and replaces it with the text passed in the
383 setHtml() call. If you call setHtml() with legacy HTML, and then
384 call toHtml(), the text that is returned may have different markup,
385 but will render the same. The entire text can be deleted with clear().
387 Text itself can be inserted using the QTextCursor class or using the
388 convenience functions insertHtml(), insertPlainText(), append() or
389 paste(). QTextCursor is also able to insert complex objects like tables
390 or lists into the document, and it deals with creating selections
391 and applying changes to selected text.
393 By default the text edit wraps words at whitespace to fit within
394 the text edit widget. The setLineWrapMode() function is used to
395 specify the kind of line wrap you want, or \l NoWrap if you don't
396 want any wrapping. Call setLineWrapMode() to set a fixed pixel width
397 \l FixedPixelWidth, or character column (e.g. 80 column) \l
398 FixedColumnWidth with the pixels or columns specified with
399 setLineWrapColumnOrWidth(). If you use word wrap to the widget's width
400 \l WidgetWidth, you can specify whether to break on whitespace or
401 anywhere with setWordWrapMode().
403 The find() function can be used to find and select a given string
406 If you want to limit the total number of paragraphs in a QTextEdit,
407 as it is for example open useful in a log viewer, then you can use
408 QTextDocument's maximumBlockCount property for that.
410 \section2 Read-only Key Bindings
412 When QTextEdit is used read-only the key bindings are limited to
413 navigation, and text may only be selected with the mouse:
415 \header \i Keypresses \i Action
416 \row \i Up \i Moves one line up.
417 \row \i Down \i Moves one line down.
418 \row \i Left \i Moves one character to the left.
419 \row \i Right \i Moves one character to the right.
420 \row \i PageUp \i Moves one (viewport) page up.
421 \row \i PageDown \i Moves one (viewport) page down.
422 \row \i Home \i Moves to the beginning of the text.
423 \row \i End \i Moves to the end of the text.
425 \i Scrolls the page horizontally (the Wheel is the mouse wheel).
426 \row \i Ctrl+Wheel \i Zooms the text.
427 \row \i Ctrl+A \i Selects all text.
430 The text edit may be able to provide some meta-information. For
431 example, the documentTitle() function will return the text from
432 within HTML \c{<title>} tags.
434 \section1 Using QTextEdit as an Editor
436 All the information about using QTextEdit as a display widget also
439 The current char format's attributes are set with setFontItalic(),
440 setFontWeight(), setFontUnderline(), setFontFamily(),
441 setFontPointSize(), setTextColor() and setCurrentFont(). The current
442 paragraph's alignment is set with setAlignment().
444 Selection of text is handled by the QTextCursor class, which provides
445 functionality for creating selections, retrieving the text contents or
446 deleting selections. You can retrieve the object that corresponds with
447 the user-visible cursor using the textCursor() method. If you want to set
448 a selection in QTextEdit just create one on a QTextCursor object and
449 then make that cursor the visible cursor using setTextCursor(). The selection
450 can be copied to the clipboard with copy(), or cut to the clipboard with
451 cut(). The entire text can be selected using selectAll().
453 When the cursor is moved and the underlying formatting attributes change,
454 the currentCharFormatChanged() signal is emitted to reflect the new attributes
455 at the new cursor position.
457 QTextEdit holds a QTextDocument object which can be retrieved using the
458 document() method. You can also set your own document object using setDocument().
459 QTextDocument emits a textChanged() signal if the text changes and it also
460 provides a isModified() function which will return true if the text has been
461 modified since it was either loaded or since the last call to setModified
462 with false as argument. In addition it provides methods for undo and redo.
464 \section2 Drag and Drop
466 QTextEdit also supports custom drag and drop behavior. By default,
467 QTextEdit will insert plain text, HTML and rich text when the user drops
468 data of these MIME types onto a document. Reimplement
469 canInsertFromMimeData() and insertFromMimeData() to add support for
470 additional MIME types.
472 For example, to allow the user to drag and drop an image onto a QTextEdit,
473 you could the implement these functions in the following way:
475 \snippet doc/src/snippets/textdocument-imagedrop/textedit.cpp 0
477 We add support for image MIME types by returning true. For all other
478 MIME types, we use the default implementation.
480 \snippet doc/src/snippets/textdocument-imagedrop/textedit.cpp 1
482 We unpack the image from the QVariant held by the MIME source and insert
483 it into the document as a resource.
485 \section2 Editing Key Bindings
487 The list of key bindings which are implemented for editing:
489 \header \i Keypresses \i Action
490 \row \i Backspace \i Deletes the character to the left of the cursor.
491 \row \i Delete \i Deletes the character to the right of the cursor.
492 \row \i Ctrl+C \i Copy the selected text to the clipboard.
493 \row \i Ctrl+Insert \i Copy the selected text to the clipboard.
494 \row \i Ctrl+K \i Deletes to the end of the line.
495 \row \i Ctrl+V \i Pastes the clipboard text into text edit.
496 \row \i Shift+Insert \i Pastes the clipboard text into text edit.
497 \row \i Ctrl+X \i Deletes the selected text and copies it to the clipboard.
498 \row \i Shift+Delete \i Deletes the selected text and copies it to the clipboard.
499 \row \i Ctrl+Z \i Undoes the last operation.
500 \row \i Ctrl+Y \i Redoes the last operation.
501 \row \i Left \i Moves the cursor one character to the left.
502 \row \i Ctrl+Left \i Moves the cursor one word to the left.
503 \row \i Right \i Moves the cursor one character to the right.
504 \row \i Ctrl+Right \i Moves the cursor one word to the right.
505 \row \i Up \i Moves the cursor one line up.
506 \row \i Down \i Moves the cursor one line down.
507 \row \i PageUp \i Moves the cursor one page up.
508 \row \i PageDown \i Moves the cursor one page down.
509 \row \i Home \i Moves the cursor to the beginning of the line.
510 \row \i Ctrl+Home \i Moves the cursor to the beginning of the text.
511 \row \i End \i Moves the cursor to the end of the line.
512 \row \i Ctrl+End \i Moves the cursor to the end of the text.
513 \row \i Alt+Wheel \i Scrolls the page horizontally (the Wheel is the mouse wheel).
516 To select (mark) text hold down the Shift key whilst pressing one
517 of the movement keystrokes, for example, \e{Shift+Right}
518 will select the character to the right, and \e{Shift+Ctrl+Right} will select the word to the right, etc.
520 \sa QTextDocument, QTextCursor, {Application Example},
521 {Syntax Highlighter Example}, {Rich Text Processing}
525 \property QTextEdit::plainText
528 This property gets and sets the text editor's contents as plain
529 text. Previous contents are removed and undo/redo history is reset
530 when the property is set.
532 If the text edit has another content type, it will not be replaced
533 by plain text if you call toPlainText(). The only exception to this
534 is the non-break space, \e{nbsp;}, that will be converted into
537 By default, for an editor with no contents, this property contains
544 \property QTextEdit::undoRedoEnabled
545 \brief whether undo and redo are enabled
547 Users are only able to undo or redo actions if this property is
548 true, and if there is an action that can be undone (or redone).
552 \enum QTextEdit::LineWrapMode
556 \value FixedPixelWidth
557 \value FixedColumnWidth
561 \enum QTextEdit::AutoFormattingFlag
563 \value AutoNone Don't do any automatic formatting.
564 \value AutoBulletList Automatically create bullet lists (e.g. when
565 the user enters an asterisk ('*') in the left most column, or
566 presses Enter in an existing list item.
567 \value AutoAll Apply all automatic formatting. Currently only
568 automatic bullet lists are supported.
573 Constructs an empty QTextEdit with parent \a
576 QTextEdit::QTextEdit(QWidget *parent)
577 : QAbstractScrollArea(*new QTextEditPrivate, parent)
586 QTextEdit::QTextEdit(QTextEditPrivate &dd, QWidget *parent)
587 : QAbstractScrollArea(dd, parent)
594 Constructs a QTextEdit with parent \a parent. The text edit will display
595 the text \a text. The text is interpreted as html.
597 QTextEdit::QTextEdit(const QString &text, QWidget *parent)
598 : QAbstractScrollArea(*new QTextEditPrivate, parent)
609 QTextEdit::~QTextEdit()
614 Returns the point size of the font of the current format.
616 \sa setFontFamily() setCurrentFont() setFontPointSize()
618 qreal QTextEdit::fontPointSize() const
620 Q_D(const QTextEdit);
621 return d->control->textCursor().charFormat().fontPointSize();
625 Returns the font family of the current format.
627 \sa setFontFamily() setCurrentFont() setFontPointSize()
629 QString QTextEdit::fontFamily() const
631 Q_D(const QTextEdit);
632 return d->control->textCursor().charFormat().fontFamily();
636 Returns the font weight of the current format.
638 \sa setFontWeight() setCurrentFont() setFontPointSize() QFont::Weight
640 int QTextEdit::fontWeight() const
642 Q_D(const QTextEdit);
643 return d->control->textCursor().charFormat().fontWeight();
647 Returns true if the font of the current format is underlined; otherwise returns
650 \sa setFontUnderline()
652 bool QTextEdit::fontUnderline() const
654 Q_D(const QTextEdit);
655 return d->control->textCursor().charFormat().fontUnderline();
659 Returns true if the font of the current format is italic; otherwise returns
664 bool QTextEdit::fontItalic() const
666 Q_D(const QTextEdit);
667 return d->control->textCursor().charFormat().fontItalic();
671 Returns the text color of the current format.
675 QColor QTextEdit::textColor() const
677 Q_D(const QTextEdit);
678 return d->control->textCursor().charFormat().foreground().color();
684 Returns the text background color of the current format.
686 \sa setTextBackgroundColor()
688 QColor QTextEdit::textBackgroundColor() const
690 Q_D(const QTextEdit);
691 return d->control->textCursor().charFormat().background().color();
695 Returns the font of the current format.
697 \sa setCurrentFont() setFontFamily() setFontPointSize()
699 QFont QTextEdit::currentFont() const
701 Q_D(const QTextEdit);
702 return d->control->textCursor().charFormat().font();
706 Sets the alignment of the current paragraph to \a a. Valid
707 alignments are Qt::AlignLeft, Qt::AlignRight,
708 Qt::AlignJustify and Qt::AlignCenter (which centers
711 void QTextEdit::setAlignment(Qt::Alignment a)
714 QTextBlockFormat fmt;
716 QTextCursor cursor = d->control->textCursor();
717 cursor.mergeBlockFormat(fmt);
718 d->control->setTextCursor(cursor);
722 Returns the alignment of the current paragraph.
726 Qt::Alignment QTextEdit::alignment() const
728 Q_D(const QTextEdit);
729 return d->control->textCursor().blockFormat().alignment();
733 Makes \a document the new document of the text editor.
735 \note The editor \e{does not take ownership of the document} unless it
736 is the document's parent object. The parent object of the provided document
737 remains the owner of the object.
739 The editor does not delete the current document, even if it is a child of the editor.
743 void QTextEdit::setDocument(QTextDocument *document)
746 d->control->setDocument(document);
747 d->updateDefaultTextOption();
748 d->relayoutDocument();
752 Returns a pointer to the underlying document.
756 QTextDocument *QTextEdit::document() const
758 Q_D(const QTextEdit);
759 return d->control->document();
763 Sets the visible \a cursor.
765 void QTextEdit::setTextCursor(const QTextCursor &cursor)
768 d->control->setTextCursor(cursor);
772 Returns a copy of the QTextCursor that represents the currently visible cursor.
773 Note that changes on the returned cursor do not affect QTextEdit's cursor; use
774 setTextCursor() to update the visible cursor.
776 QTextCursor QTextEdit::textCursor() const
778 Q_D(const QTextEdit);
779 return d->control->textCursor();
783 Sets the font family of the current format to \a fontFamily.
785 \sa fontFamily() setCurrentFont()
787 void QTextEdit::setFontFamily(const QString &fontFamily)
790 fmt.setFontFamily(fontFamily);
791 mergeCurrentCharFormat(fmt);
795 Sets the point size of the current format to \a s.
797 Note that if \a s is zero or negative, the behavior of this
798 function is not defined.
800 \sa fontPointSize() setCurrentFont() setFontFamily()
802 void QTextEdit::setFontPointSize(qreal s)
805 fmt.setFontPointSize(s);
806 mergeCurrentCharFormat(fmt);
810 \fn void QTextEdit::setFontWeight(int weight)
812 Sets the font weight of the current format to the given \a weight,
813 where the value used is in the range defined by the QFont::Weight
816 \sa fontWeight(), setCurrentFont(), setFontFamily()
818 void QTextEdit::setFontWeight(int w)
821 fmt.setFontWeight(w);
822 mergeCurrentCharFormat(fmt);
826 If \a underline is true, sets the current format to underline;
827 otherwise sets the current format to non-underline.
831 void QTextEdit::setFontUnderline(bool underline)
834 fmt.setFontUnderline(underline);
835 mergeCurrentCharFormat(fmt);
839 If \a italic is true, sets the current format to italic;
840 otherwise sets the current format to non-italic.
844 void QTextEdit::setFontItalic(bool italic)
847 fmt.setFontItalic(italic);
848 mergeCurrentCharFormat(fmt);
852 Sets the text color of the current format to \a c.
856 void QTextEdit::setTextColor(const QColor &c)
859 fmt.setForeground(QBrush(c));
860 mergeCurrentCharFormat(fmt);
866 Sets the text background color of the current format to \a c.
868 \sa textBackgroundColor()
870 void QTextEdit::setTextBackgroundColor(const QColor &c)
873 fmt.setBackground(QBrush(c));
874 mergeCurrentCharFormat(fmt);
878 Sets the font of the current format to \a f.
880 \sa currentFont() setFontPointSize() setFontFamily()
882 void QTextEdit::setCurrentFont(const QFont &f)
886 mergeCurrentCharFormat(fmt);
892 Undoes the last operation.
894 If there is no operation to undo, i.e. there is no undo step in
895 the undo/redo history, nothing happens.
899 void QTextEdit::undo()
905 void QTextEdit::redo()
912 \fn void QTextEdit::undo() const
913 \fn void QTextEdit::redo() const
916 Use the non-const overload instead.
920 \fn void QTextEdit::redo()
923 Redoes the last operation.
925 If there is no operation to redo, i.e. there is no redo step in
926 the undo/redo history, nothing happens.
931 #ifndef QT_NO_CLIPBOARD
933 Copies the selected text to the clipboard and deletes it from
936 If there is no selected text nothing happens.
941 void QTextEdit::cut()
948 Copies any selected text to the clipboard.
953 void QTextEdit::copy()
960 Pastes the text from the clipboard into the text edit at the
961 current cursor position.
963 If there is no text in the clipboard nothing happens.
965 To change the behavior of this function, i.e. to modify what
966 QTextEdit can paste and how it is being pasted, reimplement the
967 virtual canInsertFromMimeData() and insertFromMimeData()
973 void QTextEdit::paste()
981 Deletes all the text in the text edit.
983 Note that the undo/redo history is cleared by this function.
985 \sa cut() setPlainText() setHtml()
987 void QTextEdit::clear()
990 // clears and sets empty content
998 \sa copy() cut() textCursor()
1000 void QTextEdit::selectAll()
1003 d->control->selectAll();
1008 bool QTextEdit::event(QEvent *e)
1011 #ifndef QT_NO_CONTEXTMENU
1012 if (e->type() == QEvent::ContextMenu
1013 && static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
1015 ensureCursorVisible();
1016 const QPoint cursorPos = cursorRect().center();
1017 QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
1018 ce.setAccepted(e->isAccepted());
1019 const bool result = QAbstractScrollArea::event(&ce);
1020 e->setAccepted(ce.isAccepted());
1022 } else if (e->type() == QEvent::ShortcutOverride
1023 || e->type() == QEvent::ToolTip) {
1024 d->sendControlEvent(e);
1026 #endif // QT_NO_CONTEXTMENU
1027 #ifdef QT_KEYPAD_NAVIGATION
1028 if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
1029 if (QApplication::keypadNavigationEnabled())
1030 d->sendControlEvent(e);
1033 return QAbstractScrollArea::event(e);
1039 void QTextEdit::timerEvent(QTimerEvent *e)
1042 if (e->timerId() == d->autoScrollTimer.timerId()) {
1043 QRect visible = d->viewport->rect();
1046 pos = d->autoScrollDragPos;
1047 visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
1048 -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
1050 const QPoint globalPos = QCursor::pos();
1051 pos = d->viewport->mapFromGlobal(globalPos);
1052 QMouseEvent ev(QEvent::MouseMove, pos, mapTo(topLevelWidget(), pos), globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
1053 mouseMoveEvent(&ev);
1055 int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
1056 int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
1057 int delta = qMax(deltaX, deltaY);
1061 int timeout = 4900 / (delta * delta);
1062 d->autoScrollTimer.start(timeout, this);
1065 d->vbar->triggerAction(pos.y() < visible.center().y() ?
1066 QAbstractSlider::SliderSingleStepSub
1067 : QAbstractSlider::SliderSingleStepAdd);
1069 d->hbar->triggerAction(pos.x() < visible.center().x() ?
1070 QAbstractSlider::SliderSingleStepSub
1071 : QAbstractSlider::SliderSingleStepAdd);
1074 #ifdef QT_KEYPAD_NAVIGATION
1075 else if (e->timerId() == d->deleteAllTimer.timerId()) {
1076 d->deleteAllTimer.stop();
1083 Changes the text of the text edit to the string \a text.
1084 Any previous text is removed.
1086 \a text is interpreted as plain text.
1088 Note that the undo/redo history is cleared by this function.
1093 void QTextEdit::setPlainText(const QString &text)
1096 d->control->setPlainText(text);
1097 d->preferRichText = false;
1101 QString QTextEdit::toPlainText() const
1103 Returns the text of the text edit as plain text.
1105 \sa QTextEdit::setPlainText()
1107 QString QTextEdit::toPlainText() const
1109 Q_D(const QTextEdit);
1110 return d->control->toPlainText();
1114 \property QTextEdit::html
1116 This property provides an HTML interface to the text of the text edit.
1118 toHtml() returns the text of the text edit as html.
1120 setHtml() changes the text of the text edit. Any previous text is
1121 removed and the undo/redo history is cleared. The input text is
1122 interpreted as rich text in html format.
1124 \note It is the responsibility of the caller to make sure that the
1125 text is correctly decoded when a QString containing HTML is created
1126 and passed to setHtml().
1128 By default, for a newly-created, empty document, this property contains
1129 text to describe an HTML 4.0 document with no body text.
1131 \sa {Supported HTML Subset}, plainText
1134 #ifndef QT_NO_TEXTHTMLPARSER
1135 void QTextEdit::setHtml(const QString &text)
1138 d->control->setHtml(text);
1139 d->preferRichText = true;
1142 QString QTextEdit::toHtml() const
1144 Q_D(const QTextEdit);
1145 return d->control->toHtml();
1152 void QTextEdit::keyPressEvent(QKeyEvent *e)
1156 #ifdef QT_KEYPAD_NAVIGATION
1158 case Qt::Key_Select:
1159 if (QApplication::keypadNavigationEnabled()) {
1160 // code assumes linksaccessible + editable isn't meaningful
1161 if (d->control->textInteractionFlags() & Qt::TextEditable) {
1162 setEditFocus(!hasEditFocus());
1164 if (!hasEditFocus())
1167 QTextCursor cursor = d->control->textCursor();
1168 QTextCharFormat charFmt = cursor.charFormat();
1169 if (!(d->control->textInteractionFlags() & Qt::LinksAccessibleByKeyboard)
1170 || !cursor.hasSelection() || charFmt.anchorHref().isEmpty()) {
1180 if (!QApplication::keypadNavigationEnabled()
1181 || (QApplication::keypadNavigationEnabled() && !hasEditFocus())) {
1187 if (QApplication::keypadNavigationEnabled()) {
1188 if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
1189 if (e->text()[0].isPrint())
1200 #ifndef QT_NO_SHORTCUT
1202 Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
1204 if (tif & Qt::TextSelectableByKeyboard){
1205 if (e == QKeySequence::SelectPreviousPage) {
1207 d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
1209 } else if (e ==QKeySequence::SelectNextPage) {
1211 d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
1215 if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
1216 if (e == QKeySequence::MoveToPreviousPage) {
1218 d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
1220 } else if (e == QKeySequence::MoveToNextPage) {
1222 d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
1227 if (!(tif & Qt::TextEditable)) {
1231 if (e->modifiers() & Qt::ShiftModifier)
1232 d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
1234 d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
1237 d->sendControlEvent(e);
1238 if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
1239 if (e->key() == Qt::Key_Home) {
1240 d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
1242 } else if (e->key() == Qt::Key_End) {
1243 d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
1247 if (!e->isAccepted()) {
1248 QAbstractScrollArea::keyPressEvent(e);
1253 #endif // QT_NO_SHORTCUT
1256 QTextCursor cursor = d->control->textCursor();
1257 const QString text = e->text();
1258 if (cursor.atBlockStart()
1259 && (d->autoFormatting & AutoBulletList)
1260 && (text.length() == 1)
1261 && (text.at(0) == QLatin1Char('-') || text.at(0) == QLatin1Char('*'))
1262 && (!cursor.currentList())) {
1264 d->createAutoBulletList();
1270 d->sendControlEvent(e);
1271 #ifdef QT_KEYPAD_NAVIGATION
1272 if (!e->isAccepted()) {
1276 if (QApplication::keypadNavigationEnabled()) {
1277 // Cursor position didn't change, so we want to leave
1278 // these keys to change focus.
1284 if (!e->isAutoRepeat()) {
1285 if (QApplication::keypadNavigationEnabled()) {
1286 if (document()->isEmpty() || !(d->control->textInteractionFlags() & Qt::TextEditable)) {
1287 setEditFocus(false);
1289 } else if (!d->deleteAllTimer.isActive()) {
1291 d->deleteAllTimer.start(750, this);
1307 void QTextEdit::keyReleaseEvent(QKeyEvent *e)
1309 #ifdef QT_KEYPAD_NAVIGATION
1311 if (QApplication::keypadNavigationEnabled()) {
1312 if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
1313 && d->deleteAllTimer.isActive()) {
1314 d->deleteAllTimer.stop();
1315 QTextCursor cursor = d->control->textCursor();
1316 QTextBlockFormat blockFmt = cursor.blockFormat();
1318 QTextList *list = cursor.currentList();
1319 if (list && cursor.atBlockStart()) {
1320 list->remove(cursor.block());
1321 } else if (cursor.atBlockStart() && blockFmt.indent() > 0) {
1322 blockFmt.setIndent(blockFmt.indent() - 1);
1323 cursor.setBlockFormat(blockFmt);
1325 cursor.deletePreviousChar();
1327 setTextCursor(cursor);
1337 Loads the resource specified by the given \a type and \a name.
1339 This function is an extension of QTextDocument::loadResource().
1341 \sa QTextDocument::loadResource()
1343 QVariant QTextEdit::loadResource(int type, const QUrl &name)
1352 void QTextEdit::resizeEvent(QResizeEvent *e)
1356 if (d->lineWrap == NoWrap) {
1357 QTextDocument *doc = d->control->document();
1358 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1360 if (!doc->pageSize().isNull()
1361 && alignmentProperty.type() == QVariant::Bool
1362 && !alignmentProperty.toBool()) {
1364 d->_q_adjustScrollbars();
1369 if (d->lineWrap != FixedPixelWidth
1370 && e->oldSize().width() != e->size().width())
1371 d->relayoutDocument();
1373 d->_q_adjustScrollbars();
1376 void QTextEditPrivate::relayoutDocument()
1378 QTextDocument *doc = control->document();
1379 QAbstractTextDocumentLayout *layout = doc->documentLayout();
1381 if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
1382 if (lineWrap == QTextEdit::FixedColumnWidth)
1383 tlayout->setFixedColumnWidth(lineWrapColumnOrWidth);
1385 tlayout->setFixedColumnWidth(-1);
1388 QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout);
1391 lastUsedSize = tlayout->dynamicDocumentSize().toSize();
1393 lastUsedSize = layout->documentSize().toSize();
1395 // ignore calls to _q_adjustScrollbars caused by an emission of the
1396 // usedSizeChanged() signal in the layout, as we're calling it
1397 // later on our own anyway (or deliberately not) .
1398 const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
1399 ignoreAutomaticScrollbarAdjustment = true;
1401 int width = viewport->width();
1402 if (lineWrap == QTextEdit::FixedPixelWidth)
1403 width = lineWrapColumnOrWidth;
1404 else if (lineWrap == QTextEdit::NoWrap) {
1405 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1406 if (alignmentProperty.type() == QVariant::Bool && !alignmentProperty.toBool()) {
1412 doc->setPageSize(QSize(width, -1));
1414 tlayout->ensureLayouted(verticalOffset() + viewport->height());
1416 ignoreAutomaticScrollbarAdjustment = oldIgnoreScrollbarAdjustment;
1420 usedSize = tlayout->dynamicDocumentSize().toSize();
1422 usedSize = layout->documentSize().toSize();
1424 // this is an obscure situation in the layout that can happen:
1425 // if a character at the end of a line is the tallest one and therefore
1426 // influencing the total height of the line and the line right below it
1427 // is always taller though, then it can happen that if due to line breaking
1428 // that tall character wraps into the lower line the document not only shrinks
1429 // horizontally (causing the character to wrap in the first place) but also
1430 // vertically, because the original line is now smaller and the one below kept
1431 // its size. So a layout with less width _can_ take up less vertical space, too.
1432 // If the wider case causes a vertical scroll bar to appear and the narrower one
1433 // (narrower because the vertical scroll bar takes up horizontal space)) to disappear
1434 // again then we have an endless loop, as _q_adjustScrollBars sets new ranges on the
1435 // scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
1436 // the scroll bars again. That's why we try to detect this case here and break out.
1438 // (if you change this please also check the layoutingLoop() testcase in
1439 // QTextEdit's autotests)
1440 if (lastUsedSize.isValid()
1441 && !vbar->isHidden()
1442 && viewport->width() < lastUsedSize.width()
1443 && usedSize.height() < lastUsedSize.height()
1444 && usedSize.height() <= viewport->height())
1447 _q_adjustScrollbars();
1450 void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
1452 const int xOffset = horizontalOffset();
1453 const int yOffset = verticalOffset();
1455 QRect r = e->rect();
1456 p->translate(-xOffset, -yOffset);
1457 r.translate(xOffset, yOffset);
1459 QTextDocument *doc = control->document();
1460 QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());
1462 // the layout might need to expand the root frame to
1463 // the viewport if NoWrap is set
1465 layout->setViewport(viewport->rect());
1467 control->drawContents(p, r, q_func());
1470 layout->setViewport(QRect());
1473 /*! \fn void QTextEdit::paintEvent(QPaintEvent *event)
1475 This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
1476 It is usually unnecessary to reimplement this function in a subclass of QTextEdit.
1478 \warning The underlying text document must not be modified from within a reimplementation
1481 void QTextEdit::paintEvent(QPaintEvent *e)
1484 QPainter p(d->viewport);
1488 void QTextEditPrivate::_q_currentCharFormatChanged(const QTextCharFormat &fmt)
1491 emit q->currentCharFormatChanged(fmt);
1494 void QTextEditPrivate::updateDefaultTextOption()
1496 QTextDocument *doc = control->document();
1498 QTextOption opt = doc->defaultTextOption();
1499 QTextOption::WrapMode oldWrapMode = opt.wrapMode();
1501 if (lineWrap == QTextEdit::NoWrap)
1502 opt.setWrapMode(QTextOption::NoWrap);
1504 opt.setWrapMode(wordWrap);
1506 if (opt.wrapMode() != oldWrapMode)
1507 doc->setDefaultTextOption(opt);
1512 void QTextEdit::mousePressEvent(QMouseEvent *e)
1515 #ifdef QT_KEYPAD_NAVIGATION
1516 if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
1519 d->sendControlEvent(e);
1524 void QTextEdit::mouseMoveEvent(QMouseEvent *e)
1527 d->inDrag = false; // paranoia
1528 const QPoint pos = e->pos();
1529 d->sendControlEvent(e);
1530 if (!(e->buttons() & Qt::LeftButton))
1532 QRect visible = d->viewport->rect();
1533 if (visible.contains(pos))
1534 d->autoScrollTimer.stop();
1535 else if (!d->autoScrollTimer.isActive())
1536 d->autoScrollTimer.start(100, this);
1541 void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
1544 d->sendControlEvent(e);
1545 if (d->autoScrollTimer.isActive()) {
1546 d->autoScrollTimer.stop();
1547 ensureCursorVisible();
1549 if (!isReadOnly() && rect().contains(e->pos()))
1550 d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
1551 d->clickCausedFocus = 0;
1556 void QTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
1559 d->sendControlEvent(e);
1564 bool QTextEdit::focusNextPrevChild(bool next)
1566 Q_D(const QTextEdit);
1567 if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
1569 return QAbstractScrollArea::focusNextPrevChild(next);
1572 #ifndef QT_NO_CONTEXTMENU
1574 \fn void QTextEdit::contextMenuEvent(QContextMenuEvent *event)
1576 Shows the standard context menu created with createStandardContextMenu().
1578 If you do not want the text edit to have a context menu, you can set
1579 its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
1580 customize the context menu, reimplement this function. If you want
1581 to extend the standard context menu, reimplement this function, call
1582 createStandardContextMenu() and extend the menu returned.
1584 Information about the event is passed in the \a event object.
1586 \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 0
1588 void QTextEdit::contextMenuEvent(QContextMenuEvent *e)
1591 d->sendControlEvent(e);
1593 #endif // QT_NO_CONTEXTMENU
1595 #ifndef QT_NO_DRAGANDDROP
1598 void QTextEdit::dragEnterEvent(QDragEnterEvent *e)
1602 d->sendControlEvent(e);
1607 void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
1611 d->autoScrollTimer.stop();
1612 d->sendControlEvent(e);
1617 void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
1620 d->autoScrollDragPos = e->pos();
1621 if (!d->autoScrollTimer.isActive())
1622 d->autoScrollTimer.start(100, this);
1623 d->sendControlEvent(e);
1628 void QTextEdit::dropEvent(QDropEvent *e)
1632 d->autoScrollTimer.stop();
1633 d->sendControlEvent(e);
1636 #endif // QT_NO_DRAGANDDROP
1640 void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
1643 #ifdef QT_KEYPAD_NAVIGATION
1644 if (d->control->textInteractionFlags() & Qt::TextEditable
1645 && QApplication::keypadNavigationEnabled()
1649 d->sendControlEvent(e);
1650 ensureCursorVisible();
1655 void QTextEdit::scrollContentsBy(int dx, int dy)
1658 if (isRightToLeft())
1660 d->viewport->scroll(dx, dy);
1665 QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
1667 Q_D(const QTextEdit);
1668 QVariant v = d->control->inputMethodQuery(property);
1669 const QPoint offset(-d->horizontalOffset(), -d->verticalOffset());
1670 if (v.type() == QVariant::RectF)
1671 v = v.toRectF().toRect().translated(offset);
1672 else if (v.type() == QVariant::PointF)
1673 v = v.toPointF().toPoint() + offset;
1674 else if (v.type() == QVariant::Rect)
1675 v = v.toRect().translated(offset);
1676 else if (v.type() == QVariant::Point)
1677 v = v.toPoint() + offset;
1683 void QTextEdit::focusInEvent(QFocusEvent *e)
1686 if (e->reason() == Qt::MouseFocusReason) {
1687 d->clickCausedFocus = 1;
1689 QAbstractScrollArea::focusInEvent(e);
1690 d->sendControlEvent(e);
1695 void QTextEdit::focusOutEvent(QFocusEvent *e)
1698 QAbstractScrollArea::focusOutEvent(e);
1699 d->sendControlEvent(e);
1704 void QTextEdit::showEvent(QShowEvent *)
1707 if (!d->anchorToScrollToWhenVisible.isEmpty()) {
1708 scrollToAnchor(d->anchorToScrollToWhenVisible);
1709 d->anchorToScrollToWhenVisible.clear();
1710 d->showCursorOnInitialShow = false;
1711 } else if (d->showCursorOnInitialShow) {
1712 d->showCursorOnInitialShow = false;
1713 ensureCursorVisible();
1719 void QTextEdit::changeEvent(QEvent *e)
1722 QAbstractScrollArea::changeEvent(e);
1723 if (e->type() == QEvent::ApplicationFontChange
1724 || e->type() == QEvent::FontChange) {
1725 d->control->document()->setDefaultFont(font());
1726 } else if(e->type() == QEvent::ActivationChange) {
1727 if (!isActiveWindow())
1728 d->autoScrollTimer.stop();
1729 } else if (e->type() == QEvent::EnabledChange) {
1730 e->setAccepted(isEnabled());
1731 d->control->setPalette(palette());
1732 d->sendControlEvent(e);
1733 } else if (e->type() == QEvent::PaletteChange) {
1734 d->control->setPalette(palette());
1735 } else if (e->type() == QEvent::LayoutDirectionChange) {
1736 d->sendControlEvent(e);
1742 #ifndef QT_NO_WHEELEVENT
1743 void QTextEdit::wheelEvent(QWheelEvent *e)
1746 if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
1747 if (e->modifiers() & Qt::ControlModifier) {
1748 const int delta = e->delta();
1756 QAbstractScrollArea::wheelEvent(e);
1761 #ifndef QT_NO_CONTEXTMENU
1762 /*! This function creates the standard context menu which is shown
1763 when the user clicks on the text edit with the right mouse
1764 button. It is called from the default contextMenuEvent() handler.
1765 The popup menu's ownership is transferred to the caller.
1767 We recommend that you use the createStandardContextMenu(QPoint) version instead
1768 which will enable the actions that are sensitive to where the user clicked.
1771 QMenu *QTextEdit::createStandardContextMenu()
1774 return d->control->createStandardContextMenu(QPointF(), this);
1779 This function creates the standard context menu which is shown
1780 when the user clicks on the text edit with the right mouse
1781 button. It is called from the default contextMenuEvent() handler
1782 and it takes the \a position of where the mouse click was.
1783 This can enable actions that are sensitive to the position where the user clicked.
1784 The popup menu's ownership is transferred to the caller.
1787 QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
1790 return d->control->createStandardContextMenu(position, this);
1792 #endif // QT_NO_CONTEXTMENU
1795 returns a QTextCursor at position \a pos (in viewport coordinates).
1797 QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
1799 Q_D(const QTextEdit);
1800 return d->control->cursorForPosition(d->mapToContents(pos));
1804 returns a rectangle (in viewport coordinates) that includes the
1807 QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
1809 Q_D(const QTextEdit);
1810 if (cursor.isNull())
1813 QRect r = d->control->cursorRect(cursor).toRect();
1814 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1819 returns a rectangle (in viewport coordinates) that includes the
1820 cursor of the text edit.
1822 QRect QTextEdit::cursorRect() const
1824 Q_D(const QTextEdit);
1825 QRect r = d->control->cursorRect().toRect();
1826 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1832 Returns the reference of the anchor at position \a pos, or an
1833 empty string if no anchor exists at that point.
1835 QString QTextEdit::anchorAt(const QPoint& pos) const
1837 Q_D(const QTextEdit);
1838 return d->control->anchorAt(d->mapToContents(pos));
1842 \property QTextEdit::overwriteMode
1844 \brief whether text entered by the user will overwrite existing text
1846 As with many text editors, the text editor widget can be configured
1847 to insert or overwrite existing text with new text entered by the user.
1849 If this property is true, existing text is overwritten, character-for-character
1850 by new text; otherwise, text is inserted at the cursor position, displacing
1853 By default, this property is false (new text does not overwrite existing text).
1856 bool QTextEdit::overwriteMode() const
1858 Q_D(const QTextEdit);
1859 return d->control->overwriteMode();
1862 void QTextEdit::setOverwriteMode(bool overwrite)
1865 d->control->setOverwriteMode(overwrite);
1869 \property QTextEdit::tabStopWidth
1870 \brief the tab stop width in pixels
1873 By default, this property contains a value of 80 pixels.
1876 int QTextEdit::tabStopWidth() const
1878 Q_D(const QTextEdit);
1879 return qRound(d->control->document()->defaultTextOption().tabStop());
1882 void QTextEdit::setTabStopWidth(int width)
1885 QTextOption opt = d->control->document()->defaultTextOption();
1886 if (opt.tabStop() == width || width < 0)
1888 opt.setTabStop(width);
1889 d->control->document()->setDefaultTextOption(opt);
1894 \property QTextEdit::cursorWidth
1896 This property specifies the width of the cursor in pixels. The default value is 1.
1898 int QTextEdit::cursorWidth() const
1900 Q_D(const QTextEdit);
1901 return d->control->cursorWidth();
1904 void QTextEdit::setCursorWidth(int width)
1907 d->control->setCursorWidth(width);
1911 \property QTextEdit::acceptRichText
1912 \brief whether the text edit accepts rich text insertions by the user
1915 When this propery is set to false text edit will accept only
1916 plain text input from the user. For example through clipboard or drag and drop.
1918 This property's default is true.
1921 bool QTextEdit::acceptRichText() const
1923 Q_D(const QTextEdit);
1924 return d->control->acceptRichText();
1927 void QTextEdit::setAcceptRichText(bool accept)
1930 d->control->setAcceptRichText(accept);
1934 \class QTextEdit::ExtraSelection
1938 \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
1939 character format for a given selection in a document
1943 \variable QTextEdit::ExtraSelection::cursor
1944 A cursor that contains a selection in a QTextDocument
1948 \variable QTextEdit::ExtraSelection::format
1949 A format that is used to specify a foreground or background brush/color
1955 This function allows temporarily marking certain regions in the document
1956 with a given color, specified as \a selections. This can be useful for
1957 example in a programming editor to mark a whole line of text with a given
1958 background color to indicate the existence of a breakpoint.
1960 \sa QTextEdit::ExtraSelection, extraSelections()
1962 void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
1965 d->control->setExtraSelections(selections);
1970 Returns previously set extra selections.
1972 \sa setExtraSelections()
1974 QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
1976 Q_D(const QTextEdit);
1977 return d->control->extraSelections();
1981 This function returns a new MIME data object to represent the contents
1982 of the text edit's current selection. It is called when the selection needs
1983 to be encapsulated into a new QMimeData object; for example, when a drag
1984 and drop operation is started, or when data is copyied to the clipboard.
1986 If you reimplement this function, note that the ownership of the returned
1987 QMimeData object is passed to the caller. The selection can be retrieved
1988 by using the textCursor() function.
1990 QMimeData *QTextEdit::createMimeDataFromSelection() const
1992 Q_D(const QTextEdit);
1993 return d->control->QWidgetTextControl::createMimeDataFromSelection();
1997 This function returns true if the contents of the MIME data object, specified
1998 by \a source, can be decoded and inserted into the document. It is called
1999 for example when during a drag operation the mouse enters this widget and it
2000 is necessary to determine whether it is possible to accept the drag and drop
2003 Reimplement this function to enable drag and drop support for additional MIME types.
2005 bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
2007 Q_D(const QTextEdit);
2008 return d->control->QWidgetTextControl::canInsertFromMimeData(source);
2012 This function inserts the contents of the MIME data object, specified
2013 by \a source, into the text edit at the current cursor position. It is
2014 called whenever text is inserted as the result of a clipboard paste
2015 operation, or when the text edit accepts data from a drag and drop
2018 Reimplement this function to enable drag and drop support for additional MIME types.
2020 void QTextEdit::insertFromMimeData(const QMimeData *source)
2023 d->control->QWidgetTextControl::insertFromMimeData(source);
2027 \property QTextEdit::readOnly
2028 \brief whether the text edit is read-only
2030 In a read-only text edit the user can only navigate through the
2031 text and select text; modifying the text is not possible.
2033 This property's default is false.
2036 bool QTextEdit::isReadOnly() const
2038 Q_D(const QTextEdit);
2039 return !(d->control->textInteractionFlags() & Qt::TextEditable);
2042 void QTextEdit::setReadOnly(bool ro)
2045 Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
2047 flags = Qt::TextSelectableByMouse;
2048 #ifndef QT_NO_TEXTBROWSER
2049 if (qobject_cast<QTextBrowser *>(this))
2050 flags |= Qt::TextBrowserInteraction;
2053 flags = Qt::TextEditorInteraction;
2055 d->control->setTextInteractionFlags(flags);
2056 setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
2060 \property QTextEdit::textInteractionFlags
2063 Specifies how the widget should interact with user input.
2065 The default value depends on whether the QTextEdit is read-only
2066 or editable, and whether it is a QTextBrowser or not.
2069 void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
2072 d->control->setTextInteractionFlags(flags);
2075 Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
2077 Q_D(const QTextEdit);
2078 return d->control->textInteractionFlags();
2082 Merges the properties specified in \a modifier into the current character
2083 format by calling QTextCursor::mergeCharFormat on the editor's cursor.
2084 If the editor has a selection then the properties of \a modifier are
2085 directly applied to the selection.
2087 \sa QTextCursor::mergeCharFormat()
2089 void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
2092 d->control->mergeCurrentCharFormat(modifier);
2096 Sets the char format that is be used when inserting new text to \a
2097 format by calling QTextCursor::setCharFormat() on the editor's
2098 cursor. If the editor has a selection then the char format is
2099 directly applied to the selection.
2101 void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
2104 d->control->setCurrentCharFormat(format);
2108 Returns the char format that is used when inserting new text.
2110 QTextCharFormat QTextEdit::currentCharFormat() const
2112 Q_D(const QTextEdit);
2113 return d->control->currentCharFormat();
2117 \property QTextEdit::autoFormatting
2118 \brief the enabled set of auto formatting features
2120 The value can be any combination of the values in the
2121 AutoFormattingFlag enum. The default is AutoNone. Choose
2122 AutoAll to enable all automatic formatting.
2124 Currently, the only automatic formatting feature provided is
2125 AutoBulletList; future versions of Qt may offer more.
2128 QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
2130 Q_D(const QTextEdit);
2131 return d->autoFormatting;
2134 void QTextEdit::setAutoFormatting(AutoFormatting features)
2137 d->autoFormatting = features;
2141 Convenience slot that inserts \a text at the current
2146 \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 1
2148 void QTextEdit::insertPlainText(const QString &text)
2151 d->control->insertPlainText(text);
2155 Convenience slot that inserts \a text which is assumed to be of
2156 html formatting at the current cursor position.
2158 It is equivalent to:
2160 \snippet doc/src/snippets/code/src_gui_widgets_qtextedit.cpp 2
2162 \note When using this function with a style sheet, the style sheet will
2163 only apply to the current block in the document. In order to apply a style
2164 sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
2167 #ifndef QT_NO_TEXTHTMLPARSER
2168 void QTextEdit::insertHtml(const QString &text)
2171 d->control->insertHtml(text);
2173 #endif // QT_NO_TEXTHTMLPARSER
2176 Scrolls the text edit so that the anchor with the given \a name is
2177 visible; does nothing if the \a name is empty, or is already
2178 visible, or isn't found.
2180 void QTextEdit::scrollToAnchor(const QString &name)
2187 d->anchorToScrollToWhenVisible = name;
2191 QPointF p = d->control->anchorPosition(name);
2192 const int newPosition = qRound(p.y());
2193 if ( d->vbar->maximum() < newPosition )
2194 d->_q_adjustScrollbars();
2195 d->vbar->setValue(newPosition);
2199 \fn QTextEdit::zoomIn(int range)
2201 Zooms in on the text by making the base font size \a range
2202 points larger and recalculating all font sizes to be the new size.
2203 This does not change the size of any images.
2207 void QTextEdit::zoomIn(int range)
2210 const int newSize = f.pointSize() + range;
2213 f.setPointSize(newSize);
2218 \fn QTextEdit::zoomOut(int range)
2222 Zooms out on the text by making the base font size \a range points
2223 smaller and recalculating all font sizes to be the new size. This
2224 does not change the size of any images.
2228 void QTextEdit::zoomOut(int range)
2235 Moves the cursor by performing the given \a operation.
2237 If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
2238 This is the same effect that the user achieves when they hold down the Shift key
2239 and move the cursor with the cursor keys.
2241 \sa QTextCursor::movePosition()
2243 void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
2246 d->control->moveCursor(operation, mode);
2251 Returns whether text can be pasted from the clipboard into the textedit.
2253 bool QTextEdit::canPaste() const
2255 Q_D(const QTextEdit);
2256 return d->control->canPaste();
2261 Convenience function to print the text edit's document to the given \a printer. This
2262 is equivalent to calling the print method on the document directly except that this
2263 function also supports QPrinter::Selection as print range.
2265 \sa QTextDocument::print()
2267 #ifndef QT_NO_PRINTER
2268 void QTextEdit::print(QPagedPaintDevice *printer) const
2270 Q_D(const QTextEdit);
2271 d->control->print(printer);
2275 /*! \property QTextEdit::tabChangesFocus
2276 \brief whether \gui Tab changes focus or is accepted as input
2278 In some occasions text edits should not allow the user to input
2279 tabulators or change indentation using the \gui Tab key, as this breaks
2280 the focus chain. The default is false.
2284 bool QTextEdit::tabChangesFocus() const
2286 Q_D(const QTextEdit);
2287 return d->tabChangesFocus;
2290 void QTextEdit::setTabChangesFocus(bool b)
2293 d->tabChangesFocus = b;
2297 \property QTextEdit::documentTitle
2298 \brief the title of the document parsed from the text.
2300 By default, for a newly-created, empty document, this property contains
2305 \property QTextEdit::lineWrapMode
2306 \brief the line wrap mode
2308 The default mode is WidgetWidth which causes words to be
2309 wrapped at the right edge of the text edit. Wrapping occurs at
2310 whitespace, keeping whole words intact. If you want wrapping to
2311 occur within words use setWordWrapMode(). If you set a wrap mode of
2312 FixedPixelWidth or FixedColumnWidth you should also call
2313 setLineWrapColumnOrWidth() with the width you want.
2315 \sa lineWrapColumnOrWidth
2318 QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
2320 Q_D(const QTextEdit);
2324 void QTextEdit::setLineWrapMode(LineWrapMode wrap)
2327 if (d->lineWrap == wrap)
2330 d->updateDefaultTextOption();
2331 d->relayoutDocument();
2335 \property QTextEdit::lineWrapColumnOrWidth
2336 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
2338 If the wrap mode is FixedPixelWidth, the value is the number of
2339 pixels from the left edge of the text edit at which text should be
2340 wrapped. If the wrap mode is FixedColumnWidth, the value is the
2341 column number (in character columns) from the left edge of the
2342 text edit at which text should be wrapped.
2344 By default, this property contains a value of 0.
2349 int QTextEdit::lineWrapColumnOrWidth() const
2351 Q_D(const QTextEdit);
2352 return d->lineWrapColumnOrWidth;
2355 void QTextEdit::setLineWrapColumnOrWidth(int w)
2358 d->lineWrapColumnOrWidth = w;
2359 d->relayoutDocument();
2363 \property QTextEdit::wordWrapMode
2364 \brief the mode QTextEdit will use when wrapping text by words
2366 By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
2368 \sa QTextOption::WrapMode
2371 QTextOption::WrapMode QTextEdit::wordWrapMode() const
2373 Q_D(const QTextEdit);
2377 void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
2380 if (mode == d->wordWrap)
2383 d->updateDefaultTextOption();
2387 Finds the next occurrence of the string, \a exp, using the given
2388 \a options. Returns true if \a exp was found and changes the
2389 cursor to select the match; otherwise returns false.
2391 bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
2394 return d->control->find(exp, options);
2398 \fn void QTextEdit::copyAvailable(bool yes)
2400 This signal is emitted when text is selected or de-selected in the
2403 When text is selected this signal will be emitted with \a yes set
2404 to true. If no text has been selected or if the selected text is
2405 de-selected this signal is emitted with \a yes set to false.
2407 If \a yes is true then copy() can be used to copy the selection to
2408 the clipboard. If \a yes is false then copy() does nothing.
2410 \sa selectionChanged()
2414 \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)
2416 This signal is emitted if the current character format has changed, for
2417 example caused by a change of the cursor position.
2419 The new format is \a f.
2421 \sa setCurrentCharFormat()
2425 \fn void QTextEdit::selectionChanged()
2427 This signal is emitted whenever the selection changes.
2433 \fn void QTextEdit::cursorPositionChanged()
2435 This signal is emitted whenever the position of the
2442 Sets the text edit's \a text. The text can be plain text or HTML
2443 and the text edit will try to guess the right format.
2445 Use setHtml() or setPlainText() directly to avoid text edit's guessing.
2447 \sa toPlainText(), toHtml()
2449 void QTextEdit::setText(const QString &text)
2452 Qt::TextFormat format = d->textFormat;
2453 if (d->textFormat == Qt::AutoText)
2454 format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
2455 #ifndef QT_NO_TEXTHTMLPARSER
2456 if (format == Qt::RichText || format == Qt::LogText)
2465 Appends a new paragraph with \a text to the end of the text edit.
2467 \note The new paragraph appended will have the same character format and
2468 block format as the current paragraph, determined by the position of the cursor.
2470 \sa currentCharFormat(), QTextCursor::blockFormat()
2473 void QTextEdit::append(const QString &text)
2476 const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() :
2477 d->control->textCursor().atEnd();
2478 d->control->append(text);
2480 d->vbar->setValue(d->vbar->maximum());
2484 Ensures that the cursor is visible by scrolling the text edit if
2487 void QTextEdit::ensureCursorVisible()
2490 d->control->ensureCursorVisible();
2494 \enum QTextEdit::KeyboardAction
2498 \value ActionBackspace
2502 \value ActionWordBackspace
2503 \value ActionWordDelete
2507 \fn bool QTextEdit::find(const QString &exp, bool cs, bool wo)
2509 Use the find() overload that takes a QTextDocument::FindFlags
2514 \fn void QTextEdit::sync()
2520 \fn void QTextEdit::setBold(bool b)
2522 Use setFontWeight() instead.
2526 \fn void QTextEdit::setUnderline(bool b)
2528 Use setFontUnderline() instead.
2532 \fn void QTextEdit::setItalic(bool i)
2534 Use setFontItalic() instead.
2538 \fn void QTextEdit::setFamily(const QString &family)
2540 Use setFontFamily() instead.
2544 \fn void QTextEdit::setPointSize(int size)
2546 Use setFontPointSize() instead.
2550 \fn bool QTextEdit::italic() const
2552 Use fontItalic() instead.
2556 \fn bool QTextEdit::bold() const
2558 Use fontWeight() >= QFont::Bold instead.
2562 \fn bool QTextEdit::underline() const
2564 Use fontUnderline() instead.
2568 \fn QString QTextEdit::family() const
2570 Use fontFamily() instead.
2574 \fn int QTextEdit::pointSize() const
2576 Use int(fontPointSize()+0.5) instead.
2580 \fn bool QTextEdit::hasSelectedText() const
2582 Use textCursor().hasSelection() instead.
2586 \fn QString QTextEdit::selectedText() const
2588 Use textCursor().selectedText() instead.
2592 \fn bool QTextEdit::isUndoAvailable() const
2594 Use document()->isUndoAvailable() instead.
2598 \fn bool QTextEdit::isRedoAvailable() const
2600 Use document()->isRedoAvailable() instead.
2604 \fn void QTextEdit::insert(const QString &text)
2606 Use insertPlainText() instead.
2610 \fn bool QTextEdit::isModified() const
2612 Use document()->isModified() instead.
2616 \fn QColor QTextEdit::color() const
2618 Use textColor() instead.
2622 \fn void QTextEdit::textChanged()
2624 This signal is emitted whenever the document's content changes; for
2625 example, when text is inserted or deleted, or when formatting is applied.
2629 \fn void QTextEdit::undoAvailable(bool available)
2631 This signal is emitted whenever undo operations become available
2632 (\a available is true) or unavailable (\a available is false).
2636 \fn void QTextEdit::redoAvailable(bool available)
2638 This signal is emitted whenever redo operations become available
2639 (\a available is true) or unavailable (\a available is false).
2643 \fn void QTextEdit::currentFontChanged(const QFont &font)
2645 Use currentCharFormatChanged() instead.
2649 \fn void QTextEdit::currentColorChanged(const QColor &color)
2651 Use currentCharFormatChanged() instead.
2655 \fn void QTextEdit::setModified(bool m)
2657 Use document->setModified() instead.
2661 \fn void QTextEdit::setColor(const QColor &color)
2663 Use setTextColor() instead.
2665 #endif // QT_NO_TEXTEDIT
2669 #include "moc_qtextedit.cpp"