Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtextedit.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qtextedit_p.h"
6#if QT_CONFIG(lineedit)
7#include "qlineedit.h"
8#endif
9#if QT_CONFIG(textbrowser)
10#include "qtextbrowser.h"
11#endif
12
13#include <qfont.h>
14#include <qpainter.h>
15#include <qevent.h>
16#include <qdebug.h>
17#if QT_CONFIG(draganddrop)
18#include <qdrag.h>
19#endif
20#include <qclipboard.h>
21#if QT_CONFIG(menu)
22#include <qmenu.h>
23#endif
24#include <qstyle.h>
25#if QT_CONFIG(accessibility)
26#include <qaccessible.h>
27#endif
28#include "private/qtextdocumentlayout_p.h"
29#include "qtextdocument.h"
30#include "private/qtextdocument_p.h"
31#include "qtextlist.h"
32#include "private/qwidgettextcontrol_p.h"
33
34#include <qtextformat.h>
35#include <qdatetime.h>
36#include <qapplication.h>
37#include <private/qapplication_p.h>
38#include <limits.h>
39#include <qtextobject.h>
40#include <qtexttable.h>
41#include <qvariant.h>
42
44
45static inline bool shouldEnableInputMethod(QTextEdit *textedit)
46{
47#if defined (Q_OS_ANDROID)
48 return !textedit->isReadOnly() || (textedit->textInteractionFlags() & Qt::TextSelectableByMouse);
49#else
50 return !textedit->isReadOnly();
51#endif
52}
53
55{
56public:
57 inline QTextEditControl(QObject *parent) : QWidgetTextControl(parent) {}
58
59 virtual QMimeData *createMimeDataFromSelection() const override {
60 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
61 if (!ed)
62 return QWidgetTextControl::createMimeDataFromSelection();
63 return ed->createMimeDataFromSelection();
64 }
65 virtual bool canInsertFromMimeData(const QMimeData *source) const override {
66 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
67 if (!ed)
68 return QWidgetTextControl::canInsertFromMimeData(source);
69 return ed->canInsertFromMimeData(source);
70 }
71 virtual void insertFromMimeData(const QMimeData *source) override {
72 QTextEdit *ed = qobject_cast<QTextEdit *>(parent());
73 if (!ed)
74 QWidgetTextControl::insertFromMimeData(source);
75 else
76 ed->insertFromMimeData(source);
77 }
78 QVariant loadResource(int type, const QUrl &name) override {
79 auto *ed = qobject_cast<QTextEdit *>(parent());
80 if (!ed)
81 return QWidgetTextControl::loadResource(type, name);
82
83 QUrl resolvedName = ed->d_func()->resolveUrl(name);
84 return ed->loadResource(type, resolvedName);
85 }
86};
87
88QTextEditPrivate::QTextEditPrivate()
89 : control(nullptr),
90 autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),
91 lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),
92 wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), clickCausedFocus(0)
93{
94 ignoreAutomaticScrollbarAdjustment = false;
95 preferRichText = false;
96 showCursorOnInitialShow = true;
97 inDrag = false;
98}
99
101{
102 for (QMetaObject::Connection &connection : connections)
103 QObject::disconnect(connection);
104}
105
107{
108 QTextCursor cursor = control->textCursor();
109 cursor.beginEditBlock();
110
111 QTextBlockFormat blockFmt = cursor.blockFormat();
112
113 QTextListFormat listFmt;
114 listFmt.setStyle(QTextListFormat::ListDisc);
115 listFmt.setIndent(blockFmt.indent() + 1);
116
117 blockFmt.setIndent(0);
118 cursor.setBlockFormat(blockFmt);
119
120 cursor.createList(listFmt);
121
122 cursor.endEditBlock();
123 control->setTextCursor(cursor);
124}
125
126void QTextEditPrivate::init(const QString &html)
127{
128 Q_Q(QTextEdit);
129 control = new QTextEditControl(q);
130 control->setPalette(q->palette());
131
132 connections = {
133 QObjectPrivate::connect(control, &QTextEditControl::documentSizeChanged,
134 this, &QTextEditPrivate::adjustScrollbars),
135 QObjectPrivate::connect(control, &QTextEditControl::updateRequest,
136 this, &QTextEditPrivate::repaintContents),
137 QObjectPrivate::connect(control, &QTextEditControl::visibilityRequest,
138 this, &QTextEditPrivate::ensureVisible),
139 QObjectPrivate::connect(control, &QTextEditControl::blockMarkerHovered,
140 this, &QTextEditPrivate::hoveredBlockWithMarkerChanged),
141 QObjectPrivate::connect(control, &QTextEditControl::cursorPositionChanged,
142 this, &QTextEditPrivate::cursorPositionChanged),
143 QObject::connect(control, &QTextEditControl::microFocusChanged,
144 q, [q]() { q->updateMicroFocus(); }),
145 QObject::connect(control, &QTextEditControl::currentCharFormatChanged,
146 q, &QTextEdit::currentCharFormatChanged),
147 QObject::connect(control, &QTextEditControl::textChanged,
148 q, &QTextEdit::textChanged),
149 QObject::connect(control, &QTextEditControl::undoAvailable,
150 q, &QTextEdit::undoAvailable),
151 QObject::connect(control, &QTextEditControl::redoAvailable,
152 q, &QTextEdit::redoAvailable),
153 QObject::connect(control, &QTextEditControl::copyAvailable,
154 q, &QTextEdit::copyAvailable),
155 QObject::connect(control, &QTextEditControl::selectionChanged,
156 q, &QTextEdit::selectionChanged),
157 QObject::connect(control, &QTextEditControl::textChanged,
158 q, [q]() { q->updateMicroFocus(); }),
159 };
160
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);
170
171 if (!html.isEmpty())
172 control->setHtml(html);
173
174 const auto singleStep = defaultSingleStep();
175 hbar->setSingleStep(singleStep);
176 vbar->setSingleStep(singleStep);
177
178 viewport->setBackgroundRole(QPalette::Base);
179 q->setMouseTracking(true);
180 q->setAcceptDrops(true);
181 q->setFocusPolicy(Qt::StrongFocus);
182 q->setAttribute(Qt::WA_KeyCompression);
183 q->setAttribute(Qt::WA_InputMethodEnabled);
184 q->setInputMethodHints(Qt::ImhMultiLine);
185#ifndef QT_NO_CURSOR
186 viewport->setCursor(Qt::IBeamCursor);
187#endif
188}
189
190void QTextEditPrivate::repaintContents(const QRectF &contentsRect)
191{
192 if (!contentsRect.isValid()) {
193 viewport->update();
194 return;
195 }
196 const int xOffset = horizontalOffset();
197 const int yOffset = verticalOffset();
198 const QRectF visibleRect(xOffset, yOffset, viewport->width(), viewport->height());
199
200 QRect r = contentsRect.intersected(visibleRect).toAlignedRect();
201 if (r.isEmpty())
202 return;
203
204 r.translate(-xOffset, -yOffset);
205 viewport->update(r);
206}
207
209{
210 Q_Q(QTextEdit);
211 emit q->cursorPositionChanged();
212#if QT_CONFIG(accessibility)
213 QAccessibleTextCursorEvent event(q, q->textCursor().position());
214 QAccessible::updateAccessibility(&event);
215#endif
216}
217
218void QTextEditPrivate::hoveredBlockWithMarkerChanged(const QTextBlock &block)
219{
220#if QT_CONFIG(cursor)
221 Q_Q(QTextEdit);
222 Qt::CursorShape cursor = cursorToRestoreAfterHover;
223 if (block.isValid() && !q->isReadOnly()) {
224 QTextBlockFormat::MarkerType marker = block.blockFormat().marker();
225 if (marker != QTextBlockFormat::MarkerType::NoMarker) {
226 if (viewport->cursor().shape() != Qt::PointingHandCursor)
227 cursorToRestoreAfterHover = viewport->cursor().shape();
228 cursor = Qt::PointingHandCursor;
229 }
230 }
231 viewport->setCursor(cursor);
232#endif
233}
234
235void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
236{
237 QTextCursor cursor = control->textCursor();
238 bool moved = false;
239 qreal lastY = control->cursorRect(cursor).top();
240 qreal distance = 0;
241 // move using movePosition to keep the cursor's x
242 do {
243 qreal y = control->cursorRect(cursor).top();
244 distance += qAbs(y - lastY);
245 lastY = y;
246 moved = cursor.movePosition(op, moveMode);
247 } while (moved && distance < viewport->height());
248
249 if (moved) {
250 if (op == QTextCursor::Up) {
251 cursor.movePosition(QTextCursor::Down, moveMode);
252 vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
253 } else {
254 cursor.movePosition(QTextCursor::Up, moveMode);
255 vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
256 }
257 }
258 control->setTextCursor(cursor, moveMode == QTextCursor::KeepAnchor);
259}
260
261#if QT_CONFIG(scrollbar)
262static QSize documentSize(QWidgetTextControl *control)
263{
264 QTextDocument *doc = control->document();
265 QAbstractTextDocumentLayout *layout = doc->documentLayout();
266
267 QSize docSize;
268
269 if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
270 docSize = tlayout->dynamicDocumentSize().toSize();
271 int percentageDone = tlayout->layoutStatus();
272 // extrapolate height
273 if (percentageDone > 0)
274 docSize.setHeight(docSize.height() * 100 / percentageDone);
275 } else {
276 docSize = layout->documentSize().toSize();
277 }
278
279 return docSize;
280}
281
282void QTextEditPrivate::adjustScrollbars()
283{
284 if (ignoreAutomaticScrollbarAdjustment)
285 return;
286 ignoreAutomaticScrollbarAdjustment = true; // avoid recursion, #106108
287
288 QSize viewportSize = viewport->size();
289 QSize docSize = documentSize(control);
290
291 // due to the recursion guard we have to repeat this step a few times,
292 // as adding/removing a scroll bar will cause the document or viewport
293 // size to change
294 // ideally we should loop until the viewport size and doc size stabilize,
295 // but in corner cases they might fluctuate, so we need to limit the
296 // number of iterations
297 for (int i = 0; i < 4; ++i) {
298 hbar->setRange(0, docSize.width() - viewportSize.width());
299 hbar->setPageStep(viewportSize.width());
300
301 vbar->setRange(0, docSize.height() - viewportSize.height());
302 vbar->setPageStep(viewportSize.height());
303
304 // if we are in left-to-right mode widening the document due to
305 // lazy layouting does not require a repaint. If in right-to-left
306 // the scroll bar has the value zero and it visually has the maximum
307 // value (it is visually at the right), then widening the document
308 // keeps it at value zero but visually adjusts it to the new maximum
309 // on the right, hence we need an update.
310 if (q_func()->isRightToLeft())
311 viewport->update();
312
313 _q_showOrHideScrollBars();
314
315 const QSize oldViewportSize = viewportSize;
316 const QSize oldDocSize = docSize;
317
318 // make sure the document is layouted if the viewport width changes
319 viewportSize = viewport->size();
320 if (viewportSize.width() != oldViewportSize.width())
321 relayoutDocument();
322
323 docSize = documentSize(control);
324 if (viewportSize == oldViewportSize && docSize == oldDocSize)
325 break;
326 }
327 ignoreAutomaticScrollbarAdjustment = false;
328}
329#endif
330
331// rect is in content coordinates
332void QTextEditPrivate::ensureVisible(const QRectF &_rect)
333{
334 const QRect rect = _rect.toRect();
335 if ((vbar->isVisible() && vbar->maximum() < rect.bottom())
336 || (hbar->isVisible() && hbar->maximum() < rect.right()))
338 const int visibleWidth = viewport->width();
339 const int visibleHeight = viewport->height();
340 const bool rtl = q_func()->isRightToLeft();
341
342 if (rect.x() < horizontalOffset()) {
343 if (rtl)
344 hbar->setValue(hbar->maximum() - rect.x());
345 else
346 hbar->setValue(rect.x());
347 } else if (rect.x() + rect.width() > horizontalOffset() + visibleWidth) {
348 if (rtl)
349 hbar->setValue(hbar->maximum() - (rect.x() + rect.width() - visibleWidth));
350 else
351 hbar->setValue(rect.x() + rect.width() - visibleWidth);
352 }
353
354 if (rect.y() < verticalOffset())
355 vbar->setValue(rect.y());
356 else if (rect.y() + rect.height() > verticalOffset() + visibleHeight)
357 vbar->setValue(rect.y() + rect.height() - visibleHeight);
358}
359
360/*!
361 \class QTextEdit
362 \brief The QTextEdit class provides a widget that is used to edit and display
363 both plain and rich text.
364
365 \ingroup richtext-processing
366 \inmodule QtWidgets
367
368 \section1 Introduction and Concepts
369
370 QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
371 text formatting using HTML-style tags, or Markdown format. It is optimized
372 to handle large documents and to respond quickly to user input.
373
374 QTextEdit works on paragraphs and characters. A paragraph is a
375 formatted string which is word-wrapped to fit into the width of
376 the widget. By default when reading plain text, one newline
377 signifies a paragraph. A document consists of zero or more
378 paragraphs. The words in the paragraph are aligned in accordance
379 with the paragraph's alignment. Paragraphs are separated by hard
380 line breaks. Each character within a paragraph has its own
381 attributes, for example, font and color.
382
383 QTextEdit can display images, lists and tables. If the text is
384 too large to view within the text edit's viewport, scroll bars will
385 appear. The text edit can load both plain text and rich text files.
386 Rich text can be described using a subset of HTML 4 markup; refer to the
387 \l {Supported HTML Subset} page for more information.
388
389 If you just need to display a small piece of rich text use QLabel.
390
391 The rich text support in Qt is designed to provide a fast, portable and
392 efficient way to add reasonable online help facilities to
393 applications, and to provide a basis for rich text editors. If
394 you find the HTML support insufficient for your needs you may consider
395 the use of Qt WebKit, which provides a full-featured web browser
396 widget.
397
398 The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default.
399 It can be changed through the viewport()'s cursor property.
400
401 \section1 Using QTextEdit as a Display Widget
402
403 QTextEdit can display a large HTML subset, including tables and
404 images.
405
406 The text can be set or replaced using \l setHtml() which deletes any
407 existing text and replaces it with the text passed in the
408 setHtml() call. If you call setHtml() with legacy HTML, and then
409 call toHtml(), the text that is returned may have different markup,
410 but will render the same. The entire text can be deleted with clear().
411
412 Text can also be set or replaced using \l setMarkdown(), and the same
413 caveats apply: if you then call \l toMarkdown(), the text that is returned
414 may be different, but the meaning is preserved as much as possible.
415 Markdown with some embedded HTML can be parsed, with the same limitations
416 that \l setHtml() has; but \l toMarkdown() only writes "pure" Markdown,
417 without any embedded HTML.
418
419 Text itself can be inserted using the QTextCursor class or using the
420 convenience functions insertHtml(), insertPlainText(), append() or
421 paste(). QTextCursor is also able to insert complex objects like tables
422 or lists into the document, and it deals with creating selections
423 and applying changes to selected text.
424
425 By default the text edit wraps words at whitespace to fit within
426 the text edit widget. The setLineWrapMode() function is used to
427 specify the kind of line wrap you want, or \l NoWrap if you don't
428 want any wrapping. Call setLineWrapMode() to set a fixed pixel width
429 \l FixedPixelWidth, or character column (e.g. 80 column) \l
430 FixedColumnWidth with the pixels or columns specified with
431 setLineWrapColumnOrWidth(). If you use word wrap to the widget's width
432 \l WidgetWidth, you can specify whether to break on whitespace or
433 anywhere with setWordWrapMode().
434
435 The find() function can be used to find and select a given string
436 within the text.
437
438 If you want to limit the total number of paragraphs in a QTextEdit,
439 as for example it is often useful in a log viewer, then you can use
440 QTextDocument's maximumBlockCount property for that.
441
442 \section2 Read-only Key Bindings
443
444 When QTextEdit is used read-only the key bindings are limited to
445 navigation, and text may only be selected with the mouse:
446 \table
447 \header \li Keypresses \li Action
448 \row \li Up \li Moves one line up.
449 \row \li Down \li Moves one line down.
450 \row \li Left \li Moves one character to the left.
451 \row \li Right \li Moves one character to the right.
452 \row \li PageUp \li Moves one (viewport) page up.
453 \row \li PageDown \li Moves one (viewport) page down.
454 \row \li Home \li Moves to the beginning of the text.
455 \row \li End \li Moves to the end of the text.
456 \row \li Alt+Wheel
457 \li Scrolls the page horizontally (the Wheel is the mouse wheel).
458 \row \li Ctrl+Wheel \li Zooms the text.
459 \row \li Ctrl+A \li Selects all text.
460 \endtable
461
462 The text edit may be able to provide some meta-information. For
463 example, the documentTitle() function will return the text from
464 within HTML \c{<title>} tags.
465
466 \note Zooming into HTML documents only works if the font-size is not set to a fixed size.
467
468 \section1 Using QTextEdit as an Editor
469
470 All the information about using QTextEdit as a display widget also
471 applies here.
472
473 The current char format's attributes are set with setFontItalic(),
474 setFontWeight(), setFontUnderline(), setFontFamily(),
475 setFontPointSize(), setTextColor() and setCurrentFont(). The current
476 paragraph's alignment is set with setAlignment().
477
478 Selection of text is handled by the QTextCursor class, which provides
479 functionality for creating selections, retrieving the text contents or
480 deleting selections. You can retrieve the object that corresponds with
481 the user-visible cursor using the textCursor() method. If you want to set
482 a selection in QTextEdit just create one on a QTextCursor object and
483 then make that cursor the visible cursor using setTextCursor(). The selection
484 can be copied to the clipboard with copy(), or cut to the clipboard with
485 cut(). The entire text can be selected using selectAll().
486
487 When the cursor is moved and the underlying formatting attributes change,
488 the currentCharFormatChanged() signal is emitted to reflect the new attributes
489 at the new cursor position.
490
491 The textChanged() signal is emitted whenever the text changes (as a result
492 of setText() or through the editor itself).
493
494 QTextEdit holds a QTextDocument object which can be retrieved using the
495 document() method. You can also set your own document object using setDocument().
496
497 QTextDocument provides an \l {QTextDocument::isModified()}{isModified()}
498 function which will return true if the text has been modified since it was
499 either loaded or since the last call to \l {QTextDocument::}{setModified()}
500 with false as argument.
501 In addition it provides methods for undo and redo.
502
503 \section2 Drag and Drop
504
505 QTextEdit also supports custom drag and drop behavior. By default,
506 QTextEdit will insert plain text, HTML and rich text when the user drops
507 data of these MIME types onto a document. Reimplement
508 canInsertFromMimeData() and insertFromMimeData() to add support for
509 additional MIME types.
510
511 For example, to allow the user to drag and drop an image onto a QTextEdit,
512 you could the implement these functions in the following way:
513
514 \snippet textdocument-imagedrop/textedit.cpp 0
515
516 We add support for image MIME types by returning true. For all other
517 MIME types, we use the default implementation.
518
519 \snippet textdocument-imagedrop/textedit.cpp 1
520
521 We unpack the image from the QVariant held by the MIME source and insert
522 it into the document as a resource.
523
524 \section2 Editing Key Bindings
525
526 The list of key bindings which are implemented for editing:
527 \table
528 \header \li Keypresses \li Action
529 \row \li Backspace \li Deletes the character to the left of the cursor.
530 \row \li Delete \li Deletes the character to the right of the cursor.
531 \row \li Ctrl+C \li Copy the selected text to the clipboard.
532 \row \li Ctrl+Insert \li Copy the selected text to the clipboard.
533 \row \li Ctrl+K \li Deletes to the end of the line.
534 \row \li Ctrl+V \li Pastes the clipboard text into text edit.
535 \row \li Shift+Insert \li Pastes the clipboard text into text edit.
536 \row \li Ctrl+X \li Deletes the selected text and copies it to the clipboard.
537 \row \li Shift+Delete \li Deletes the selected text and copies it to the clipboard.
538 \row \li Ctrl+Z \li Undoes the last operation.
539 \row \li Ctrl+Y \li Redoes the last operation.
540 \row \li Left \li Moves the cursor one character to the left.
541 \row \li Ctrl+Left \li Moves the cursor one word to the left.
542 \row \li Right \li Moves the cursor one character to the right.
543 \row \li Ctrl+Right \li Moves the cursor one word to the right.
544 \row \li Up \li Moves the cursor one line up.
545 \row \li Down \li Moves the cursor one line down.
546 \row \li PageUp \li Moves the cursor one page up.
547 \row \li PageDown \li Moves the cursor one page down.
548 \row \li Home \li Moves the cursor to the beginning of the line.
549 \row \li Ctrl+Home \li Moves the cursor to the beginning of the text.
550 \row \li End \li Moves the cursor to the end of the line.
551 \row \li Ctrl+End \li Moves the cursor to the end of the text.
552 \row \li Alt+Wheel \li Scrolls the page horizontally (the Wheel is the mouse wheel).
553 \endtable
554
555 To select (mark) text hold down the Shift key whilst pressing one
556 of the movement keystrokes, for example, \e{Shift+Right}
557 will select the character to the right, and \e{Shift+Ctrl+Right} will select the word to the right, etc.
558
559 \sa QTextDocument, QTextCursor,
560 {Syntax Highlighter Example}, {Rich Text Processing}
561*/
562
563/*!
564 \property QTextEdit::plainText
565 \since 4.3
566
567 \brief the text editor's contents as plain text.
568
569 Previous contents are removed and undo/redo history is reset
570 when the property is set. currentCharFormat() is also reset, unless
571 textCursor() is already at the beginning of the document.
572
573 If the text edit has another content type, it will not be replaced
574 by plain text if you call toPlainText(). The only exception to this
575 is the non-break space, \e{nbsp;}, that will be converted into
576 standard space.
577
578 By default, for an editor with no contents, this property contains
579 an empty string.
580
581 \sa html
582*/
583
584/*!
585 \property QTextEdit::undoRedoEnabled
586 \brief whether undo and redo are enabled.
587
588 Users are only able to undo or redo actions if this property is
589 true, and if there is an action that can be undone (or redone).
590*/
591
592/*!
593 \enum QTextEdit::LineWrapMode
594
595 \value NoWrap
596 \value WidgetWidth
597 \value FixedPixelWidth
598 \value FixedColumnWidth
599*/
600
601/*!
602 \enum QTextEdit::AutoFormattingFlag
603
604 \value AutoNone Don't do any automatic formatting.
605 \value AutoBulletList Automatically create bullet lists (e.g. when
606 the user enters an asterisk ('*') in the left most column, or
607 presses Enter in an existing list item.
608 \value AutoAll Apply all automatic formatting. Currently only
609 automatic bullet lists are supported.
610*/
611
612
613/*!
614 Constructs an empty QTextEdit with parent \a
615 parent.
616*/
617QTextEdit::QTextEdit(QWidget *parent)
618 : QAbstractScrollArea(*new QTextEditPrivate, parent)
619{
620 Q_D(QTextEdit);
621 d->init();
622}
623
624/*!
625 \internal
626*/
627QTextEdit::QTextEdit(QTextEditPrivate &dd, QWidget *parent)
628 : QAbstractScrollArea(dd, parent)
629{
630 Q_D(QTextEdit);
631 d->init();
632}
633
634/*!
635 Constructs a QTextEdit with parent \a parent. The text edit will display
636 the text \a text. The text is interpreted as html.
637*/
638QTextEdit::QTextEdit(const QString &text, QWidget *parent)
639 : QAbstractScrollArea(*new QTextEditPrivate, parent)
640{
641 Q_D(QTextEdit);
642 d->init(text);
643}
644
645
646
647/*!
648 Destructor.
649*/
650QTextEdit::~QTextEdit()
651{
652}
653
654/*!
655 Returns the point size of the font of the current format.
656
657 \sa setFontFamily(), setCurrentFont(), setFontPointSize()
658*/
659qreal QTextEdit::fontPointSize() const
660{
661 Q_D(const QTextEdit);
662 return d->control->textCursor().charFormat().fontPointSize();
663}
664
665/*!
666 Returns the font family of the current format.
667
668 \sa setFontFamily(), setCurrentFont(), setFontPointSize()
669*/
670QString QTextEdit::fontFamily() const
671{
672 Q_D(const QTextEdit);
673 return d->control->textCursor().charFormat().fontFamilies().toStringList().value(0, QString());
674}
675
676/*!
677 Returns the font weight of the current format.
678
679 \sa setFontWeight(), setCurrentFont(), setFontPointSize(), QFont::Weight
680*/
681int QTextEdit::fontWeight() const
682{
683 Q_D(const QTextEdit);
684 return d->control->textCursor().charFormat().fontWeight();
685}
686
687/*!
688 Returns \c true if the font of the current format is underlined; otherwise returns
689 false.
690
691 \sa setFontUnderline()
692*/
693bool QTextEdit::fontUnderline() const
694{
695 Q_D(const QTextEdit);
696 return d->control->textCursor().charFormat().fontUnderline();
697}
698
699/*!
700 Returns \c true if the font of the current format is italic; otherwise returns
701 false.
702
703 \sa setFontItalic()
704*/
705bool QTextEdit::fontItalic() const
706{
707 Q_D(const QTextEdit);
708 return d->control->textCursor().charFormat().fontItalic();
709}
710
711/*!
712 Returns the text color of the current format.
713
714 \sa setTextColor()
715*/
716QColor QTextEdit::textColor() const
717{
718 Q_D(const QTextEdit);
719
720 const auto fg = d->control->textCursor().charFormat().foreground();
721 if (fg.style() == Qt::NoBrush) {
722 const auto context = d->control->getPaintContext(const_cast<QTextEdit *>(this));
723 return context.palette.color(QPalette::Text);
724 }
725
726 return fg.color();
727}
728
729/*!
730 \since 4.4
731
732 Returns the text background color of the current format.
733
734 \sa setTextBackgroundColor()
735*/
736QColor QTextEdit::textBackgroundColor() const
737{
738 Q_D(const QTextEdit);
739 const QBrush &brush = d->control->textCursor().charFormat().background();
740 return brush.style() == Qt::NoBrush ? Qt::transparent : brush.color();
741}
742
743/*!
744 Returns the font of the current format.
745
746 \sa setCurrentFont(), setFontFamily(), setFontPointSize()
747*/
748QFont QTextEdit::currentFont() const
749{
750 Q_D(const QTextEdit);
751 return d->control->textCursor().charFormat().font();
752}
753
754/*!
755 Sets the alignment of the current paragraph to \a a. Valid
756 alignments are Qt::AlignLeft, Qt::AlignRight,
757 Qt::AlignJustify and Qt::AlignCenter (which centers
758 horizontally).
759*/
760void QTextEdit::setAlignment(Qt::Alignment a)
761{
762 Q_D(QTextEdit);
763 QTextBlockFormat fmt;
764 fmt.setAlignment(a);
765 QTextCursor cursor = d->control->textCursor();
766 cursor.mergeBlockFormat(fmt);
767 d->control->setTextCursor(cursor);
768 d->relayoutDocument();
769}
770
771/*!
772 Returns the alignment of the current paragraph.
773
774 \sa setAlignment()
775*/
776Qt::Alignment QTextEdit::alignment() const
777{
778 Q_D(const QTextEdit);
779 return d->control->textCursor().blockFormat().alignment();
780}
781
782/*!
783 \property QTextEdit::document
784 \brief the underlying document of the text editor.
785
786 \note The editor \e{does not take ownership of the document} unless it
787 is the document's parent object. The parent object of the provided document
788 remains the owner of the object. If the previously assigned document is a
789 child of the editor then it will be deleted.
790*/
791void QTextEdit::setDocument(QTextDocument *document)
792{
793 Q_D(QTextEdit);
794 d->control->setDocument(document);
795 d->updateDefaultTextOption();
796 d->relayoutDocument();
797}
798
799QTextDocument *QTextEdit::document() const
800{
801 Q_D(const QTextEdit);
802 return d->control->document();
803}
804
805/*!
806 \since 5.2
807
808 \property QTextEdit::placeholderText
809 \brief the editor placeholder text
810
811 Setting this property makes the editor display a grayed-out
812 placeholder text as long as the document() is empty.
813
814 By default, this property contains an empty string.
815
816 \sa document()
817*/
818QString QTextEdit::placeholderText() const
819{
820 Q_D(const QTextEdit);
821 return d->placeholderText;
822}
823
824void QTextEdit::setPlaceholderText(const QString &placeholderText)
825{
826 Q_D(QTextEdit);
827 if (d->placeholderText != placeholderText) {
828 d->placeholderText = placeholderText;
829 if (d->control->document()->isEmpty())
830 d->viewport->update();
831 }
832}
833
834/*!
835 Sets the visible \a cursor.
836*/
837void QTextEdit::setTextCursor(const QTextCursor &cursor)
838{
839 doSetTextCursor(cursor);
840}
841
842/*!
843 \internal
844
845 This provides a hook for subclasses to intercept cursor changes.
846*/
847
848void QTextEdit::doSetTextCursor(const QTextCursor &cursor)
849{
850 Q_D(QTextEdit);
851 d->control->setTextCursor(cursor);
852}
853
854/*!
855 Returns a copy of the QTextCursor that represents the currently visible cursor.
856 Note that changes on the returned cursor do not affect QTextEdit's cursor; use
857 setTextCursor() to update the visible cursor.
858 */
859QTextCursor QTextEdit::textCursor() const
860{
861 Q_D(const QTextEdit);
862 return d->control->textCursor();
863}
864
865/*!
866 Sets the font family of the current format to \a fontFamily.
867
868 \sa fontFamily(), setCurrentFont()
869*/
870void QTextEdit::setFontFamily(const QString &fontFamily)
871{
872 QTextCharFormat fmt;
873 fmt.setFontFamilies({fontFamily});
874 mergeCurrentCharFormat(fmt);
875}
876
877/*!
878 Sets the point size of the current format to \a s.
879
880 Note that if \a s is zero or negative, the behavior of this
881 function is not defined.
882
883 \sa fontPointSize(), setCurrentFont(), setFontFamily()
884*/
885void QTextEdit::setFontPointSize(qreal s)
886{
887 QTextCharFormat fmt;
888 fmt.setFontPointSize(s);
889 mergeCurrentCharFormat(fmt);
890}
891
892/*!
893 \fn void QTextEdit::setFontWeight(int weight)
894
895 Sets the font weight of the current format to the given \a weight,
896 where the value used is in the range defined by the QFont::Weight
897 enum.
898
899 \sa fontWeight(), setCurrentFont(), setFontFamily()
900*/
901void QTextEdit::setFontWeight(int w)
902{
903 QTextCharFormat fmt;
904 fmt.setFontWeight(w);
905 mergeCurrentCharFormat(fmt);
906}
907
908/*!
909 If \a underline is true, sets the current format to underline;
910 otherwise sets the current format to non-underline.
911
912 \sa fontUnderline()
913*/
914void QTextEdit::setFontUnderline(bool underline)
915{
916 QTextCharFormat fmt;
917 fmt.setFontUnderline(underline);
918 mergeCurrentCharFormat(fmt);
919}
920
921/*!
922 If \a italic is true, sets the current format to italic;
923 otherwise sets the current format to non-italic.
924
925 \sa fontItalic()
926*/
927void QTextEdit::setFontItalic(bool italic)
928{
929 QTextCharFormat fmt;
930 fmt.setFontItalic(italic);
931 mergeCurrentCharFormat(fmt);
932}
933
934/*!
935 Sets the text color of the current format to \a c.
936
937 \sa textColor()
938*/
939void QTextEdit::setTextColor(const QColor &c)
940{
941 QTextCharFormat fmt;
942 fmt.setForeground(QBrush(c));
943 mergeCurrentCharFormat(fmt);
944}
945
946/*!
947 \since 4.4
948
949 Sets the text background color of the current format to \a c.
950
951 \sa textBackgroundColor()
952*/
953void QTextEdit::setTextBackgroundColor(const QColor &c)
954{
955 QTextCharFormat fmt;
956 fmt.setBackground(QBrush(c));
957 mergeCurrentCharFormat(fmt);
958}
959
960/*!
961 Sets the font of the current format to \a f.
962
963 \sa currentFont(), setFontPointSize(), setFontFamily()
964*/
965void QTextEdit::setCurrentFont(const QFont &f)
966{
967 QTextCharFormat fmt;
968 fmt.setFont(f);
969 mergeCurrentCharFormat(fmt);
970}
971
972/*!
973 \since 4.2
974
975 Undoes the last operation.
976
977 If there is no operation to undo, i.e. there is no undo step in
978 the undo/redo history, nothing happens.
979
980 \sa redo()
981*/
982void QTextEdit::undo()
983{
984 Q_D(QTextEdit);
985 d->control->undo();
986}
987
988void QTextEdit::redo()
989{
990 Q_D(QTextEdit);
991 d->control->redo();
992}
993
994/*!
995 \fn void QTextEdit::redo()
996 \since 4.2
997
998 Redoes the last operation.
999
1000 If there is no operation to redo, i.e. there is no redo step in
1001 the undo/redo history, nothing happens.
1002
1003 \sa undo()
1004*/
1005
1006#ifndef QT_NO_CLIPBOARD
1007/*!
1008 Copies the selected text to the clipboard and deletes it from
1009 the text edit.
1010
1011 If there is no selected text nothing happens.
1012
1013 \sa copy(), paste()
1014*/
1015
1016void QTextEdit::cut()
1017{
1018 Q_D(QTextEdit);
1019 d->control->cut();
1020}
1021
1022/*!
1023 Copies any selected text to the clipboard.
1024
1025 \sa copyAvailable()
1026*/
1027
1028void QTextEdit::copy()
1029{
1030 Q_D(QTextEdit);
1031 d->control->copy();
1032}
1033
1034/*!
1035 Pastes the text from the clipboard into the text edit at the
1036 current cursor position.
1037
1038 If there is no text in the clipboard nothing happens.
1039
1040 To change the behavior of this function, i.e. to modify what
1041 QTextEdit can paste and how it is being pasted, reimplement the
1042 virtual canInsertFromMimeData() and insertFromMimeData()
1043 functions.
1044
1045 \sa cut(), copy()
1046*/
1047
1048void QTextEdit::paste()
1049{
1050 Q_D(QTextEdit);
1051 d->control->paste();
1052}
1053#endif
1054
1055/*!
1056 Deletes all the text in the text edit.
1057
1058 Notes:
1059 \list
1060 \li The undo/redo history is also cleared.
1061 \li currentCharFormat() is reset, unless textCursor()
1062 is already at the beginning of the document.
1063 \endlist
1064
1065 \sa cut(), setPlainText(), setHtml()
1066*/
1067void QTextEdit::clear()
1068{
1069 Q_D(QTextEdit);
1070 // clears and sets empty content
1071 d->control->clear();
1072}
1073
1074
1075/*!
1076 Selects all text.
1077
1078 \sa copy(), cut(), textCursor()
1079 */
1080void QTextEdit::selectAll()
1081{
1082 Q_D(QTextEdit);
1083 d->control->selectAll();
1084}
1085
1086/*! \internal
1087*/
1088bool QTextEdit::event(QEvent *e)
1089{
1090 Q_D(QTextEdit);
1091 switch (e->type()) {
1092 case QEvent::ShortcutOverride:
1093 case QEvent::ToolTip:
1094 d->sendControlEvent(e);
1095 break;
1096 case QEvent::WindowActivate:
1097 case QEvent::WindowDeactivate:
1098 d->control->setPalette(palette());
1099 break;
1100#ifndef QT_NO_CONTEXTMENU
1101 case QEvent::ContextMenu:
1102 if (static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard) {
1103 ensureCursorVisible();
1104 const QPoint cursorPos = cursorRect().center();
1105 QContextMenuEvent ce(QContextMenuEvent::Keyboard, cursorPos, d->viewport->mapToGlobal(cursorPos));
1106 ce.setAccepted(e->isAccepted());
1107 const bool result = QAbstractScrollArea::event(&ce);
1108 e->setAccepted(ce.isAccepted());
1109 return result;
1110 }
1111 break;
1112#endif // QT_NO_CONTEXTMENU
1113 default:
1114 break;
1115 }
1116 return QAbstractScrollArea::event(e);
1117}
1118
1119/*! \internal
1120*/
1121
1122void QTextEdit::timerEvent(QTimerEvent *e)
1123{
1124 Q_D(QTextEdit);
1125 if (e->timerId() == d->autoScrollTimer.timerId()) {
1126 QRect visible = d->viewport->rect();
1127 QPoint pos;
1128 if (d->inDrag) {
1129 pos = d->autoScrollDragPos;
1130 visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
1131 -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
1132 } else {
1133 const QPoint globalPos = QCursor::pos();
1134 pos = d->viewport->mapFromGlobal(globalPos);
1135 QMouseEvent ev(QEvent::MouseMove, pos, mapTo(topLevelWidget(), pos), globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
1136 mouseMoveEvent(&ev);
1137 }
1138 int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
1139 int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
1140 int delta = qMax(deltaX, deltaY);
1141 if (delta >= 0) {
1142 if (delta < 7)
1143 delta = 7;
1144 int timeout = 4900 / (delta * delta);
1145 d->autoScrollTimer.start(timeout, this);
1146
1147 if (deltaY > 0)
1148 d->vbar->triggerAction(pos.y() < visible.center().y() ?
1149 QAbstractSlider::SliderSingleStepSub
1150 : QAbstractSlider::SliderSingleStepAdd);
1151 if (deltaX > 0)
1152 d->hbar->triggerAction(pos.x() < visible.center().x() ?
1153 QAbstractSlider::SliderSingleStepSub
1154 : QAbstractSlider::SliderSingleStepAdd);
1155 }
1156 }
1157}
1158
1159/*!
1160 Changes the text of the text edit to the string \a text.
1161 Any previous text is removed.
1162
1163 Notes:
1164 \list
1165 \li \a text is interpreted as plain text.
1166 \li The undo/redo history is also cleared.
1167 \li currentCharFormat() is reset, unless textCursor()
1168 is already at the beginning of the document.
1169 \endlist
1170
1171 \sa toPlainText()
1172*/
1173
1174void QTextEdit::setPlainText(const QString &text)
1175{
1176 Q_D(QTextEdit);
1177 d->control->setPlainText(text);
1178 d->preferRichText = false;
1179}
1180
1181/*!
1182 QString QTextEdit::toPlainText() const
1183
1184 Returns the text of the text edit as plain text.
1185
1186 \sa QTextEdit::setPlainText()
1187 */
1188QString QTextEdit::toPlainText() const
1189{
1190 Q_D(const QTextEdit);
1191 return d->control->toPlainText();
1192}
1193
1194/*!
1195 \property QTextEdit::html
1196
1197 This property provides an HTML interface to the text of the text edit.
1198
1199 toHtml() returns the text of the text edit as html.
1200
1201 setHtml() changes the text of the text edit. Any previous text is
1202 removed and the undo/redo history is cleared. The input text is
1203 interpreted as rich text in html format. currentCharFormat() is also
1204 reset, unless textCursor() is already at the beginning of the document.
1205
1206 \note It is the responsibility of the caller to make sure that the
1207 text is correctly decoded when a QString containing HTML is created
1208 and passed to setHtml().
1209
1210 By default, for a newly-created, empty document, this property contains
1211 text to describe an HTML 4.0 document with no body text.
1212
1213 \sa {Supported HTML Subset}, plainText
1214*/
1215
1216#ifndef QT_NO_TEXTHTMLPARSER
1217void QTextEdit::setHtml(const QString &text)
1218{
1219 Q_D(QTextEdit);
1220 d->control->setHtml(text);
1221 d->preferRichText = true;
1222}
1223
1224QString QTextEdit::toHtml() const
1225{
1226 Q_D(const QTextEdit);
1227 return d->control->toHtml();
1228}
1229#endif
1230
1231#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
1232/*!
1233 \property QTextEdit::markdown
1234
1235 This property provides a Markdown interface to the text of the text edit.
1236
1237 \c toMarkdown() returns the text of the text edit as "pure" Markdown,
1238 without any embedded HTML formatting. Some features that QTextDocument
1239 supports (such as the use of specific colors and named fonts) cannot be
1240 expressed in "pure" Markdown, and they will be omitted.
1241
1242 \c setMarkdown() changes the text of the text edit. Any previous text is
1243 removed and the undo/redo history is cleared. The input text is
1244 interpreted as rich text in Markdown format.
1245
1246 Parsing of HTML included in the \a markdown string is handled in the same
1247 way as in \l setHtml; however, Markdown formatting inside HTML blocks is
1248 not supported.
1249
1250 Some features of the parser can be enabled or disabled via the \a features
1251 argument:
1252
1253 \value MarkdownNoHTML
1254 Any HTML tags in the Markdown text will be discarded
1255 \value MarkdownDialectCommonMark
1256 The parser supports only the features standardized by CommonMark
1257 \value MarkdownDialectGitHub
1258 The parser supports the GitHub dialect
1259
1260 The default is \c MarkdownDialectGitHub.
1261
1262 \sa plainText, html, QTextDocument::toMarkdown(), QTextDocument::setMarkdown()
1263 \since 5.14
1264*/
1265#endif
1266
1267#if QT_CONFIG(textmarkdownreader)
1268void QTextEdit::setMarkdown(const QString &markdown)
1269{
1270 Q_D(const QTextEdit);
1271 d->control->setMarkdown(markdown);
1272}
1273#endif
1274
1275#if QT_CONFIG(textmarkdownwriter)
1276QString QTextEdit::toMarkdown(QTextDocument::MarkdownFeatures features) const
1277{
1278 Q_D(const QTextEdit);
1279 return d->control->toMarkdown(features);
1280}
1281#endif
1282
1283/*! \reimp
1284*/
1285void QTextEdit::keyPressEvent(QKeyEvent *e)
1286{
1287 Q_D(QTextEdit);
1288
1289#ifndef QT_NO_SHORTCUT
1290
1291 Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
1292
1293 if (tif & Qt::TextSelectableByKeyboard){
1294 if (e == QKeySequence::SelectPreviousPage) {
1295 e->accept();
1296 d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
1297 return;
1298 } else if (e ==QKeySequence::SelectNextPage) {
1299 e->accept();
1300 d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
1301 return;
1302 }
1303 }
1304 if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
1305 if (e == QKeySequence::MoveToPreviousPage) {
1306 e->accept();
1307 d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
1308 return;
1309 } else if (e == QKeySequence::MoveToNextPage) {
1310 e->accept();
1311 d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
1312 return;
1313 }
1314 }
1315
1316 if (!(tif & Qt::TextEditable)) {
1317 switch (e->key()) {
1318 case Qt::Key_Space:
1319 e->accept();
1320 if (e->modifiers() & Qt::ShiftModifier)
1321 d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
1322 else
1323 d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
1324 break;
1325 default:
1326 d->sendControlEvent(e);
1327 if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
1328 if (e->key() == Qt::Key_Home) {
1329 d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
1330 e->accept();
1331 } else if (e->key() == Qt::Key_End) {
1332 d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
1333 e->accept();
1334 }
1335 }
1336 if (!e->isAccepted()) {
1337 QAbstractScrollArea::keyPressEvent(e);
1338 }
1339 }
1340 return;
1341 }
1342#endif // QT_NO_SHORTCUT
1343
1344 {
1345 QTextCursor cursor = d->control->textCursor();
1346 const QString text = e->text();
1347 if (cursor.atBlockStart()
1348 && (d->autoFormatting & AutoBulletList)
1349 && (text.size() == 1)
1350 && (text.at(0) == u'-' || text.at(0) == u'*')
1351 && (!cursor.currentList())) {
1352
1353 d->createAutoBulletList();
1354 e->accept();
1355 return;
1356 }
1357 }
1358
1359 d->sendControlEvent(e);
1360}
1361
1362/*! \reimp
1363*/
1364void QTextEdit::keyReleaseEvent(QKeyEvent *e)
1365{
1366 Q_D(QTextEdit);
1367 if (!isReadOnly())
1368 d->handleSoftwareInputPanel();
1369 e->ignore();
1370}
1371
1372/*!
1373 Loads the resource specified by the given \a type and \a name.
1374
1375 This function is an extension of QTextDocument::loadResource().
1376
1377 \sa QTextDocument::loadResource()
1378*/
1379QVariant QTextEdit::loadResource(int type, const QUrl &name)
1380{
1381 Q_UNUSED(type);
1382 Q_UNUSED(name);
1383 return QVariant();
1384}
1385
1386/*! \reimp
1387*/
1388void QTextEdit::resizeEvent(QResizeEvent *e)
1389{
1390 Q_D(QTextEdit);
1391
1392 if (d->lineWrap == NoWrap) {
1393 QTextDocument *doc = d->control->document();
1394 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1395
1396 if (!doc->pageSize().isNull()
1397 && alignmentProperty.userType() == QMetaType::Bool
1398 && !alignmentProperty.toBool()) {
1399
1400 d->adjustScrollbars();
1401 return;
1402 }
1403 }
1404
1405 if (d->lineWrap != FixedPixelWidth
1406 && e->oldSize().width() != e->size().width())
1407 d->relayoutDocument();
1408 else
1409 d->adjustScrollbars();
1410}
1411
1413{
1414 QTextDocument *doc = control->document();
1415 QAbstractTextDocumentLayout *layout = doc->documentLayout();
1416
1417 if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
1418 if (lineWrap == QTextEdit::FixedColumnWidth)
1419 tlayout->setFixedColumnWidth(lineWrapColumnOrWidth);
1420 else
1421 tlayout->setFixedColumnWidth(-1);
1422 }
1423
1424 QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout);
1425 QSize lastUsedSize;
1426 if (tlayout)
1427 lastUsedSize = tlayout->dynamicDocumentSize().toSize();
1428 else
1429 lastUsedSize = layout->documentSize().toSize();
1430
1431 // ignore calls to adjustScrollbars caused by an emission of the
1432 // usedSizeChanged() signal in the layout, as we're calling it
1433 // later on our own anyway (or deliberately not) .
1434 const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
1435 ignoreAutomaticScrollbarAdjustment = true;
1436
1437 int width = viewport->width();
1438 if (lineWrap == QTextEdit::FixedPixelWidth)
1439 width = lineWrapColumnOrWidth;
1440 else if (lineWrap == QTextEdit::NoWrap) {
1441 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1442 if (alignmentProperty.userType() == QMetaType::Bool && !alignmentProperty.toBool()) {
1443
1444 width = 0;
1445 }
1446 }
1447
1448 doc->setPageSize(QSize(width, -1));
1449 if (tlayout)
1450 tlayout->ensureLayouted(verticalOffset() + viewport->height());
1451
1452 ignoreAutomaticScrollbarAdjustment = oldIgnoreScrollbarAdjustment;
1453
1454 QSize usedSize;
1455 if (tlayout)
1456 usedSize = tlayout->dynamicDocumentSize().toSize();
1457 else
1458 usedSize = layout->documentSize().toSize();
1459
1460 // this is an obscure situation in the layout that can happen:
1461 // if a character at the end of a line is the tallest one and therefore
1462 // influencing the total height of the line and the line right below it
1463 // is always taller though, then it can happen that if due to line breaking
1464 // that tall character wraps into the lower line the document not only shrinks
1465 // horizontally (causing the character to wrap in the first place) but also
1466 // vertically, because the original line is now smaller and the one below kept
1467 // its size. So a layout with less width _can_ take up less vertical space, too.
1468 // If the wider case causes a vertical scroll bar to appear and the narrower one
1469 // (narrower because the vertical scroll bar takes up horizontal space)) to disappear
1470 // again then we have an endless loop, as adjustScrollbars sets new ranges on the
1471 // scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
1472 // the scroll bars again. That's why we try to detect this case here and break out.
1473 //
1474 // (if you change this please also check the layoutingLoop() testcase in
1475 // QTextEdit's autotests)
1476 if (lastUsedSize.isValid()
1477 && !vbar->isHidden()
1478 && viewport->width() < lastUsedSize.width()
1479 && usedSize.height() < lastUsedSize.height()
1480 && usedSize.height() <= viewport->height())
1481 return;
1482
1484}
1485
1486void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
1487{
1488 const int xOffset = horizontalOffset();
1489 const int yOffset = verticalOffset();
1490
1491 QRect r = e->rect();
1492 p->translate(-xOffset, -yOffset);
1493 r.translate(xOffset, yOffset);
1494
1495 QTextDocument *doc = control->document();
1496 QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());
1497
1498 // the layout might need to expand the root frame to
1499 // the viewport if NoWrap is set
1500 if (layout)
1501 layout->setViewport(viewport->rect());
1502
1503 control->drawContents(p, r, q_func());
1504
1505 if (layout)
1506 layout->setViewport(QRect());
1507
1508 if (!placeholderText.isEmpty() && doc->isEmpty() && !control->isPreediting()) {
1509 const QColor col = control->palette().placeholderText().color();
1510 p->setPen(col);
1511 const int margin = int(doc->documentMargin());
1512 QRectF boundingRect = layout ? layout->frameBoundingRect(doc->rootFrame()) : viewport->rect();
1513 p->drawText(boundingRect.adjusted(margin, margin, -margin, -margin),
1514 Qt::AlignTop | Qt::TextWordWrap,
1515 placeholderText);
1516 }
1517}
1518
1519/*! \fn void QTextEdit::paintEvent(QPaintEvent *event)
1520
1521This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
1522It is usually unnecessary to reimplement this function in a subclass of QTextEdit.
1523
1524\note If you create a QPainter, it must operate on the \l{QAbstractScrollArea::}{viewport()}.
1525
1526\warning The underlying text document must not be modified from within a reimplementation
1527of this function.
1528*/
1529void QTextEdit::paintEvent(QPaintEvent *e)
1530{
1531 Q_D(QTextEdit);
1532 QPainter p(d->viewport);
1533 d->paint(&p, e);
1534}
1535
1537{
1538 QTextDocument *doc = control->document();
1539
1540 QTextOption opt = doc->defaultTextOption();
1541 QTextOption::WrapMode oldWrapMode = opt.wrapMode();
1542
1543 if (lineWrap == QTextEdit::NoWrap)
1544 opt.setWrapMode(QTextOption::NoWrap);
1545 else
1546 opt.setWrapMode(wordWrap);
1547
1548 if (opt.wrapMode() != oldWrapMode)
1549 doc->setDefaultTextOption(opt);
1550}
1551
1552/*! \reimp
1553*/
1554void QTextEdit::mousePressEvent(QMouseEvent *e)
1555{
1556 Q_D(QTextEdit);
1557 d->sendControlEvent(e);
1558}
1559
1560/*! \reimp
1561*/
1562void QTextEdit::mouseMoveEvent(QMouseEvent *e)
1563{
1564 Q_D(QTextEdit);
1565 d->inDrag = false; // paranoia
1566 const QPoint pos = e->position().toPoint();
1567 d->sendControlEvent(e);
1568 if (!(e->buttons() & Qt::LeftButton))
1569 return;
1570 if (e->source() == Qt::MouseEventNotSynthesized) {
1571 const QRect visible = d->viewport->rect();
1572 if (visible.contains(pos))
1573 d->autoScrollTimer.stop();
1574 else if (!d->autoScrollTimer.isActive())
1575 d->autoScrollTimer.start(100, this);
1576 }
1577}
1578
1579/*! \reimp
1580*/
1581void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
1582{
1583 Q_D(QTextEdit);
1584 d->sendControlEvent(e);
1585 if (e->source() == Qt::MouseEventNotSynthesized && d->autoScrollTimer.isActive()) {
1586 d->autoScrollTimer.stop();
1587 ensureCursorVisible();
1588 }
1589 if (!isReadOnly() && rect().contains(e->position().toPoint()))
1590 d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
1591 d->clickCausedFocus = 0;
1592}
1593
1594/*! \reimp
1595*/
1596void QTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
1597{
1598 Q_D(QTextEdit);
1599 d->sendControlEvent(e);
1600}
1601
1602/*! \reimp
1603*/
1604bool QTextEdit::focusNextPrevChild(bool next)
1605{
1606 Q_D(const QTextEdit);
1607 if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
1608 return false;
1609 return QAbstractScrollArea::focusNextPrevChild(next);
1610}
1611
1612#ifndef QT_NO_CONTEXTMENU
1613/*!
1614 \fn void QTextEdit::contextMenuEvent(QContextMenuEvent *event)
1615
1616 Shows the standard context menu created with createStandardContextMenu().
1617
1618 If you do not want the text edit to have a context menu, you can set
1619 its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
1620 customize the context menu, reimplement this function. If you want
1621 to extend the standard context menu, reimplement this function, call
1622 createStandardContextMenu() and extend the menu returned.
1623
1624 Information about the event is passed in the \a event object.
1625
1626 \snippet code/src_gui_widgets_qtextedit.cpp 0
1627*/
1628void QTextEdit::contextMenuEvent(QContextMenuEvent *e)
1629{
1630 Q_D(QTextEdit);
1631 d->sendControlEvent(e);
1632}
1633#endif // QT_NO_CONTEXTMENU
1634
1635#if QT_CONFIG(draganddrop)
1636/*! \reimp
1637*/
1638void QTextEdit::dragEnterEvent(QDragEnterEvent *e)
1639{
1640 Q_D(QTextEdit);
1641 d->inDrag = true;
1642 d->sendControlEvent(e);
1643}
1644
1645/*! \reimp
1646*/
1647void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
1648{
1649 Q_D(QTextEdit);
1650 d->inDrag = false;
1651 d->autoScrollTimer.stop();
1652 d->sendControlEvent(e);
1653}
1654
1655/*! \reimp
1656*/
1657void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
1658{
1659 Q_D(QTextEdit);
1660 d->autoScrollDragPos = e->position().toPoint();
1661 if (!d->autoScrollTimer.isActive())
1662 d->autoScrollTimer.start(100, this);
1663 d->sendControlEvent(e);
1664}
1665
1666/*! \reimp
1667*/
1668void QTextEdit::dropEvent(QDropEvent *e)
1669{
1670 Q_D(QTextEdit);
1671 d->inDrag = false;
1672 d->autoScrollTimer.stop();
1673 d->sendControlEvent(e);
1674}
1675
1676#endif // QT_CONFIG(draganddrop)
1677
1678/*! \reimp
1679 */
1680void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
1681{
1682 Q_D(QTextEdit);
1683 d->sendControlEvent(e);
1684 const bool emptyEvent = e->preeditString().isEmpty() && e->commitString().isEmpty()
1685 && e->attributes().isEmpty();
1686 if (emptyEvent)
1687 return;
1688 ensureCursorVisible();
1689}
1690
1691/*!\reimp
1692*/
1693void QTextEdit::scrollContentsBy(int dx, int dy)
1694{
1695 Q_D(QTextEdit);
1696 if (isRightToLeft())
1697 dx = -dx;
1698 d->viewport->scroll(dx, dy);
1699 QGuiApplication::inputMethod()->update(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
1700}
1701
1702/*!\reimp
1703*/
1704QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
1705{
1706 return inputMethodQuery(property, QVariant());
1707}
1708
1709/*!\internal
1710 */
1711QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argument) const
1712{
1713 Q_D(const QTextEdit);
1714 switch (query) {
1715 case Qt::ImEnabled:
1716 return isEnabled() && !isReadOnly();
1717 case Qt::ImHints:
1718 case Qt::ImInputItemClipRectangle:
1719 return QWidget::inputMethodQuery(query);
1720 case Qt::ImReadOnly:
1721 return isReadOnly();
1722 default:
1723 break;
1724 }
1725
1726 const QPointF offset = QPointF(-d->horizontalOffset(), -d->verticalOffset())
1727 + d->viewport->mapTo(this, QPointF());
1728 switch (argument.userType()) {
1729 case QMetaType::QRectF:
1730 argument = argument.toRectF().translated(-offset);
1731 break;
1732 case QMetaType::QPointF:
1733 argument = argument.toPointF() - offset;
1734 break;
1735 case QMetaType::QRect:
1736 argument = argument.toRect().translated(-offset.toPoint());
1737 break;
1738 case QMetaType::QPoint:
1739 argument = argument.toPoint() - offset;
1740 break;
1741 default:
1742 break;
1743 }
1744
1745 const QVariant v = d->control->inputMethodQuery(query, argument);
1746 switch (v.userType()) {
1747 case QMetaType::QRectF:
1748 return v.toRectF().translated(offset);
1749 case QMetaType::QPointF:
1750 return v.toPointF() + offset;
1751 case QMetaType::QRect:
1752 return v.toRect().translated(offset.toPoint());
1753 case QMetaType::QPoint:
1754 return v.toPoint() + offset.toPoint();
1755 default:
1756 break;
1757 }
1758 return v;
1759}
1760
1761/*! \reimp
1762*/
1763void QTextEdit::focusInEvent(QFocusEvent *e)
1764{
1765 Q_D(QTextEdit);
1766 if (e->reason() == Qt::MouseFocusReason) {
1767 d->clickCausedFocus = 1;
1768 }
1769 QAbstractScrollArea::focusInEvent(e);
1770 d->sendControlEvent(e);
1771}
1772
1773/*! \reimp
1774*/
1775void QTextEdit::focusOutEvent(QFocusEvent *e)
1776{
1777 Q_D(QTextEdit);
1778 QAbstractScrollArea::focusOutEvent(e);
1779 d->sendControlEvent(e);
1780}
1781
1782/*! \reimp
1783*/
1784void QTextEdit::showEvent(QShowEvent *)
1785{
1786 Q_D(QTextEdit);
1787 if (!d->anchorToScrollToWhenVisible.isEmpty()) {
1788 scrollToAnchor(d->anchorToScrollToWhenVisible);
1789 d->anchorToScrollToWhenVisible.clear();
1790 d->showCursorOnInitialShow = false;
1791 } else if (d->showCursorOnInitialShow) {
1792 d->showCursorOnInitialShow = false;
1793 ensureCursorVisible();
1794 }
1795}
1796
1797/*! \reimp
1798*/
1799void QTextEdit::changeEvent(QEvent *e)
1800{
1801 Q_D(QTextEdit);
1802 QAbstractScrollArea::changeEvent(e);
1803 if (e->type() == QEvent::ApplicationFontChange
1804 || e->type() == QEvent::FontChange) {
1805 d->control->document()->setDefaultFont(font());
1806 } else if (e->type() == QEvent::ActivationChange) {
1807 if (!isActiveWindow())
1808 d->autoScrollTimer.stop();
1809 } else if (e->type() == QEvent::EnabledChange) {
1810 e->setAccepted(isEnabled());
1811 d->control->setPalette(palette());
1812 d->sendControlEvent(e);
1813 } else if (e->type() == QEvent::PaletteChange) {
1814 d->control->setPalette(palette());
1815 } else if (e->type() == QEvent::LayoutDirectionChange) {
1816 d->sendControlEvent(e);
1817 }
1818}
1819
1820/*! \reimp
1821*/
1822#if QT_CONFIG(wheelevent)
1823void QTextEdit::wheelEvent(QWheelEvent *e)
1824{
1825 Q_D(QTextEdit);
1826 if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
1827 if (e->modifiers() & Qt::ControlModifier) {
1828 float delta = e->angleDelta().y() / 120.f;
1829 zoomInF(delta);
1830 return;
1831 }
1832 }
1833 QAbstractScrollArea::wheelEvent(e);
1834 updateMicroFocus();
1835}
1836#endif
1837
1838#ifndef QT_NO_CONTEXTMENU
1839/*! This function creates the standard context menu which is shown
1840 when the user clicks on the text edit with the right mouse
1841 button. It is called from the default contextMenuEvent() handler.
1842 The popup menu's ownership is transferred to the caller.
1843
1844 We recommend that you use the createStandardContextMenu(QPoint) version instead
1845 which will enable the actions that are sensitive to where the user clicked.
1846*/
1847
1848QMenu *QTextEdit::createStandardContextMenu()
1849{
1850 Q_D(QTextEdit);
1851 return d->control->createStandardContextMenu(QPointF(), this);
1852}
1853
1854/*!
1855 \since 4.4
1856 This function creates the standard context menu which is shown
1857 when the user clicks on the text edit with the right mouse
1858 button. It is called from the default contextMenuEvent() handler
1859 and it takes the \a position in document coordinates where the mouse click was.
1860 This can enable actions that are sensitive to the position where the user clicked.
1861 The popup menu's ownership is transferred to the caller.
1862*/
1863
1864QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
1865{
1866 Q_D(QTextEdit);
1867 return d->control->createStandardContextMenu(position, this);
1868}
1869#endif // QT_NO_CONTEXTMENU
1870
1871/*!
1872 returns a QTextCursor at position \a pos (in viewport coordinates).
1873*/
1874QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
1875{
1876 Q_D(const QTextEdit);
1877 return d->control->cursorForPosition(d->mapToContents(pos));
1878}
1879
1880/*!
1881 returns a rectangle (in viewport coordinates) that includes the
1882 \a cursor.
1883 */
1884QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
1885{
1886 Q_D(const QTextEdit);
1887 if (cursor.isNull())
1888 return QRect();
1889
1890 QRect r = d->control->cursorRect(cursor).toRect();
1891 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1892 return r;
1893}
1894
1895/*!
1896 returns a rectangle (in viewport coordinates) that includes the
1897 cursor of the text edit.
1898 */
1899QRect QTextEdit::cursorRect() const
1900{
1901 Q_D(const QTextEdit);
1902 QRect r = d->control->cursorRect().toRect();
1903 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1904 return r;
1905}
1906
1907
1908/*!
1909 Returns the reference of the anchor at position \a pos, or an
1910 empty string if no anchor exists at that point.
1911*/
1912QString QTextEdit::anchorAt(const QPoint& pos) const
1913{
1914 Q_D(const QTextEdit);
1915 return d->control->anchorAt(d->mapToContents(pos));
1916}
1917
1918/*!
1919 \property QTextEdit::overwriteMode
1920 \since 4.1
1921 \brief whether text entered by the user will overwrite existing text
1922
1923 As with many text editors, the text editor widget can be configured
1924 to insert or overwrite existing text with new text entered by the user.
1925
1926 If this property is \c true, existing text is overwritten, character-for-character
1927 by new text; otherwise, text is inserted at the cursor position, displacing
1928 existing text.
1929
1930 By default, this property is \c false (new text does not overwrite existing text).
1931*/
1932
1933bool QTextEdit::overwriteMode() const
1934{
1935 Q_D(const QTextEdit);
1936 return d->control->overwriteMode();
1937}
1938
1939void QTextEdit::setOverwriteMode(bool overwrite)
1940{
1941 Q_D(QTextEdit);
1942 d->control->setOverwriteMode(overwrite);
1943}
1944
1945/*!
1946 \property QTextEdit::tabStopDistance
1947 \brief the tab stop distance in pixels
1948 \since 5.10
1949
1950 By default, this property contains a value of 80 pixels.
1951
1952 Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
1953 of the QChar::VisualTabCharacter character, otherwise the tab-character
1954 will be drawn incompletely.
1955
1956 \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
1957*/
1958
1959qreal QTextEdit::tabStopDistance() const
1960{
1961 Q_D(const QTextEdit);
1962 return d->control->document()->defaultTextOption().tabStopDistance();
1963}
1964
1965void QTextEdit::setTabStopDistance(qreal distance)
1966{
1967 Q_D(QTextEdit);
1968 QTextOption opt = d->control->document()->defaultTextOption();
1969 if (opt.tabStopDistance() == distance || distance < 0)
1970 return;
1971 opt.setTabStopDistance(distance);
1972 d->control->document()->setDefaultTextOption(opt);
1973}
1974
1975/*!
1976 \since 4.2
1977 \property QTextEdit::cursorWidth
1978
1979 This property specifies the width of the cursor in pixels. The default value is 1.
1980*/
1981int QTextEdit::cursorWidth() const
1982{
1983 Q_D(const QTextEdit);
1984 return d->control->cursorWidth();
1985}
1986
1987void QTextEdit::setCursorWidth(int width)
1988{
1989 Q_D(QTextEdit);
1990 d->control->setCursorWidth(width);
1991}
1992
1993/*!
1994 \property QTextEdit::acceptRichText
1995 \brief whether the text edit accepts rich text insertions by the user
1996 \since 4.1
1997
1998 When this property is set to false text edit will accept only
1999 plain text input from the user. For example through clipboard or drag and drop.
2000
2001 This property's default is true.
2002*/
2003
2004bool QTextEdit::acceptRichText() const
2005{
2006 Q_D(const QTextEdit);
2007 return d->control->acceptRichText();
2008}
2009
2010void QTextEdit::setAcceptRichText(bool accept)
2011{
2012 Q_D(QTextEdit);
2013 d->control->setAcceptRichText(accept);
2014}
2015
2016/*!
2017 \class QTextEdit::ExtraSelection
2018 \since 4.2
2019 \inmodule QtWidgets
2020
2021 \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
2022 character format for a given selection in a document.
2023*/
2024
2025/*!
2026 \variable QTextEdit::ExtraSelection::cursor
2027 A cursor that contains a selection in a QTextDocument
2028*/
2029
2030/*!
2031 \variable QTextEdit::ExtraSelection::format
2032 A format that is used to specify a foreground or background brush/color
2033 for the selection.
2034*/
2035
2036/*!
2037 \since 4.2
2038 This function allows temporarily marking certain regions in the document
2039 with a given color, specified as \a selections. This can be useful for
2040 example in a programming editor to mark a whole line of text with a given
2041 background color to indicate the existence of a breakpoint.
2042
2043 \sa QTextEdit::ExtraSelection, extraSelections()
2044*/
2045void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
2046{
2047 Q_D(QTextEdit);
2048 d->control->setExtraSelections(selections);
2049}
2050
2051/*!
2052 \since 4.2
2053 Returns previously set extra selections.
2054
2055 \sa setExtraSelections()
2056*/
2057QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
2058{
2059 Q_D(const QTextEdit);
2060 return d->control->extraSelections();
2061}
2062
2063/*!
2064 This function returns a new MIME data object to represent the contents
2065 of the text edit's current selection. It is called when the selection needs
2066 to be encapsulated into a new QMimeData object; for example, when a drag
2067 and drop operation is started, or when data is copied to the clipboard.
2068
2069 If you reimplement this function, note that the ownership of the returned
2070 QMimeData object is passed to the caller. The selection can be retrieved
2071 by using the textCursor() function.
2072*/
2073QMimeData *QTextEdit::createMimeDataFromSelection() const
2074{
2075 Q_D(const QTextEdit);
2076 return d->control->QWidgetTextControl::createMimeDataFromSelection();
2077}
2078
2079/*!
2080 This function returns \c true if the contents of the MIME data object, specified
2081 by \a source, can be decoded and inserted into the document. It is called
2082 for example when during a drag operation the mouse enters this widget and it
2083 is necessary to determine whether it is possible to accept the drag and drop
2084 operation.
2085
2086 Reimplement this function to enable drag and drop support for additional MIME types.
2087 */
2088bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
2089{
2090 Q_D(const QTextEdit);
2091 return d->control->QWidgetTextControl::canInsertFromMimeData(source);
2092}
2093
2094/*!
2095 This function inserts the contents of the MIME data object, specified
2096 by \a source, into the text edit at the current cursor position. It is
2097 called whenever text is inserted as the result of a clipboard paste
2098 operation, or when the text edit accepts data from a drag and drop
2099 operation.
2100
2101 Reimplement this function to enable drag and drop support for additional MIME types.
2102 */
2103void QTextEdit::insertFromMimeData(const QMimeData *source)
2104{
2105 Q_D(QTextEdit);
2106 d->control->QWidgetTextControl::insertFromMimeData(source);
2107}
2108
2109/*!
2110 \property QTextEdit::readOnly
2111 \brief whether the text edit is read-only
2112
2113 In a read-only text edit the user can only navigate through the
2114 text and select text; modifying the text is not possible.
2115
2116 This property's default is false.
2117*/
2118
2119bool QTextEdit::isReadOnly() const
2120{
2121 Q_D(const QTextEdit);
2122 return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
2123}
2124
2125void QTextEdit::setReadOnly(bool ro)
2126{
2127 Q_D(QTextEdit);
2128 Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
2129 if (ro) {
2130 flags = Qt::TextSelectableByMouse;
2131#if QT_CONFIG(textbrowser)
2132 if (qobject_cast<QTextBrowser *>(this))
2133 flags |= Qt::TextBrowserInteraction;
2134#endif
2135 } else {
2136 flags = Qt::TextEditorInteraction;
2137 }
2138 d->control->setTextInteractionFlags(flags);
2139 setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
2140 QEvent event(QEvent::ReadOnlyChange);
2141 QCoreApplication::sendEvent(this, &event);
2142}
2143
2144/*!
2145 \property QTextEdit::textInteractionFlags
2146 \since 4.2
2147
2148 Specifies how the widget should interact with user input.
2149
2150 The default value depends on whether the QTextEdit is read-only
2151 or editable, and whether it is a QTextBrowser or not.
2152*/
2153
2154void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
2155{
2156 Q_D(QTextEdit);
2157 d->control->setTextInteractionFlags(flags);
2158}
2159
2160Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
2161{
2162 Q_D(const QTextEdit);
2163 return d->control->textInteractionFlags();
2164}
2165
2166/*!
2167 Merges the properties specified in \a modifier into the current character
2168 format by calling QTextCursor::mergeCharFormat on the editor's cursor.
2169 If the editor has a selection then the properties of \a modifier are
2170 directly applied to the selection.
2171
2172 \sa QTextCursor::mergeCharFormat()
2173 */
2174void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
2175{
2176 Q_D(QTextEdit);
2177 d->control->mergeCurrentCharFormat(modifier);
2178}
2179
2180/*!
2181 Sets the char format that is be used when inserting new text to \a
2182 format by calling QTextCursor::setCharFormat() on the editor's
2183 cursor. If the editor has a selection then the char format is
2184 directly applied to the selection.
2185 */
2186void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
2187{
2188 Q_D(QTextEdit);
2189 d->control->setCurrentCharFormat(format);
2190}
2191
2192/*!
2193 Returns the char format that is used when inserting new text.
2194 */
2195QTextCharFormat QTextEdit::currentCharFormat() const
2196{
2197 Q_D(const QTextEdit);
2198 return d->control->currentCharFormat();
2199}
2200
2201/*!
2202 \property QTextEdit::autoFormatting
2203 \brief the enabled set of auto formatting features
2204
2205 The value can be any combination of the values in the
2206 AutoFormattingFlag enum. The default is AutoNone. Choose
2207 AutoAll to enable all automatic formatting.
2208
2209 Currently, the only automatic formatting feature provided is
2210 AutoBulletList; future versions of Qt may offer more.
2211*/
2212
2213QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
2214{
2215 Q_D(const QTextEdit);
2216 return d->autoFormatting;
2217}
2218
2219void QTextEdit::setAutoFormatting(AutoFormatting features)
2220{
2221 Q_D(QTextEdit);
2222 d->autoFormatting = features;
2223}
2224
2225/*!
2226 Convenience slot that inserts \a text at the current
2227 cursor position.
2228
2229 It is equivalent to
2230
2231 \snippet code/src_gui_widgets_qtextedit.cpp 1
2232 */
2233void QTextEdit::insertPlainText(const QString &text)
2234{
2235 Q_D(QTextEdit);
2236 d->control->insertPlainText(text);
2237}
2238
2239/*!
2240 Convenience slot that inserts \a text which is assumed to be of
2241 html formatting at the current cursor position.
2242
2243 It is equivalent to:
2244
2245 \snippet code/src_gui_widgets_qtextedit.cpp 2
2246
2247 \note When using this function with a style sheet, the style sheet will
2248 only apply to the current block in the document. In order to apply a style
2249 sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
2250 instead.
2251 */
2252#ifndef QT_NO_TEXTHTMLPARSER
2253void QTextEdit::insertHtml(const QString &text)
2254{
2255 Q_D(QTextEdit);
2256 d->control->insertHtml(text);
2257}
2258#endif // QT_NO_TEXTHTMLPARSER
2259
2260/*!
2261 Scrolls the text edit so that the anchor with the given \a name is
2262 visible; does nothing if the \a name is empty, or is already
2263 visible, or isn't found.
2264*/
2265void QTextEdit::scrollToAnchor(const QString &name)
2266{
2267 Q_D(QTextEdit);
2268 if (name.isEmpty())
2269 return;
2270
2271 if (!isVisible()) {
2272 d->anchorToScrollToWhenVisible = name;
2273 return;
2274 }
2275
2276 QPointF p = d->control->anchorPosition(name);
2277 const int newPosition = qRound(p.y());
2278 if ( d->vbar->maximum() < newPosition )
2279 d->adjustScrollbars();
2280 d->vbar->setValue(newPosition);
2281}
2282
2283/*!
2284 Zooms in on the text by making the base font size \a range
2285 points larger and recalculating all font sizes to be the new size.
2286 This does not change the size of any images.
2287
2288 \sa zoomOut()
2289*/
2290void QTextEdit::zoomIn(int range)
2291{
2292 zoomInF(range);
2293}
2294
2295/*!
2296 Zooms out on the text by making the base font size \a range points
2297 smaller and recalculating all font sizes to be the new size. This
2298 does not change the size of any images.
2299
2300 \sa zoomIn()
2301*/
2302void QTextEdit::zoomOut(int range)
2303{
2304 zoomInF(-range);
2305}
2306
2307/*!
2308 \internal
2309*/
2310void QTextEdit::zoomInF(float range)
2311{
2312 if (range == 0.f)
2313 return;
2314 QFont f = font();
2315 const float newSize = f.pointSizeF() + range;
2316 if (newSize <= 0)
2317 return;
2318 f.setPointSizeF(newSize);
2319 setFont(f);
2320}
2321
2322/*!
2323 \since 4.2
2324 Moves the cursor by performing the given \a operation.
2325
2326 If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
2327 This is the same effect that the user achieves when they hold down the Shift key
2328 and move the cursor with the cursor keys.
2329
2330 \sa QTextCursor::movePosition()
2331*/
2332void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
2333{
2334 Q_D(QTextEdit);
2335 d->control->moveCursor(operation, mode);
2336}
2337
2338/*!
2339 \since 4.2
2340 Returns whether text can be pasted from the clipboard into the textedit.
2341*/
2342bool QTextEdit::canPaste() const
2343{
2344 Q_D(const QTextEdit);
2345 return d->control->canPaste();
2346}
2347
2348/*!
2349 \since 4.3
2350 Convenience function to print the text edit's document to the given \a printer. This
2351 is equivalent to calling the print method on the document directly except that this
2352 function also supports QPrinter::Selection as print range.
2353
2354 \sa QTextDocument::print()
2355*/
2356#ifndef QT_NO_PRINTER
2357void QTextEdit::print(QPagedPaintDevice *printer) const
2358{
2359 Q_D(const QTextEdit);
2360 d->control->print(printer);
2361}
2362#endif
2363
2364/*! \property QTextEdit::tabChangesFocus
2365 \brief whether \uicontrol Tab changes focus or is accepted as input
2366
2367 In some occasions text edits should not allow the user to input
2368 tabulators or change indentation using the \uicontrol Tab key, as this breaks
2369 the focus chain. The default is false.
2370
2371*/
2372
2373bool QTextEdit::tabChangesFocus() const
2374{
2375 Q_D(const QTextEdit);
2376 return d->tabChangesFocus;
2377}
2378
2379void QTextEdit::setTabChangesFocus(bool b)
2380{
2381 Q_D(QTextEdit);
2382 d->tabChangesFocus = b;
2383}
2384
2385/*!
2386 \property QTextEdit::documentTitle
2387 \brief the title of the document parsed from the text.
2388
2389 By default, for a newly-created, empty document, this property contains
2390 an empty string.
2391*/
2392
2393/*!
2394 \property QTextEdit::lineWrapMode
2395 \brief the line wrap mode
2396
2397 The default mode is WidgetWidth which causes words to be
2398 wrapped at the right edge of the text edit. Wrapping occurs at
2399 whitespace, keeping whole words intact. If you want wrapping to
2400 occur within words use setWordWrapMode(). If you set a wrap mode of
2401 FixedPixelWidth or FixedColumnWidth you should also call
2402 setLineWrapColumnOrWidth() with the width you want.
2403
2404 \sa lineWrapColumnOrWidth
2405*/
2406
2407QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
2408{
2409 Q_D(const QTextEdit);
2410 return d->lineWrap;
2411}
2412
2413void QTextEdit::setLineWrapMode(LineWrapMode wrap)
2414{
2415 Q_D(QTextEdit);
2416 if (d->lineWrap == wrap)
2417 return;
2418 d->lineWrap = wrap;
2419 d->updateDefaultTextOption();
2420 d->relayoutDocument();
2421}
2422
2423/*!
2424 \property QTextEdit::lineWrapColumnOrWidth
2425 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
2426
2427 If the wrap mode is FixedPixelWidth, the value is the number of
2428 pixels from the left edge of the text edit at which text should be
2429 wrapped. If the wrap mode is FixedColumnWidth, the value is the
2430 column number (in character columns) from the left edge of the
2431 text edit at which text should be wrapped.
2432
2433 By default, this property contains a value of 0.
2434
2435 \sa lineWrapMode
2436*/
2437
2438int QTextEdit::lineWrapColumnOrWidth() const
2439{
2440 Q_D(const QTextEdit);
2441 return d->lineWrapColumnOrWidth;
2442}
2443
2444void QTextEdit::setLineWrapColumnOrWidth(int w)
2445{
2446 Q_D(QTextEdit);
2447 d->lineWrapColumnOrWidth = w;
2448 d->relayoutDocument();
2449}
2450
2451/*!
2452 \property QTextEdit::wordWrapMode
2453 \brief the mode QTextEdit will use when wrapping text by words
2454
2455 By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
2456
2457 \sa QTextOption::WrapMode
2458*/
2459
2460QTextOption::WrapMode QTextEdit::wordWrapMode() const
2461{
2462 Q_D(const QTextEdit);
2463 return d->wordWrap;
2464}
2465
2466void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
2467{
2468 Q_D(QTextEdit);
2469 if (mode == d->wordWrap)
2470 return;
2471 d->wordWrap = mode;
2472 d->updateDefaultTextOption();
2473}
2474
2475/*!
2476 Finds the next occurrence of the string, \a exp, using the given
2477 \a options. Returns \c true if \a exp was found and changes the
2478 cursor to select the match; otherwise returns \c false.
2479*/
2480bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
2481{
2482 Q_D(QTextEdit);
2483 return d->control->find(exp, options);
2484}
2485
2486/*!
2487 \fn bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2488
2489 \since 5.13
2490 \overload
2491
2492 Finds the next occurrence, matching the regular expression, \a exp, using the given
2493 \a options.
2494
2495 Returns \c true if a match was found and changes the cursor to select the match;
2496 otherwise returns \c false.
2497
2498 \warning For historical reasons, the case sensitivity option set on
2499 \a exp is ignored. Instead, the \a options are used to determine
2500 if the search is case sensitive or not.
2501*/
2502#if QT_CONFIG(regularexpression)
2503bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2504{
2505 Q_D(QTextEdit);
2506 return d->control->find(exp, options);
2507}
2508#endif
2509
2510/*!
2511 \fn void QTextEdit::copyAvailable(bool yes)
2512
2513 This signal is emitted when text is selected or de-selected in the
2514 text edit.
2515
2516 When text is selected this signal will be emitted with \a yes set
2517 to true. If no text has been selected or if the selected text is
2518 de-selected this signal is emitted with \a yes set to false.
2519
2520 If \a yes is true then copy() can be used to copy the selection to
2521 the clipboard. If \a yes is false then copy() does nothing.
2522
2523 \sa selectionChanged()
2524*/
2525
2526/*!
2527 \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)
2528
2529 This signal is emitted if the current character format has changed, for
2530 example caused by a change of the cursor position.
2531
2532 The new format is \a f.
2533
2534 \sa setCurrentCharFormat()
2535*/
2536
2537/*!
2538 \fn void QTextEdit::selectionChanged()
2539
2540 This signal is emitted whenever the selection changes.
2541
2542 \sa copyAvailable()
2543*/
2544
2545/*!
2546 \fn void QTextEdit::cursorPositionChanged()
2547
2548 This signal is emitted whenever the position of the
2549 cursor changed.
2550*/
2551
2552/*!
2553 \since 4.2
2554
2555 Sets the text edit's \a text. The text can be plain text or HTML
2556 and the text edit will try to guess the right format.
2557
2558 Use setHtml() or setPlainText() directly to avoid text edit's guessing.
2559
2560 \sa toPlainText(), toHtml()
2561*/
2562void QTextEdit::setText(const QString &text)
2563{
2564 Qt::TextFormat format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
2565#ifndef QT_NO_TEXTHTMLPARSER
2566 if (format == Qt::RichText)
2567 setHtml(text);
2568 else
2569#else
2570 Q_UNUSED(format);
2571#endif
2572 setPlainText(text);
2573}
2574
2575
2576/*!
2577 Appends a new paragraph with \a text to the end of the text edit.
2578
2579 \note The new paragraph appended will have the same character format and
2580 block format as the current paragraph, determined by the position of the cursor.
2581
2582 \sa currentCharFormat(), QTextCursor::blockFormat()
2583*/
2584
2585void QTextEdit::append(const QString &text)
2586{
2587 Q_D(QTextEdit);
2588 const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() :
2589 d->control->textCursor().atEnd();
2590 d->control->append(text);
2591 if (atBottom)
2592 d->vbar->setValue(d->vbar->maximum());
2593}
2594
2595/*!
2596 Ensures that the cursor is visible by scrolling the text edit if
2597 necessary.
2598*/
2599void QTextEdit::ensureCursorVisible()
2600{
2601 Q_D(QTextEdit);
2602 d->control->ensureCursorVisible();
2603}
2604
2605/*!
2606 \fn void QTextEdit::textChanged()
2607
2608 This signal is emitted whenever the document's content changes; for
2609 example, when text is inserted or deleted, or when formatting is applied.
2610*/
2611
2612/*!
2613 \fn void QTextEdit::undoAvailable(bool available)
2614
2615 This signal is emitted whenever undo operations become available
2616 (\a available is true) or unavailable (\a available is false).
2617*/
2618
2619/*!
2620 \fn void QTextEdit::redoAvailable(bool available)
2621
2622 This signal is emitted whenever redo operations become available
2623 (\a available is true) or unavailable (\a available is false).
2624*/
2625
2626QT_END_NAMESPACE
2627
2628#include "moc_qtextedit.cpp"
friend class QPainter
QRect viewport() const
Returns the viewport rectangle.
virtual void insertFromMimeData(const QMimeData *source) override
Definition qtextedit.cpp:71
virtual QMimeData * createMimeDataFromSelection() const override
Definition qtextedit.cpp:59
QVariant loadResource(int type, const QUrl &name) override
Definition qtextedit.cpp:78
virtual bool canInsertFromMimeData(const QMimeData *source) const override
Definition qtextedit.cpp:65
QTextEditControl(QObject *parent)
Definition qtextedit.cpp:57
void pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
int horizontalOffset() const
Definition qtextedit_p.h:65
int verticalOffset() const
Definition qtextedit_p.h:67
void createAutoBulletList()
void cursorPositionChanged()
void adjustScrollbars()
void updateDefaultTextOption()
The QTextEdit class provides a widget that is used to edit and display both plain and rich text.
Definition qtextedit.h:30
Combined button and popup list for selecting options.
static QT_BEGIN_NAMESPACE bool shouldEnableInputMethod(QTextEdit *textedit)
Definition qtextedit.cpp:45