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 auto *contextMenuEvent = static_cast<QContextMenuEvent *>(e);
1103 if (contextMenuEvent->reason() == QContextMenuEvent::Keyboard) {
1104 ensureCursorVisible();
1105 const QPoint cursorPos = cursorRect().center();
1106 QContextMenuEvent ce(cursorPos, d->viewport->mapToGlobal(cursorPos), Qt::NoModifier,
1107 contextMenuEvent->device());
1108 ce.setAccepted(e->isAccepted());
1109 const bool result = QAbstractScrollArea::event(&ce);
1110 e->setAccepted(ce.isAccepted());
1111 return result;
1112 }
1113 break;
1114 }
1115#endif // QT_NO_CONTEXTMENU
1116 default:
1117 break;
1118 }
1119 return QAbstractScrollArea::event(e);
1120}
1121
1122/*! \internal
1123*/
1124
1125void QTextEdit::timerEvent(QTimerEvent *e)
1126{
1127 Q_D(QTextEdit);
1128 if (e->timerId() == d->autoScrollTimer.timerId()) {
1129 QRect visible = d->viewport->rect();
1130 QPoint pos;
1131 if (d->inDrag) {
1132 pos = d->autoScrollDragPos;
1133 visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
1134 -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
1135 } else {
1136 const QPoint globalPos = QCursor::pos();
1137 pos = d->viewport->mapFromGlobal(globalPos);
1138 QMouseEvent ev(QEvent::MouseMove, pos, mapTo(topLevelWidget(), pos), globalPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
1139 mouseMoveEvent(&ev);
1140 }
1141 int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
1142 int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
1143 int delta = qMax(deltaX, deltaY);
1144 if (delta >= 0) {
1145 if (delta < 7)
1146 delta = 7;
1147 const auto timeout = std::chrono::milliseconds(4900 / (delta * delta));
1148 d->autoScrollTimer.start(timeout, this);
1149
1150 if (deltaY > 0)
1151 d->vbar->triggerAction(pos.y() < visible.center().y() ?
1152 QAbstractSlider::SliderSingleStepSub
1153 : QAbstractSlider::SliderSingleStepAdd);
1154 if (deltaX > 0)
1155 d->hbar->triggerAction(pos.x() < visible.center().x() ?
1156 QAbstractSlider::SliderSingleStepSub
1157 : QAbstractSlider::SliderSingleStepAdd);
1158 }
1159 }
1160}
1161
1162/*!
1163 Changes the text of the text edit to the string \a text.
1164 Any previous text is removed.
1165
1166 Notes:
1167 \list
1168 \li \a text is interpreted as plain text.
1169 \li The undo/redo history is also cleared.
1170 \li currentCharFormat() is reset, unless textCursor()
1171 is already at the beginning of the document.
1172 \endlist
1173
1174 \sa toPlainText()
1175*/
1176
1177void QTextEdit::setPlainText(const QString &text)
1178{
1179 Q_D(QTextEdit);
1180 d->control->setPlainText(text);
1181 d->preferRichText = false;
1182}
1183
1184/*!
1185 QString QTextEdit::toPlainText() const
1186
1187 Returns the text of the text edit as plain text.
1188
1189 \sa QTextEdit::setPlainText()
1190 */
1191QString QTextEdit::toPlainText() const
1192{
1193 Q_D(const QTextEdit);
1194 return d->control->toPlainText();
1195}
1196
1197/*!
1198 \property QTextEdit::html
1199
1200 This property provides an HTML interface to the text of the text edit.
1201
1202 toHtml() returns the text of the text edit as html.
1203
1204 setHtml() changes the text of the text edit. Any previous text is
1205 removed and the undo/redo history is cleared. The input text is
1206 interpreted as rich text in html format. currentCharFormat() is also
1207 reset, unless textCursor() is already at the beginning of the document.
1208
1209 \note It is the responsibility of the caller to make sure that the
1210 text is correctly decoded when a QString containing HTML is created
1211 and passed to setHtml().
1212
1213 By default, for a newly-created, empty document, this property contains
1214 text to describe an HTML 4.0 document with no body text.
1215
1216 \sa {Supported HTML Subset}, plainText
1217*/
1218
1219#ifndef QT_NO_TEXTHTMLPARSER
1220void QTextEdit::setHtml(const QString &text)
1221{
1222 Q_D(QTextEdit);
1223 d->control->setHtml(text);
1224 d->preferRichText = true;
1225}
1226
1227QString QTextEdit::toHtml() const
1228{
1229 Q_D(const QTextEdit);
1230 return d->control->toHtml();
1231}
1232#endif
1233
1234#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
1235/*!
1236 \property QTextEdit::markdown
1237
1238 This property provides a Markdown interface to the text of the text edit.
1239
1240 \c toMarkdown() returns the text of the text edit as "pure" Markdown,
1241 without any embedded HTML formatting. Some features that QTextDocument
1242 supports (such as the use of specific colors and named fonts) cannot be
1243 expressed in "pure" Markdown, and they will be omitted.
1244
1245 \c setMarkdown() changes the text of the text edit. Any previous text is
1246 removed and the undo/redo history is cleared. The input text is
1247 interpreted as rich text in Markdown format.
1248
1249 Parsing of HTML included in the \a markdown string is handled in the same
1250 way as in \l setHtml; however, Markdown formatting inside HTML blocks is
1251 not supported.
1252
1253 Some features of the parser can be enabled or disabled via the \a features
1254 argument:
1255
1256 \value MarkdownNoHTML
1257 Any HTML tags in the Markdown text will be discarded
1258 \value MarkdownDialectCommonMark
1259 The parser supports only the features standardized by CommonMark
1260 \value MarkdownDialectGitHub
1261 The parser supports the GitHub dialect
1262
1263 The default is \c MarkdownDialectGitHub.
1264
1265 \sa plainText, html, QTextDocument::toMarkdown(), QTextDocument::setMarkdown()
1266 \since 5.14
1267*/
1268#endif
1269
1270#if QT_CONFIG(textmarkdownreader)
1271void QTextEdit::setMarkdown(const QString &markdown)
1272{
1273 Q_D(const QTextEdit);
1274 d->control->setMarkdown(markdown);
1275}
1276#endif
1277
1278#if QT_CONFIG(textmarkdownwriter)
1279QString QTextEdit::toMarkdown(QTextDocument::MarkdownFeatures features) const
1280{
1281 Q_D(const QTextEdit);
1282 return d->control->toMarkdown(features);
1283}
1284#endif
1285
1286/*! \reimp
1287*/
1288void QTextEdit::keyPressEvent(QKeyEvent *e)
1289{
1290 Q_D(QTextEdit);
1291
1292#ifndef QT_NO_SHORTCUT
1293
1294 Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
1295
1296 if (tif & Qt::TextSelectableByKeyboard){
1297 if (e == QKeySequence::SelectPreviousPage) {
1298 e->accept();
1299 d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
1300 return;
1301 } else if (e ==QKeySequence::SelectNextPage) {
1302 e->accept();
1303 d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
1304 return;
1305 }
1306 }
1307 if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
1308 if (e == QKeySequence::MoveToPreviousPage) {
1309 e->accept();
1310 d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
1311 return;
1312 } else if (e == QKeySequence::MoveToNextPage) {
1313 e->accept();
1314 d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
1315 return;
1316 }
1317 }
1318
1319 if (!(tif & Qt::TextEditable)) {
1320 switch (e->key()) {
1321 case Qt::Key_Space:
1322 e->accept();
1323 if (e->modifiers() & Qt::ShiftModifier)
1324 d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
1325 else
1326 d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
1327 break;
1328 default:
1329 d->sendControlEvent(e);
1330 if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
1331 if (e->key() == Qt::Key_Home) {
1332 d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
1333 e->accept();
1334 } else if (e->key() == Qt::Key_End) {
1335 d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
1336 e->accept();
1337 }
1338 }
1339 if (!e->isAccepted()) {
1340 QAbstractScrollArea::keyPressEvent(e);
1341 }
1342 }
1343 return;
1344 }
1345#endif // QT_NO_SHORTCUT
1346
1347 {
1348 QTextCursor cursor = d->control->textCursor();
1349 const QString text = e->text();
1350 if (cursor.atBlockStart()
1351 && (d->autoFormatting & AutoBulletList)
1352 && (text.size() == 1)
1353 && (text.at(0) == u'-' || text.at(0) == u'*')
1354 && (!cursor.currentList())) {
1355
1356 d->createAutoBulletList();
1357 e->accept();
1358 return;
1359 }
1360 }
1361
1362 d->sendControlEvent(e);
1363}
1364
1365/*! \reimp
1366*/
1367void QTextEdit::keyReleaseEvent(QKeyEvent *e)
1368{
1369 Q_D(QTextEdit);
1370 if (!isReadOnly())
1371 d->handleSoftwareInputPanel();
1372 e->ignore();
1373}
1374
1375/*!
1376 Loads the resource specified by the given \a type and \a name.
1377
1378 This function is an extension of QTextDocument::loadResource().
1379
1380 \sa QTextDocument::loadResource()
1381*/
1382QVariant QTextEdit::loadResource(int type, const QUrl &name)
1383{
1384 Q_UNUSED(type);
1385 Q_UNUSED(name);
1386 return QVariant();
1387}
1388
1389/*! \reimp
1390*/
1391void QTextEdit::resizeEvent(QResizeEvent *e)
1392{
1393 Q_D(QTextEdit);
1394
1395 if (d->lineWrap == NoWrap) {
1396 QTextDocument *doc = d->control->document();
1397 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1398
1399 if (!doc->pageSize().isNull()
1400 && alignmentProperty.userType() == QMetaType::Bool
1401 && !alignmentProperty.toBool()) {
1402
1403 d->adjustScrollbars();
1404 return;
1405 }
1406 }
1407
1408 if (d->lineWrap != FixedPixelWidth
1409 && e->oldSize().width() != e->size().width())
1410 d->relayoutDocument();
1411 else
1412 d->adjustScrollbars();
1413}
1414
1416{
1417 QTextDocument *doc = control->document();
1418 QAbstractTextDocumentLayout *layout = doc->documentLayout();
1419
1420 if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {
1421 if (lineWrap == QTextEdit::FixedColumnWidth)
1422 tlayout->setFixedColumnWidth(lineWrapColumnOrWidth);
1423 else
1424 tlayout->setFixedColumnWidth(-1);
1425 }
1426
1427 QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout);
1428 QSize lastUsedSize;
1429 if (tlayout)
1430 lastUsedSize = tlayout->dynamicDocumentSize().toSize();
1431 else
1432 lastUsedSize = layout->documentSize().toSize();
1433
1434 // ignore calls to adjustScrollbars caused by an emission of the
1435 // usedSizeChanged() signal in the layout, as we're calling it
1436 // later on our own anyway (or deliberately not) .
1437 const bool oldIgnoreScrollbarAdjustment = ignoreAutomaticScrollbarAdjustment;
1438 ignoreAutomaticScrollbarAdjustment = true;
1439
1440 int width = viewport->width();
1441 if (lineWrap == QTextEdit::FixedPixelWidth)
1442 width = lineWrapColumnOrWidth;
1443 else if (lineWrap == QTextEdit::NoWrap) {
1444 QVariant alignmentProperty = doc->documentLayout()->property("contentHasAlignment");
1445 if (alignmentProperty.userType() == QMetaType::Bool && !alignmentProperty.toBool()) {
1446
1447 width = 0;
1448 }
1449 }
1450
1451 doc->setPageSize(QSize(width, -1));
1452 if (tlayout)
1453 tlayout->ensureLayouted(verticalOffset() + viewport->height());
1454
1455 ignoreAutomaticScrollbarAdjustment = oldIgnoreScrollbarAdjustment;
1456
1457 QSize usedSize;
1458 if (tlayout)
1459 usedSize = tlayout->dynamicDocumentSize().toSize();
1460 else
1461 usedSize = layout->documentSize().toSize();
1462
1463 // this is an obscure situation in the layout that can happen:
1464 // if a character at the end of a line is the tallest one and therefore
1465 // influencing the total height of the line and the line right below it
1466 // is always taller though, then it can happen that if due to line breaking
1467 // that tall character wraps into the lower line the document not only shrinks
1468 // horizontally (causing the character to wrap in the first place) but also
1469 // vertically, because the original line is now smaller and the one below kept
1470 // its size. So a layout with less width _can_ take up less vertical space, too.
1471 // If the wider case causes a vertical scroll bar to appear and the narrower one
1472 // (narrower because the vertical scroll bar takes up horizontal space)) to disappear
1473 // again then we have an endless loop, as adjustScrollbars sets new ranges on the
1474 // scroll bars, the QAbstractScrollArea will find out about it and try to show/hide
1475 // the scroll bars again. That's why we try to detect this case here and break out.
1476 //
1477 // (if you change this please also check the layoutingLoop() testcase in
1478 // QTextEdit's autotests)
1479 if (lastUsedSize.isValid()
1480 && !vbar->isHidden()
1481 && viewport->width() < lastUsedSize.width()
1482 && usedSize.height() < lastUsedSize.height()
1483 && usedSize.height() <= viewport->height())
1484 return;
1485
1487}
1488
1489void QTextEditPrivate::paint(QPainter *p, QPaintEvent *e)
1490{
1491 const int xOffset = horizontalOffset();
1492 const int yOffset = verticalOffset();
1493
1494 QRect r = e->rect();
1495 p->translate(-xOffset, -yOffset);
1496 r.translate(xOffset, yOffset);
1497
1498 QTextDocument *doc = control->document();
1499 QTextDocumentLayout *layout = qobject_cast<QTextDocumentLayout *>(doc->documentLayout());
1500
1501 // the layout might need to expand the root frame to
1502 // the viewport if NoWrap is set
1503 if (layout)
1504 layout->setViewport(viewport->rect());
1505
1506 control->drawContents(p, r, q_func());
1507
1508 if (layout)
1509 layout->setViewport(QRect());
1510
1511 if (!placeholderText.isEmpty() && doc->isEmpty() && !control->isPreediting()) {
1512 const QColor col = control->palette().placeholderText().color();
1513 p->setPen(col);
1514 const int margin = int(doc->documentMargin());
1515 QRectF boundingRect = layout ? layout->frameBoundingRect(doc->rootFrame()) : viewport->rect();
1516 p->drawText(boundingRect.adjusted(margin, margin, -margin, -margin),
1517 Qt::AlignTop | Qt::TextWordWrap,
1518 placeholderText);
1519 }
1520}
1521
1522/*! \fn void QTextEdit::paintEvent(QPaintEvent *event)
1523
1524This event handler can be reimplemented in a subclass to receive paint events passed in \a event.
1525It is usually unnecessary to reimplement this function in a subclass of QTextEdit.
1526
1527\note If you create a QPainter, it must operate on the \l{QAbstractScrollArea::}{viewport()}.
1528
1529\warning The underlying text document must not be modified from within a reimplementation
1530of this function.
1531*/
1532void QTextEdit::paintEvent(QPaintEvent *e)
1533{
1534 Q_D(QTextEdit);
1535 QPainter p(d->viewport);
1536 d->paint(&p, e);
1537}
1538
1540{
1541 QTextDocument *doc = control->document();
1542
1543 QTextOption opt = doc->defaultTextOption();
1544 QTextOption::WrapMode oldWrapMode = opt.wrapMode();
1545
1546 if (lineWrap == QTextEdit::NoWrap)
1547 opt.setWrapMode(QTextOption::NoWrap);
1548 else
1549 opt.setWrapMode(wordWrap);
1550
1551 if (opt.wrapMode() != oldWrapMode)
1552 doc->setDefaultTextOption(opt);
1553}
1554
1555/*! \reimp
1556*/
1557void QTextEdit::mousePressEvent(QMouseEvent *e)
1558{
1559 Q_D(QTextEdit);
1560 d->sendControlEvent(e);
1561}
1562
1563/*! \reimp
1564*/
1565void QTextEdit::mouseMoveEvent(QMouseEvent *e)
1566{
1567 Q_D(QTextEdit);
1568 d->inDrag = false; // paranoia
1569 const QPoint pos = e->position().toPoint();
1570 d->sendControlEvent(e);
1571 if (!(e->buttons() & Qt::LeftButton))
1572 return;
1573 if (e->source() == Qt::MouseEventNotSynthesized) {
1574 const QRect visible = d->viewport->rect();
1575 if (visible.contains(pos))
1576 d->autoScrollTimer.stop();
1577 else if (!d->autoScrollTimer.isActive())
1578 d->autoScrollTimer.start(100, this);
1579 }
1580}
1581
1582/*! \reimp
1583*/
1584void QTextEdit::mouseReleaseEvent(QMouseEvent *e)
1585{
1586 Q_D(QTextEdit);
1587 d->sendControlEvent(e);
1588 if (e->source() == Qt::MouseEventNotSynthesized && d->autoScrollTimer.isActive()) {
1589 d->autoScrollTimer.stop();
1590 ensureCursorVisible();
1591 }
1592 if (!isReadOnly() && rect().contains(e->position().toPoint()))
1593 d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
1594 d->clickCausedFocus = 0;
1595}
1596
1597/*! \reimp
1598*/
1599void QTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
1600{
1601 Q_D(QTextEdit);
1602 d->sendControlEvent(e);
1603}
1604
1605/*! \reimp
1606*/
1607bool QTextEdit::focusNextPrevChild(bool next)
1608{
1609 Q_D(const QTextEdit);
1610 if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
1611 return false;
1612 return QAbstractScrollArea::focusNextPrevChild(next);
1613}
1614
1615#ifndef QT_NO_CONTEXTMENU
1616/*!
1617 \fn void QTextEdit::contextMenuEvent(QContextMenuEvent *event)
1618
1619 Shows the standard context menu created with createStandardContextMenu().
1620
1621 If you do not want the text edit to have a context menu, you can set
1622 its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
1623 customize the context menu, reimplement this function. If you want
1624 to extend the standard context menu, reimplement this function, call
1625 createStandardContextMenu() and extend the menu returned.
1626
1627 Information about the event is passed in the \a event object.
1628
1629 \snippet code/src_gui_widgets_qtextedit.cpp 0
1630*/
1631void QTextEdit::contextMenuEvent(QContextMenuEvent *e)
1632{
1633 Q_D(QTextEdit);
1634 d->sendControlEvent(e);
1635}
1636#endif // QT_NO_CONTEXTMENU
1637
1638#if QT_CONFIG(draganddrop)
1639/*! \reimp
1640*/
1641void QTextEdit::dragEnterEvent(QDragEnterEvent *e)
1642{
1643 Q_D(QTextEdit);
1644 d->inDrag = true;
1645 d->sendControlEvent(e);
1646}
1647
1648/*! \reimp
1649*/
1650void QTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
1651{
1652 Q_D(QTextEdit);
1653 d->inDrag = false;
1654 d->autoScrollTimer.stop();
1655 d->sendControlEvent(e);
1656}
1657
1658/*! \reimp
1659*/
1660void QTextEdit::dragMoveEvent(QDragMoveEvent *e)
1661{
1662 Q_D(QTextEdit);
1663 d->autoScrollDragPos = e->position().toPoint();
1664 if (!d->autoScrollTimer.isActive())
1665 d->autoScrollTimer.start(100, this);
1666 d->sendControlEvent(e);
1667}
1668
1669/*! \reimp
1670*/
1671void QTextEdit::dropEvent(QDropEvent *e)
1672{
1673 Q_D(QTextEdit);
1674 d->inDrag = false;
1675 d->autoScrollTimer.stop();
1676 d->sendControlEvent(e);
1677}
1678
1679#endif // QT_CONFIG(draganddrop)
1680
1681/*! \reimp
1682 */
1683void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
1684{
1685 Q_D(QTextEdit);
1686 d->sendControlEvent(e);
1687 const bool emptyEvent = e->preeditString().isEmpty() && e->commitString().isEmpty()
1688 && e->attributes().isEmpty();
1689 if (emptyEvent)
1690 return;
1691 ensureCursorVisible();
1692}
1693
1694/*!\reimp
1695*/
1696void QTextEdit::scrollContentsBy(int dx, int dy)
1697{
1698 Q_D(QTextEdit);
1699 if (isRightToLeft())
1700 dx = -dx;
1701 d->viewport->scroll(dx, dy);
1702 QGuiApplication::inputMethod()->update(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
1703}
1704
1705/*!\reimp
1706*/
1707QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
1708{
1709 return inputMethodQuery(property, QVariant());
1710}
1711
1712/*!\internal
1713 */
1714QVariant QTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argument) const
1715{
1716 Q_D(const QTextEdit);
1717 switch (query) {
1718 case Qt::ImEnabled:
1719 return isEnabled() && !isReadOnly();
1720 case Qt::ImHints:
1721 case Qt::ImInputItemClipRectangle:
1722 return QWidget::inputMethodQuery(query);
1723 case Qt::ImReadOnly:
1724 return isReadOnly();
1725 default:
1726 break;
1727 }
1728
1729 const QPointF offset = QPointF(-d->horizontalOffset(), -d->verticalOffset())
1730 + d->viewport->mapTo(this, QPointF());
1731 switch (argument.userType()) {
1732 case QMetaType::QRectF:
1733 argument = argument.toRectF().translated(-offset);
1734 break;
1735 case QMetaType::QPointF:
1736 argument = argument.toPointF() - offset;
1737 break;
1738 case QMetaType::QRect:
1739 argument = argument.toRect().translated(-offset.toPoint());
1740 break;
1741 case QMetaType::QPoint:
1742 argument = argument.toPoint() - offset;
1743 break;
1744 default:
1745 break;
1746 }
1747
1748 const QVariant v = d->control->inputMethodQuery(query, argument);
1749 switch (v.userType()) {
1750 case QMetaType::QRectF:
1751 return v.toRectF().translated(offset);
1752 case QMetaType::QPointF:
1753 return v.toPointF() + offset;
1754 case QMetaType::QRect:
1755 return v.toRect().translated(offset.toPoint());
1756 case QMetaType::QPoint:
1757 return v.toPoint() + offset.toPoint();
1758 default:
1759 break;
1760 }
1761 return v;
1762}
1763
1764/*! \reimp
1765*/
1766void QTextEdit::focusInEvent(QFocusEvent *e)
1767{
1768 Q_D(QTextEdit);
1769 if (e->reason() == Qt::MouseFocusReason) {
1770 d->clickCausedFocus = 1;
1771 }
1772 QAbstractScrollArea::focusInEvent(e);
1773 d->sendControlEvent(e);
1774}
1775
1776/*! \reimp
1777*/
1778void QTextEdit::focusOutEvent(QFocusEvent *e)
1779{
1780 Q_D(QTextEdit);
1781 QAbstractScrollArea::focusOutEvent(e);
1782 d->sendControlEvent(e);
1783}
1784
1785/*! \reimp
1786*/
1787void QTextEdit::showEvent(QShowEvent *)
1788{
1789 Q_D(QTextEdit);
1790 if (!d->anchorToScrollToWhenVisible.isEmpty()) {
1791 scrollToAnchor(d->anchorToScrollToWhenVisible);
1792 d->anchorToScrollToWhenVisible.clear();
1793 d->showCursorOnInitialShow = false;
1794 } else if (d->showCursorOnInitialShow) {
1795 d->showCursorOnInitialShow = false;
1796 ensureCursorVisible();
1797 }
1798}
1799
1800/*! \reimp
1801*/
1802void QTextEdit::changeEvent(QEvent *e)
1803{
1804 Q_D(QTextEdit);
1805 QAbstractScrollArea::changeEvent(e);
1806 if (e->type() == QEvent::ApplicationFontChange
1807 || e->type() == QEvent::FontChange) {
1808 d->control->document()->setDefaultFont(font());
1809 } else if (e->type() == QEvent::ActivationChange) {
1810 if (!isActiveWindow())
1811 d->autoScrollTimer.stop();
1812 } else if (e->type() == QEvent::EnabledChange) {
1813 e->setAccepted(isEnabled());
1814 d->control->setPalette(palette());
1815 d->sendControlEvent(e);
1816 } else if (e->type() == QEvent::PaletteChange) {
1817 d->control->setPalette(palette());
1818 } else if (e->type() == QEvent::LayoutDirectionChange) {
1819 d->sendControlEvent(e);
1820 }
1821}
1822
1823/*! \reimp
1824*/
1825#if QT_CONFIG(wheelevent)
1826void QTextEdit::wheelEvent(QWheelEvent *e)
1827{
1828 Q_D(QTextEdit);
1829 if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
1830 if (e->modifiers() & Qt::ControlModifier) {
1831 float delta = e->angleDelta().y() / 120.f;
1832 zoomInF(delta);
1833 return;
1834 }
1835 }
1836 QAbstractScrollArea::wheelEvent(e);
1837 updateMicroFocus();
1838}
1839#endif
1840
1841#ifndef QT_NO_CONTEXTMENU
1842/*! This function creates the standard context menu which is shown
1843 when the user clicks on the text edit with the right mouse
1844 button. It is called from the default contextMenuEvent() handler.
1845 The popup menu's ownership is transferred to the caller.
1846
1847 We recommend that you use the createStandardContextMenu(QPoint) version instead
1848 which will enable the actions that are sensitive to where the user clicked.
1849*/
1850
1851QMenu *QTextEdit::createStandardContextMenu()
1852{
1853 Q_D(QTextEdit);
1854 return d->control->createStandardContextMenu(QPointF(), this);
1855}
1856
1857/*!
1858 \since 4.4
1859 This function creates the standard context menu which is shown
1860 when the user clicks on the text edit with the right mouse
1861 button. It is called from the default contextMenuEvent() handler
1862 and it takes the \a position in document coordinates where the mouse click was.
1863 This can enable actions that are sensitive to the position where the user clicked.
1864 The popup menu's ownership is transferred to the caller.
1865*/
1866
1867QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
1868{
1869 Q_D(QTextEdit);
1870 return d->control->createStandardContextMenu(position, this);
1871}
1872#endif // QT_NO_CONTEXTMENU
1873
1874/*!
1875 returns a QTextCursor at position \a pos (in viewport coordinates).
1876*/
1877QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
1878{
1879 Q_D(const QTextEdit);
1880 return d->control->cursorForPosition(d->mapToContents(pos));
1881}
1882
1883/*!
1884 returns a rectangle (in viewport coordinates) that includes the
1885 \a cursor.
1886 */
1887QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
1888{
1889 Q_D(const QTextEdit);
1890 if (cursor.isNull())
1891 return QRect();
1892
1893 QRect r = d->control->cursorRect(cursor).toRect();
1894 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1895 return r;
1896}
1897
1898/*!
1899 returns a rectangle (in viewport coordinates) that includes the
1900 cursor of the text edit.
1901 */
1902QRect QTextEdit::cursorRect() const
1903{
1904 Q_D(const QTextEdit);
1905 QRect r = d->control->cursorRect().toRect();
1906 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1907 return r;
1908}
1909
1910
1911/*!
1912 Returns the reference of the anchor at position \a pos, or an
1913 empty string if no anchor exists at that point.
1914*/
1915QString QTextEdit::anchorAt(const QPoint& pos) const
1916{
1917 Q_D(const QTextEdit);
1918 return d->control->anchorAt(d->mapToContents(pos));
1919}
1920
1921/*!
1922 \property QTextEdit::overwriteMode
1923 \since 4.1
1924 \brief whether text entered by the user will overwrite existing text
1925
1926 As with many text editors, the text editor widget can be configured
1927 to insert or overwrite existing text with new text entered by the user.
1928
1929 If this property is \c true, existing text is overwritten, character-for-character
1930 by new text; otherwise, text is inserted at the cursor position, displacing
1931 existing text.
1932
1933 By default, this property is \c false (new text does not overwrite existing text).
1934*/
1935
1936bool QTextEdit::overwriteMode() const
1937{
1938 Q_D(const QTextEdit);
1939 return d->control->overwriteMode();
1940}
1941
1942void QTextEdit::setOverwriteMode(bool overwrite)
1943{
1944 Q_D(QTextEdit);
1945 d->control->setOverwriteMode(overwrite);
1946}
1947
1948/*!
1949 \property QTextEdit::tabStopDistance
1950 \brief the tab stop distance in pixels
1951 \since 5.10
1952
1953 By default, this property contains a value of 80 pixels.
1954
1955 Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
1956 of the QChar::VisualTabCharacter character, otherwise the tab-character
1957 will be drawn incompletely.
1958
1959 \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
1960*/
1961
1962qreal QTextEdit::tabStopDistance() const
1963{
1964 Q_D(const QTextEdit);
1965 return d->control->document()->defaultTextOption().tabStopDistance();
1966}
1967
1968void QTextEdit::setTabStopDistance(qreal distance)
1969{
1970 Q_D(QTextEdit);
1971 QTextOption opt = d->control->document()->defaultTextOption();
1972 if (opt.tabStopDistance() == distance || distance < 0)
1973 return;
1974 opt.setTabStopDistance(distance);
1975 d->control->document()->setDefaultTextOption(opt);
1976}
1977
1978/*!
1979 \since 4.2
1980 \property QTextEdit::cursorWidth
1981
1982 This property specifies the width of the cursor in pixels. The default value is 1.
1983*/
1984int QTextEdit::cursorWidth() const
1985{
1986 Q_D(const QTextEdit);
1987 return d->control->cursorWidth();
1988}
1989
1990void QTextEdit::setCursorWidth(int width)
1991{
1992 Q_D(QTextEdit);
1993 d->control->setCursorWidth(width);
1994}
1995
1996/*!
1997 \property QTextEdit::acceptRichText
1998 \brief whether the text edit accepts rich text insertions by the user
1999 \since 4.1
2000
2001 When this property is set to false text edit will accept only
2002 plain text input from the user. For example through clipboard or drag and drop.
2003
2004 This property's default is true.
2005*/
2006
2007bool QTextEdit::acceptRichText() const
2008{
2009 Q_D(const QTextEdit);
2010 return d->control->acceptRichText();
2011}
2012
2013void QTextEdit::setAcceptRichText(bool accept)
2014{
2015 Q_D(QTextEdit);
2016 d->control->setAcceptRichText(accept);
2017}
2018
2019/*!
2020 \class QTextEdit::ExtraSelection
2021 \since 4.2
2022 \inmodule QtWidgets
2023
2024 \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
2025 character format for a given selection in a document.
2026*/
2027
2028/*!
2029 \variable QTextEdit::ExtraSelection::cursor
2030 A cursor that contains a selection in a QTextDocument
2031*/
2032
2033/*!
2034 \variable QTextEdit::ExtraSelection::format
2035 A format that is used to specify a foreground or background brush/color
2036 for the selection.
2037*/
2038
2039/*!
2040 \since 4.2
2041 This function allows temporarily marking certain regions in the document
2042 with a given color, specified as \a selections. This can be useful for
2043 example in a programming editor to mark a whole line of text with a given
2044 background color to indicate the existence of a breakpoint.
2045
2046 \sa QTextEdit::ExtraSelection, extraSelections()
2047*/
2048void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
2049{
2050 Q_D(QTextEdit);
2051 d->control->setExtraSelections(selections);
2052}
2053
2054/*!
2055 \since 4.2
2056 Returns previously set extra selections.
2057
2058 \sa setExtraSelections()
2059*/
2060QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
2061{
2062 Q_D(const QTextEdit);
2063 return d->control->extraSelections();
2064}
2065
2066/*!
2067 This function returns a new MIME data object to represent the contents
2068 of the text edit's current selection. It is called when the selection needs
2069 to be encapsulated into a new QMimeData object; for example, when a drag
2070 and drop operation is started, or when data is copied to the clipboard.
2071
2072 If you reimplement this function, note that the ownership of the returned
2073 QMimeData object is passed to the caller. The selection can be retrieved
2074 by using the textCursor() function.
2075*/
2076QMimeData *QTextEdit::createMimeDataFromSelection() const
2077{
2078 Q_D(const QTextEdit);
2079 return d->control->QWidgetTextControl::createMimeDataFromSelection();
2080}
2081
2082/*!
2083 This function returns \c true if the contents of the MIME data object, specified
2084 by \a source, can be decoded and inserted into the document. It is called
2085 for example when during a drag operation the mouse enters this widget and it
2086 is necessary to determine whether it is possible to accept the drag and drop
2087 operation.
2088
2089 Reimplement this function to enable drag and drop support for additional MIME types.
2090 */
2091bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
2092{
2093 Q_D(const QTextEdit);
2094 return d->control->QWidgetTextControl::canInsertFromMimeData(source);
2095}
2096
2097/*!
2098 This function inserts the contents of the MIME data object, specified
2099 by \a source, into the text edit at the current cursor position. It is
2100 called whenever text is inserted as the result of a clipboard paste
2101 operation, or when the text edit accepts data from a drag and drop
2102 operation.
2103
2104 Reimplement this function to enable drag and drop support for additional MIME types.
2105 */
2106void QTextEdit::insertFromMimeData(const QMimeData *source)
2107{
2108 Q_D(QTextEdit);
2109 d->control->QWidgetTextControl::insertFromMimeData(source);
2110}
2111
2112/*!
2113 \property QTextEdit::readOnly
2114 \brief whether the text edit is read-only
2115
2116 In a read-only text edit the user can only navigate through the
2117 text and select text; modifying the text is not possible.
2118
2119 This property's default is false.
2120*/
2121
2122bool QTextEdit::isReadOnly() const
2123{
2124 Q_D(const QTextEdit);
2125 return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
2126}
2127
2128void QTextEdit::setReadOnly(bool ro)
2129{
2130 Q_D(QTextEdit);
2131 Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
2132 if (ro) {
2133 flags = Qt::TextSelectableByMouse;
2134#if QT_CONFIG(textbrowser)
2135 if (qobject_cast<QTextBrowser *>(this))
2136 flags |= Qt::TextBrowserInteraction;
2137#endif
2138 } else {
2139 flags = Qt::TextEditorInteraction;
2140 }
2141 d->control->setTextInteractionFlags(flags);
2142 setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
2143 QEvent event(QEvent::ReadOnlyChange);
2144 QCoreApplication::sendEvent(this, &event);
2145}
2146
2147/*!
2148 \property QTextEdit::textInteractionFlags
2149 \since 4.2
2150
2151 Specifies how the widget should interact with user input.
2152
2153 The default value depends on whether the QTextEdit is read-only
2154 or editable, and whether it is a QTextBrowser or not.
2155*/
2156
2157void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
2158{
2159 Q_D(QTextEdit);
2160 d->control->setTextInteractionFlags(flags);
2161}
2162
2163Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
2164{
2165 Q_D(const QTextEdit);
2166 return d->control->textInteractionFlags();
2167}
2168
2169/*!
2170 Merges the properties specified in \a modifier into the current character
2171 format by calling QTextCursor::mergeCharFormat on the editor's cursor.
2172 If the editor has a selection then the properties of \a modifier are
2173 directly applied to the selection.
2174
2175 \sa QTextCursor::mergeCharFormat()
2176 */
2177void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
2178{
2179 Q_D(QTextEdit);
2180 d->control->mergeCurrentCharFormat(modifier);
2181}
2182
2183/*!
2184 Sets the char format that is be used when inserting new text to \a
2185 format by calling QTextCursor::setCharFormat() on the editor's
2186 cursor. If the editor has a selection then the char format is
2187 directly applied to the selection.
2188 */
2189void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
2190{
2191 Q_D(QTextEdit);
2192 d->control->setCurrentCharFormat(format);
2193}
2194
2195/*!
2196 Returns the char format that is used when inserting new text.
2197 */
2198QTextCharFormat QTextEdit::currentCharFormat() const
2199{
2200 Q_D(const QTextEdit);
2201 return d->control->currentCharFormat();
2202}
2203
2204/*!
2205 \property QTextEdit::autoFormatting
2206 \brief the enabled set of auto formatting features
2207
2208 The value can be any combination of the values in the
2209 AutoFormattingFlag enum. The default is AutoNone. Choose
2210 AutoAll to enable all automatic formatting.
2211
2212 Currently, the only automatic formatting feature provided is
2213 AutoBulletList; future versions of Qt may offer more.
2214*/
2215
2216QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
2217{
2218 Q_D(const QTextEdit);
2219 return d->autoFormatting;
2220}
2221
2222void QTextEdit::setAutoFormatting(AutoFormatting features)
2223{
2224 Q_D(QTextEdit);
2225 d->autoFormatting = features;
2226}
2227
2228/*!
2229 Convenience slot that inserts \a text at the current
2230 cursor position.
2231
2232 It is equivalent to
2233
2234 \snippet code/src_gui_widgets_qtextedit.cpp 1
2235 */
2236void QTextEdit::insertPlainText(const QString &text)
2237{
2238 Q_D(QTextEdit);
2239 d->control->insertPlainText(text);
2240}
2241
2242/*!
2243 Convenience slot that inserts \a text which is assumed to be of
2244 html formatting at the current cursor position.
2245
2246 It is equivalent to:
2247
2248 \snippet code/src_gui_widgets_qtextedit.cpp 2
2249
2250 \note When using this function with a style sheet, the style sheet will
2251 only apply to the current block in the document. In order to apply a style
2252 sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
2253 instead.
2254 */
2255#ifndef QT_NO_TEXTHTMLPARSER
2256void QTextEdit::insertHtml(const QString &text)
2257{
2258 Q_D(QTextEdit);
2259 d->control->insertHtml(text);
2260}
2261#endif // QT_NO_TEXTHTMLPARSER
2262
2263/*!
2264 Scrolls the text edit so that the anchor with the given \a name is
2265 visible; does nothing if the \a name is empty, or is already
2266 visible, or isn't found.
2267*/
2268void QTextEdit::scrollToAnchor(const QString &name)
2269{
2270 Q_D(QTextEdit);
2271 if (name.isEmpty())
2272 return;
2273
2274 if (!isVisible()) {
2275 d->anchorToScrollToWhenVisible = name;
2276 return;
2277 }
2278
2279 QPointF p = d->control->anchorPosition(name);
2280 const int newPosition = qRound(p.y());
2281 if ( d->vbar->maximum() < newPosition )
2282 d->adjustScrollbars();
2283 d->vbar->setValue(newPosition);
2284}
2285
2286/*!
2287 Zooms in on the text by making the base font size \a range
2288 points larger and recalculating all font sizes to be the new size.
2289 This does not change the size of any images.
2290
2291 \sa zoomOut()
2292*/
2293void QTextEdit::zoomIn(int range)
2294{
2295 zoomInF(range);
2296}
2297
2298/*!
2299 Zooms out on the text by making the base font size \a range points
2300 smaller and recalculating all font sizes to be the new size. This
2301 does not change the size of any images.
2302
2303 \sa zoomIn()
2304*/
2305void QTextEdit::zoomOut(int range)
2306{
2307 zoomInF(-range);
2308}
2309
2310/*!
2311 \internal
2312*/
2313void QTextEdit::zoomInF(float range)
2314{
2315 if (range == 0.f)
2316 return;
2317 QFont f = font();
2318 const float newSize = f.pointSizeF() + range;
2319 if (newSize <= 0)
2320 return;
2321 f.setPointSizeF(newSize);
2322 setFont(f);
2323}
2324
2325/*!
2326 \since 4.2
2327 Moves the cursor by performing the given \a operation.
2328
2329 If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
2330 This is the same effect that the user achieves when they hold down the Shift key
2331 and move the cursor with the cursor keys.
2332
2333 \sa QTextCursor::movePosition()
2334*/
2335void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
2336{
2337 Q_D(QTextEdit);
2338 d->control->moveCursor(operation, mode);
2339}
2340
2341/*!
2342 \since 4.2
2343 Returns whether text can be pasted from the clipboard into the textedit.
2344*/
2345bool QTextEdit::canPaste() const
2346{
2347 Q_D(const QTextEdit);
2348 return d->control->canPaste();
2349}
2350
2351/*!
2352 \since 4.3
2353 Convenience function to print the text edit's document to the given \a printer. This
2354 is equivalent to calling the print method on the document directly except that this
2355 function also supports QPrinter::Selection as print range.
2356
2357 \sa QTextDocument::print()
2358*/
2359#ifndef QT_NO_PRINTER
2360void QTextEdit::print(QPagedPaintDevice *printer) const
2361{
2362 Q_D(const QTextEdit);
2363 d->control->print(printer);
2364}
2365#endif
2366
2367/*! \property QTextEdit::tabChangesFocus
2368 \brief whether \uicontrol Tab changes focus or is accepted as input
2369
2370 In some occasions text edits should not allow the user to input
2371 tabulators or change indentation using the \uicontrol Tab key, as this breaks
2372 the focus chain. The default is false.
2373
2374*/
2375
2376bool QTextEdit::tabChangesFocus() const
2377{
2378 Q_D(const QTextEdit);
2379 return d->tabChangesFocus;
2380}
2381
2382void QTextEdit::setTabChangesFocus(bool b)
2383{
2384 Q_D(QTextEdit);
2385 d->tabChangesFocus = b;
2386}
2387
2388/*!
2389 \property QTextEdit::documentTitle
2390 \brief the title of the document parsed from the text.
2391
2392 By default, for a newly-created, empty document, this property contains
2393 an empty string.
2394*/
2395
2396/*!
2397 \property QTextEdit::lineWrapMode
2398 \brief the line wrap mode
2399
2400 The default mode is WidgetWidth which causes words to be
2401 wrapped at the right edge of the text edit. Wrapping occurs at
2402 whitespace, keeping whole words intact. If you want wrapping to
2403 occur within words use setWordWrapMode(). If you set a wrap mode of
2404 FixedPixelWidth or FixedColumnWidth you should also call
2405 setLineWrapColumnOrWidth() with the width you want.
2406
2407 \sa lineWrapColumnOrWidth
2408*/
2409
2410QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
2411{
2412 Q_D(const QTextEdit);
2413 return d->lineWrap;
2414}
2415
2416void QTextEdit::setLineWrapMode(LineWrapMode wrap)
2417{
2418 Q_D(QTextEdit);
2419 if (d->lineWrap == wrap)
2420 return;
2421 d->lineWrap = wrap;
2422 d->updateDefaultTextOption();
2423 d->relayoutDocument();
2424}
2425
2426/*!
2427 \property QTextEdit::lineWrapColumnOrWidth
2428 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
2429
2430 If the wrap mode is FixedPixelWidth, the value is the number of
2431 pixels from the left edge of the text edit at which text should be
2432 wrapped. If the wrap mode is FixedColumnWidth, the value is the
2433 column number (in character columns) from the left edge of the
2434 text edit at which text should be wrapped.
2435
2436 By default, this property contains a value of 0.
2437
2438 \sa lineWrapMode
2439*/
2440
2441int QTextEdit::lineWrapColumnOrWidth() const
2442{
2443 Q_D(const QTextEdit);
2444 return d->lineWrapColumnOrWidth;
2445}
2446
2447void QTextEdit::setLineWrapColumnOrWidth(int w)
2448{
2449 Q_D(QTextEdit);
2450 d->lineWrapColumnOrWidth = w;
2451 d->relayoutDocument();
2452}
2453
2454/*!
2455 \property QTextEdit::wordWrapMode
2456 \brief the mode QTextEdit will use when wrapping text by words
2457
2458 By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
2459
2460 \sa QTextOption::WrapMode
2461*/
2462
2463QTextOption::WrapMode QTextEdit::wordWrapMode() const
2464{
2465 Q_D(const QTextEdit);
2466 return d->wordWrap;
2467}
2468
2469void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
2470{
2471 Q_D(QTextEdit);
2472 if (mode == d->wordWrap)
2473 return;
2474 d->wordWrap = mode;
2475 d->updateDefaultTextOption();
2476}
2477
2478/*!
2479 Finds the next occurrence of the string, \a exp, using the given
2480 \a options. Returns \c true if \a exp was found and changes the
2481 cursor to select the match; otherwise returns \c false.
2482*/
2483bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
2484{
2485 Q_D(QTextEdit);
2486 return d->control->find(exp, options);
2487}
2488
2489/*!
2490 \fn bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2491
2492 \since 5.13
2493 \overload
2494
2495 Finds the next occurrence, matching the regular expression, \a exp, using the given
2496 \a options.
2497
2498 Returns \c true if a match was found and changes the cursor to select the match;
2499 otherwise returns \c false.
2500
2501 \warning For historical reasons, the case sensitivity option set on
2502 \a exp is ignored. Instead, the \a options are used to determine
2503 if the search is case sensitive or not.
2504*/
2505#if QT_CONFIG(regularexpression)
2506bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2507{
2508 Q_D(QTextEdit);
2509 return d->control->find(exp, options);
2510}
2511#endif
2512
2513/*!
2514 \fn void QTextEdit::copyAvailable(bool yes)
2515
2516 This signal is emitted when text is selected or de-selected in the
2517 text edit.
2518
2519 When text is selected this signal will be emitted with \a yes set
2520 to true. If no text has been selected or if the selected text is
2521 de-selected this signal is emitted with \a yes set to false.
2522
2523 If \a yes is true then copy() can be used to copy the selection to
2524 the clipboard. If \a yes is false then copy() does nothing.
2525
2526 \sa selectionChanged()
2527*/
2528
2529/*!
2530 \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)
2531
2532 This signal is emitted if the current character format has changed, for
2533 example caused by a change of the cursor position.
2534
2535 The new format is \a f.
2536
2537 \sa setCurrentCharFormat()
2538*/
2539
2540/*!
2541 \fn void QTextEdit::selectionChanged()
2542
2543 This signal is emitted whenever the selection changes.
2544
2545 \sa copyAvailable()
2546*/
2547
2548/*!
2549 \fn void QTextEdit::cursorPositionChanged()
2550
2551 This signal is emitted whenever the position of the
2552 cursor changed.
2553*/
2554
2555/*!
2556 \since 4.2
2557
2558 Sets the text edit's \a text. The text can be plain text or HTML
2559 and the text edit will try to guess the right format.
2560
2561 Use setHtml() or setPlainText() directly to avoid text edit's guessing.
2562
2563 \sa toPlainText(), toHtml()
2564*/
2565void QTextEdit::setText(const QString &text)
2566{
2567 Qt::TextFormat format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
2568#ifndef QT_NO_TEXTHTMLPARSER
2569 if (format == Qt::RichText)
2570 setHtml(text);
2571 else
2572#else
2573 Q_UNUSED(format);
2574#endif
2575 setPlainText(text);
2576}
2577
2578
2579/*!
2580 Appends a new paragraph with \a text to the end of the text edit.
2581
2582 \note The new paragraph appended will have the same character format and
2583 block format as the current paragraph, determined by the position of the cursor.
2584
2585 \sa currentCharFormat(), QTextCursor::blockFormat()
2586*/
2587
2588void QTextEdit::append(const QString &text)
2589{
2590 Q_D(QTextEdit);
2591 const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() :
2592 d->control->textCursor().atEnd();
2593 d->control->append(text);
2594 if (atBottom)
2595 d->vbar->setValue(d->vbar->maximum());
2596}
2597
2598/*!
2599 Ensures that the cursor is visible by scrolling the text edit if
2600 necessary.
2601*/
2602void QTextEdit::ensureCursorVisible()
2603{
2604 Q_D(QTextEdit);
2605 d->control->ensureCursorVisible();
2606}
2607
2608/*!
2609 \fn void QTextEdit::textChanged()
2610
2611 This signal is emitted whenever the document's content changes; for
2612 example, when text is inserted or deleted, or when formatting is applied.
2613*/
2614
2615/*!
2616 \fn void QTextEdit::undoAvailable(bool available)
2617
2618 This signal is emitted whenever undo operations become available
2619 (\a available is true) or unavailable (\a available is false).
2620*/
2621
2622/*!
2623 \fn void QTextEdit::redoAvailable(bool available)
2624
2625 This signal is emitted whenever redo operations become available
2626 (\a available is true) or unavailable (\a available is false).
2627*/
2628
2629QT_END_NAMESPACE
2630
2631#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