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(-d->horizontalOffset(), -d->verticalOffset());
1727 switch (argument.userType()) {
1728 case QMetaType::QRectF:
1729 argument = argument.toRectF().translated(-offset);
1730 break;
1731 case QMetaType::QPointF:
1732 argument = argument.toPointF() - offset;
1733 break;
1734 case QMetaType::QRect:
1735 argument = argument.toRect().translated(-offset.toPoint());
1736 break;
1737 case QMetaType::QPoint:
1738 argument = argument.toPoint() - offset;
1739 break;
1740 default:
1741 break;
1742 }
1743
1744 const QVariant v = d->control->inputMethodQuery(query, argument);
1745 switch (v.userType()) {
1746 case QMetaType::QRectF:
1747 return v.toRectF().translated(offset);
1748 case QMetaType::QPointF:
1749 return v.toPointF() + offset;
1750 case QMetaType::QRect:
1751 return v.toRect().translated(offset.toPoint());
1752 case QMetaType::QPoint:
1753 return v.toPoint() + offset.toPoint();
1754 default:
1755 break;
1756 }
1757 return v;
1758}
1759
1760/*! \reimp
1761*/
1762void QTextEdit::focusInEvent(QFocusEvent *e)
1763{
1764 Q_D(QTextEdit);
1765 if (e->reason() == Qt::MouseFocusReason) {
1766 d->clickCausedFocus = 1;
1767 }
1768 QAbstractScrollArea::focusInEvent(e);
1769 d->sendControlEvent(e);
1770}
1771
1772/*! \reimp
1773*/
1774void QTextEdit::focusOutEvent(QFocusEvent *e)
1775{
1776 Q_D(QTextEdit);
1777 QAbstractScrollArea::focusOutEvent(e);
1778 d->sendControlEvent(e);
1779}
1780
1781/*! \reimp
1782*/
1783void QTextEdit::showEvent(QShowEvent *)
1784{
1785 Q_D(QTextEdit);
1786 if (!d->anchorToScrollToWhenVisible.isEmpty()) {
1787 scrollToAnchor(d->anchorToScrollToWhenVisible);
1788 d->anchorToScrollToWhenVisible.clear();
1789 d->showCursorOnInitialShow = false;
1790 } else if (d->showCursorOnInitialShow) {
1791 d->showCursorOnInitialShow = false;
1792 ensureCursorVisible();
1793 }
1794}
1795
1796/*! \reimp
1797*/
1798void QTextEdit::changeEvent(QEvent *e)
1799{
1800 Q_D(QTextEdit);
1801 QAbstractScrollArea::changeEvent(e);
1802 if (e->type() == QEvent::ApplicationFontChange
1803 || e->type() == QEvent::FontChange) {
1804 d->control->document()->setDefaultFont(font());
1805 } else if (e->type() == QEvent::ActivationChange) {
1806 if (!isActiveWindow())
1807 d->autoScrollTimer.stop();
1808 } else if (e->type() == QEvent::EnabledChange) {
1809 e->setAccepted(isEnabled());
1810 d->control->setPalette(palette());
1811 d->sendControlEvent(e);
1812 } else if (e->type() == QEvent::PaletteChange) {
1813 d->control->setPalette(palette());
1814 } else if (e->type() == QEvent::LayoutDirectionChange) {
1815 d->sendControlEvent(e);
1816 }
1817}
1818
1819/*! \reimp
1820*/
1821#if QT_CONFIG(wheelevent)
1822void QTextEdit::wheelEvent(QWheelEvent *e)
1823{
1824 Q_D(QTextEdit);
1825 if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
1826 if (e->modifiers() & Qt::ControlModifier) {
1827 float delta = e->angleDelta().y() / 120.f;
1828 zoomInF(delta);
1829 return;
1830 }
1831 }
1832 QAbstractScrollArea::wheelEvent(e);
1833 updateMicroFocus();
1834}
1835#endif
1836
1837#ifndef QT_NO_CONTEXTMENU
1838/*! This function creates the standard context menu which is shown
1839 when the user clicks on the text edit with the right mouse
1840 button. It is called from the default contextMenuEvent() handler.
1841 The popup menu's ownership is transferred to the caller.
1842
1843 We recommend that you use the createStandardContextMenu(QPoint) version instead
1844 which will enable the actions that are sensitive to where the user clicked.
1845*/
1846
1847QMenu *QTextEdit::createStandardContextMenu()
1848{
1849 Q_D(QTextEdit);
1850 return d->control->createStandardContextMenu(QPointF(), this);
1851}
1852
1853/*!
1854 \since 4.4
1855 This function creates the standard context menu which is shown
1856 when the user clicks on the text edit with the right mouse
1857 button. It is called from the default contextMenuEvent() handler
1858 and it takes the \a position in document coordinates where the mouse click was.
1859 This can enable actions that are sensitive to the position where the user clicked.
1860 The popup menu's ownership is transferred to the caller.
1861*/
1862
1863QMenu *QTextEdit::createStandardContextMenu(const QPoint &position)
1864{
1865 Q_D(QTextEdit);
1866 return d->control->createStandardContextMenu(position, this);
1867}
1868#endif // QT_NO_CONTEXTMENU
1869
1870/*!
1871 returns a QTextCursor at position \a pos (in viewport coordinates).
1872*/
1873QTextCursor QTextEdit::cursorForPosition(const QPoint &pos) const
1874{
1875 Q_D(const QTextEdit);
1876 return d->control->cursorForPosition(d->mapToContents(pos));
1877}
1878
1879/*!
1880 returns a rectangle (in viewport coordinates) that includes the
1881 \a cursor.
1882 */
1883QRect QTextEdit::cursorRect(const QTextCursor &cursor) const
1884{
1885 Q_D(const QTextEdit);
1886 if (cursor.isNull())
1887 return QRect();
1888
1889 QRect r = d->control->cursorRect(cursor).toRect();
1890 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1891 return r;
1892}
1893
1894/*!
1895 returns a rectangle (in viewport coordinates) that includes the
1896 cursor of the text edit.
1897 */
1898QRect QTextEdit::cursorRect() const
1899{
1900 Q_D(const QTextEdit);
1901 QRect r = d->control->cursorRect().toRect();
1902 r.translate(-d->horizontalOffset(),-d->verticalOffset());
1903 return r;
1904}
1905
1906
1907/*!
1908 Returns the reference of the anchor at position \a pos, or an
1909 empty string if no anchor exists at that point.
1910*/
1911QString QTextEdit::anchorAt(const QPoint& pos) const
1912{
1913 Q_D(const QTextEdit);
1914 return d->control->anchorAt(d->mapToContents(pos));
1915}
1916
1917/*!
1918 \property QTextEdit::overwriteMode
1919 \since 4.1
1920 \brief whether text entered by the user will overwrite existing text
1921
1922 As with many text editors, the text editor widget can be configured
1923 to insert or overwrite existing text with new text entered by the user.
1924
1925 If this property is \c true, existing text is overwritten, character-for-character
1926 by new text; otherwise, text is inserted at the cursor position, displacing
1927 existing text.
1928
1929 By default, this property is \c false (new text does not overwrite existing text).
1930*/
1931
1932bool QTextEdit::overwriteMode() const
1933{
1934 Q_D(const QTextEdit);
1935 return d->control->overwriteMode();
1936}
1937
1938void QTextEdit::setOverwriteMode(bool overwrite)
1939{
1940 Q_D(QTextEdit);
1941 d->control->setOverwriteMode(overwrite);
1942}
1943
1944/*!
1945 \property QTextEdit::tabStopDistance
1946 \brief the tab stop distance in pixels
1947 \since 5.10
1948
1949 By default, this property contains a value of 80 pixels.
1950
1951 Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
1952 of the QChar::VisualTabCharacter character, otherwise the tab-character
1953 will be drawn incompletely.
1954
1955 \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
1956*/
1957
1958qreal QTextEdit::tabStopDistance() const
1959{
1960 Q_D(const QTextEdit);
1961 return d->control->document()->defaultTextOption().tabStopDistance();
1962}
1963
1964void QTextEdit::setTabStopDistance(qreal distance)
1965{
1966 Q_D(QTextEdit);
1967 QTextOption opt = d->control->document()->defaultTextOption();
1968 if (opt.tabStopDistance() == distance || distance < 0)
1969 return;
1970 opt.setTabStopDistance(distance);
1971 d->control->document()->setDefaultTextOption(opt);
1972}
1973
1974/*!
1975 \since 4.2
1976 \property QTextEdit::cursorWidth
1977
1978 This property specifies the width of the cursor in pixels. The default value is 1.
1979*/
1980int QTextEdit::cursorWidth() const
1981{
1982 Q_D(const QTextEdit);
1983 return d->control->cursorWidth();
1984}
1985
1986void QTextEdit::setCursorWidth(int width)
1987{
1988 Q_D(QTextEdit);
1989 d->control->setCursorWidth(width);
1990}
1991
1992/*!
1993 \property QTextEdit::acceptRichText
1994 \brief whether the text edit accepts rich text insertions by the user
1995 \since 4.1
1996
1997 When this property is set to false text edit will accept only
1998 plain text input from the user. For example through clipboard or drag and drop.
1999
2000 This property's default is true.
2001*/
2002
2003bool QTextEdit::acceptRichText() const
2004{
2005 Q_D(const QTextEdit);
2006 return d->control->acceptRichText();
2007}
2008
2009void QTextEdit::setAcceptRichText(bool accept)
2010{
2011 Q_D(QTextEdit);
2012 d->control->setAcceptRichText(accept);
2013}
2014
2015/*!
2016 \class QTextEdit::ExtraSelection
2017 \since 4.2
2018 \inmodule QtWidgets
2019
2020 \brief The QTextEdit::ExtraSelection structure provides a way of specifying a
2021 character format for a given selection in a document.
2022*/
2023
2024/*!
2025 \variable QTextEdit::ExtraSelection::cursor
2026 A cursor that contains a selection in a QTextDocument
2027*/
2028
2029/*!
2030 \variable QTextEdit::ExtraSelection::format
2031 A format that is used to specify a foreground or background brush/color
2032 for the selection.
2033*/
2034
2035/*!
2036 \since 4.2
2037 This function allows temporarily marking certain regions in the document
2038 with a given color, specified as \a selections. This can be useful for
2039 example in a programming editor to mark a whole line of text with a given
2040 background color to indicate the existence of a breakpoint.
2041
2042 \sa QTextEdit::ExtraSelection, extraSelections()
2043*/
2044void QTextEdit::setExtraSelections(const QList<ExtraSelection> &selections)
2045{
2046 Q_D(QTextEdit);
2047 d->control->setExtraSelections(selections);
2048}
2049
2050/*!
2051 \since 4.2
2052 Returns previously set extra selections.
2053
2054 \sa setExtraSelections()
2055*/
2056QList<QTextEdit::ExtraSelection> QTextEdit::extraSelections() const
2057{
2058 Q_D(const QTextEdit);
2059 return d->control->extraSelections();
2060}
2061
2062/*!
2063 This function returns a new MIME data object to represent the contents
2064 of the text edit's current selection. It is called when the selection needs
2065 to be encapsulated into a new QMimeData object; for example, when a drag
2066 and drop operation is started, or when data is copied to the clipboard.
2067
2068 If you reimplement this function, note that the ownership of the returned
2069 QMimeData object is passed to the caller. The selection can be retrieved
2070 by using the textCursor() function.
2071*/
2072QMimeData *QTextEdit::createMimeDataFromSelection() const
2073{
2074 Q_D(const QTextEdit);
2075 return d->control->QWidgetTextControl::createMimeDataFromSelection();
2076}
2077
2078/*!
2079 This function returns \c true if the contents of the MIME data object, specified
2080 by \a source, can be decoded and inserted into the document. It is called
2081 for example when during a drag operation the mouse enters this widget and it
2082 is necessary to determine whether it is possible to accept the drag and drop
2083 operation.
2084
2085 Reimplement this function to enable drag and drop support for additional MIME types.
2086 */
2087bool QTextEdit::canInsertFromMimeData(const QMimeData *source) const
2088{
2089 Q_D(const QTextEdit);
2090 return d->control->QWidgetTextControl::canInsertFromMimeData(source);
2091}
2092
2093/*!
2094 This function inserts the contents of the MIME data object, specified
2095 by \a source, into the text edit at the current cursor position. It is
2096 called whenever text is inserted as the result of a clipboard paste
2097 operation, or when the text edit accepts data from a drag and drop
2098 operation.
2099
2100 Reimplement this function to enable drag and drop support for additional MIME types.
2101 */
2102void QTextEdit::insertFromMimeData(const QMimeData *source)
2103{
2104 Q_D(QTextEdit);
2105 d->control->QWidgetTextControl::insertFromMimeData(source);
2106}
2107
2108/*!
2109 \property QTextEdit::readOnly
2110 \brief whether the text edit is read-only
2111
2112 In a read-only text edit the user can only navigate through the
2113 text and select text; modifying the text is not possible.
2114
2115 This property's default is false.
2116*/
2117
2118bool QTextEdit::isReadOnly() const
2119{
2120 Q_D(const QTextEdit);
2121 return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
2122}
2123
2124void QTextEdit::setReadOnly(bool ro)
2125{
2126 Q_D(QTextEdit);
2127 Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
2128 if (ro) {
2129 flags = Qt::TextSelectableByMouse;
2130#if QT_CONFIG(textbrowser)
2131 if (qobject_cast<QTextBrowser *>(this))
2132 flags |= Qt::TextBrowserInteraction;
2133#endif
2134 } else {
2135 flags = Qt::TextEditorInteraction;
2136 }
2137 d->control->setTextInteractionFlags(flags);
2138 setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
2139 QEvent event(QEvent::ReadOnlyChange);
2140 QCoreApplication::sendEvent(this, &event);
2141}
2142
2143/*!
2144 \property QTextEdit::textInteractionFlags
2145 \since 4.2
2146
2147 Specifies how the widget should interact with user input.
2148
2149 The default value depends on whether the QTextEdit is read-only
2150 or editable, and whether it is a QTextBrowser or not.
2151*/
2152
2153void QTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
2154{
2155 Q_D(QTextEdit);
2156 d->control->setTextInteractionFlags(flags);
2157}
2158
2159Qt::TextInteractionFlags QTextEdit::textInteractionFlags() const
2160{
2161 Q_D(const QTextEdit);
2162 return d->control->textInteractionFlags();
2163}
2164
2165/*!
2166 Merges the properties specified in \a modifier into the current character
2167 format by calling QTextCursor::mergeCharFormat on the editor's cursor.
2168 If the editor has a selection then the properties of \a modifier are
2169 directly applied to the selection.
2170
2171 \sa QTextCursor::mergeCharFormat()
2172 */
2173void QTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
2174{
2175 Q_D(QTextEdit);
2176 d->control->mergeCurrentCharFormat(modifier);
2177}
2178
2179/*!
2180 Sets the char format that is be used when inserting new text to \a
2181 format by calling QTextCursor::setCharFormat() on the editor's
2182 cursor. If the editor has a selection then the char format is
2183 directly applied to the selection.
2184 */
2185void QTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
2186{
2187 Q_D(QTextEdit);
2188 d->control->setCurrentCharFormat(format);
2189}
2190
2191/*!
2192 Returns the char format that is used when inserting new text.
2193 */
2194QTextCharFormat QTextEdit::currentCharFormat() const
2195{
2196 Q_D(const QTextEdit);
2197 return d->control->currentCharFormat();
2198}
2199
2200/*!
2201 \property QTextEdit::autoFormatting
2202 \brief the enabled set of auto formatting features
2203
2204 The value can be any combination of the values in the
2205 AutoFormattingFlag enum. The default is AutoNone. Choose
2206 AutoAll to enable all automatic formatting.
2207
2208 Currently, the only automatic formatting feature provided is
2209 AutoBulletList; future versions of Qt may offer more.
2210*/
2211
2212QTextEdit::AutoFormatting QTextEdit::autoFormatting() const
2213{
2214 Q_D(const QTextEdit);
2215 return d->autoFormatting;
2216}
2217
2218void QTextEdit::setAutoFormatting(AutoFormatting features)
2219{
2220 Q_D(QTextEdit);
2221 d->autoFormatting = features;
2222}
2223
2224/*!
2225 Convenience slot that inserts \a text at the current
2226 cursor position.
2227
2228 It is equivalent to
2229
2230 \snippet code/src_gui_widgets_qtextedit.cpp 1
2231 */
2232void QTextEdit::insertPlainText(const QString &text)
2233{
2234 Q_D(QTextEdit);
2235 d->control->insertPlainText(text);
2236}
2237
2238/*!
2239 Convenience slot that inserts \a text which is assumed to be of
2240 html formatting at the current cursor position.
2241
2242 It is equivalent to:
2243
2244 \snippet code/src_gui_widgets_qtextedit.cpp 2
2245
2246 \note When using this function with a style sheet, the style sheet will
2247 only apply to the current block in the document. In order to apply a style
2248 sheet throughout a document, use QTextDocument::setDefaultStyleSheet()
2249 instead.
2250 */
2251#ifndef QT_NO_TEXTHTMLPARSER
2252void QTextEdit::insertHtml(const QString &text)
2253{
2254 Q_D(QTextEdit);
2255 d->control->insertHtml(text);
2256}
2257#endif // QT_NO_TEXTHTMLPARSER
2258
2259/*!
2260 Scrolls the text edit so that the anchor with the given \a name is
2261 visible; does nothing if the \a name is empty, or is already
2262 visible, or isn't found.
2263*/
2264void QTextEdit::scrollToAnchor(const QString &name)
2265{
2266 Q_D(QTextEdit);
2267 if (name.isEmpty())
2268 return;
2269
2270 if (!isVisible()) {
2271 d->anchorToScrollToWhenVisible = name;
2272 return;
2273 }
2274
2275 QPointF p = d->control->anchorPosition(name);
2276 const int newPosition = qRound(p.y());
2277 if ( d->vbar->maximum() < newPosition )
2278 d->adjustScrollbars();
2279 d->vbar->setValue(newPosition);
2280}
2281
2282/*!
2283 Zooms in on the text by making the base font size \a range
2284 points larger and recalculating all font sizes to be the new size.
2285 This does not change the size of any images.
2286
2287 \sa zoomOut()
2288*/
2289void QTextEdit::zoomIn(int range)
2290{
2291 zoomInF(range);
2292}
2293
2294/*!
2295 Zooms out on the text by making the base font size \a range points
2296 smaller and recalculating all font sizes to be the new size. This
2297 does not change the size of any images.
2298
2299 \sa zoomIn()
2300*/
2301void QTextEdit::zoomOut(int range)
2302{
2303 zoomInF(-range);
2304}
2305
2306/*!
2307 \internal
2308*/
2309void QTextEdit::zoomInF(float range)
2310{
2311 if (range == 0.f)
2312 return;
2313 QFont f = font();
2314 const float newSize = f.pointSizeF() + range;
2315 if (newSize <= 0)
2316 return;
2317 f.setPointSizeF(newSize);
2318 setFont(f);
2319}
2320
2321/*!
2322 \since 4.2
2323 Moves the cursor by performing the given \a operation.
2324
2325 If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
2326 This is the same effect that the user achieves when they hold down the Shift key
2327 and move the cursor with the cursor keys.
2328
2329 \sa QTextCursor::movePosition()
2330*/
2331void QTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
2332{
2333 Q_D(QTextEdit);
2334 d->control->moveCursor(operation, mode);
2335}
2336
2337/*!
2338 \since 4.2
2339 Returns whether text can be pasted from the clipboard into the textedit.
2340*/
2341bool QTextEdit::canPaste() const
2342{
2343 Q_D(const QTextEdit);
2344 return d->control->canPaste();
2345}
2346
2347/*!
2348 \since 4.3
2349 Convenience function to print the text edit's document to the given \a printer. This
2350 is equivalent to calling the print method on the document directly except that this
2351 function also supports QPrinter::Selection as print range.
2352
2353 \sa QTextDocument::print()
2354*/
2355#ifndef QT_NO_PRINTER
2356void QTextEdit::print(QPagedPaintDevice *printer) const
2357{
2358 Q_D(const QTextEdit);
2359 d->control->print(printer);
2360}
2361#endif
2362
2363/*! \property QTextEdit::tabChangesFocus
2364 \brief whether \uicontrol Tab changes focus or is accepted as input
2365
2366 In some occasions text edits should not allow the user to input
2367 tabulators or change indentation using the \uicontrol Tab key, as this breaks
2368 the focus chain. The default is false.
2369
2370*/
2371
2372bool QTextEdit::tabChangesFocus() const
2373{
2374 Q_D(const QTextEdit);
2375 return d->tabChangesFocus;
2376}
2377
2378void QTextEdit::setTabChangesFocus(bool b)
2379{
2380 Q_D(QTextEdit);
2381 d->tabChangesFocus = b;
2382}
2383
2384/*!
2385 \property QTextEdit::documentTitle
2386 \brief the title of the document parsed from the text.
2387
2388 By default, for a newly-created, empty document, this property contains
2389 an empty string.
2390*/
2391
2392/*!
2393 \property QTextEdit::lineWrapMode
2394 \brief the line wrap mode
2395
2396 The default mode is WidgetWidth which causes words to be
2397 wrapped at the right edge of the text edit. Wrapping occurs at
2398 whitespace, keeping whole words intact. If you want wrapping to
2399 occur within words use setWordWrapMode(). If you set a wrap mode of
2400 FixedPixelWidth or FixedColumnWidth you should also call
2401 setLineWrapColumnOrWidth() with the width you want.
2402
2403 \sa lineWrapColumnOrWidth
2404*/
2405
2406QTextEdit::LineWrapMode QTextEdit::lineWrapMode() const
2407{
2408 Q_D(const QTextEdit);
2409 return d->lineWrap;
2410}
2411
2412void QTextEdit::setLineWrapMode(LineWrapMode wrap)
2413{
2414 Q_D(QTextEdit);
2415 if (d->lineWrap == wrap)
2416 return;
2417 d->lineWrap = wrap;
2418 d->updateDefaultTextOption();
2419 d->relayoutDocument();
2420}
2421
2422/*!
2423 \property QTextEdit::lineWrapColumnOrWidth
2424 \brief the position (in pixels or columns depending on the wrap mode) where text will be wrapped
2425
2426 If the wrap mode is FixedPixelWidth, the value is the number of
2427 pixels from the left edge of the text edit at which text should be
2428 wrapped. If the wrap mode is FixedColumnWidth, the value is the
2429 column number (in character columns) from the left edge of the
2430 text edit at which text should be wrapped.
2431
2432 By default, this property contains a value of 0.
2433
2434 \sa lineWrapMode
2435*/
2436
2437int QTextEdit::lineWrapColumnOrWidth() const
2438{
2439 Q_D(const QTextEdit);
2440 return d->lineWrapColumnOrWidth;
2441}
2442
2443void QTextEdit::setLineWrapColumnOrWidth(int w)
2444{
2445 Q_D(QTextEdit);
2446 d->lineWrapColumnOrWidth = w;
2447 d->relayoutDocument();
2448}
2449
2450/*!
2451 \property QTextEdit::wordWrapMode
2452 \brief the mode QTextEdit will use when wrapping text by words
2453
2454 By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
2455
2456 \sa QTextOption::WrapMode
2457*/
2458
2459QTextOption::WrapMode QTextEdit::wordWrapMode() const
2460{
2461 Q_D(const QTextEdit);
2462 return d->wordWrap;
2463}
2464
2465void QTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
2466{
2467 Q_D(QTextEdit);
2468 if (mode == d->wordWrap)
2469 return;
2470 d->wordWrap = mode;
2471 d->updateDefaultTextOption();
2472}
2473
2474/*!
2475 Finds the next occurrence of the string, \a exp, using the given
2476 \a options. Returns \c true if \a exp was found and changes the
2477 cursor to select the match; otherwise returns \c false.
2478*/
2479bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
2480{
2481 Q_D(QTextEdit);
2482 return d->control->find(exp, options);
2483}
2484
2485/*!
2486 \fn bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2487
2488 \since 5.13
2489 \overload
2490
2491 Finds the next occurrence, matching the regular expression, \a exp, using the given
2492 \a options.
2493
2494 Returns \c true if a match was found and changes the cursor to select the match;
2495 otherwise returns \c false.
2496
2497 \warning For historical reasons, the case sensitivity option set on
2498 \a exp is ignored. Instead, the \a options are used to determine
2499 if the search is case sensitive or not.
2500*/
2501#if QT_CONFIG(regularexpression)
2502bool QTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2503{
2504 Q_D(QTextEdit);
2505 return d->control->find(exp, options);
2506}
2507#endif
2508
2509/*!
2510 \fn void QTextEdit::copyAvailable(bool yes)
2511
2512 This signal is emitted when text is selected or de-selected in the
2513 text edit.
2514
2515 When text is selected this signal will be emitted with \a yes set
2516 to true. If no text has been selected or if the selected text is
2517 de-selected this signal is emitted with \a yes set to false.
2518
2519 If \a yes is true then copy() can be used to copy the selection to
2520 the clipboard. If \a yes is false then copy() does nothing.
2521
2522 \sa selectionChanged()
2523*/
2524
2525/*!
2526 \fn void QTextEdit::currentCharFormatChanged(const QTextCharFormat &f)
2527
2528 This signal is emitted if the current character format has changed, for
2529 example caused by a change of the cursor position.
2530
2531 The new format is \a f.
2532
2533 \sa setCurrentCharFormat()
2534*/
2535
2536/*!
2537 \fn void QTextEdit::selectionChanged()
2538
2539 This signal is emitted whenever the selection changes.
2540
2541 \sa copyAvailable()
2542*/
2543
2544/*!
2545 \fn void QTextEdit::cursorPositionChanged()
2546
2547 This signal is emitted whenever the position of the
2548 cursor changed.
2549*/
2550
2551/*!
2552 \since 4.2
2553
2554 Sets the text edit's \a text. The text can be plain text or HTML
2555 and the text edit will try to guess the right format.
2556
2557 Use setHtml() or setPlainText() directly to avoid text edit's guessing.
2558
2559 \sa toPlainText(), toHtml()
2560*/
2561void QTextEdit::setText(const QString &text)
2562{
2563 Qt::TextFormat format = Qt::mightBeRichText(text) ? Qt::RichText : Qt::PlainText;
2564#ifndef QT_NO_TEXTHTMLPARSER
2565 if (format == Qt::RichText)
2566 setHtml(text);
2567 else
2568#else
2569 Q_UNUSED(format);
2570#endif
2571 setPlainText(text);
2572}
2573
2574
2575/*!
2576 Appends a new paragraph with \a text to the end of the text edit.
2577
2578 \note The new paragraph appended will have the same character format and
2579 block format as the current paragraph, determined by the position of the cursor.
2580
2581 \sa currentCharFormat(), QTextCursor::blockFormat()
2582*/
2583
2584void QTextEdit::append(const QString &text)
2585{
2586 Q_D(QTextEdit);
2587 const bool atBottom = isReadOnly() ? d->verticalOffset() >= d->vbar->maximum() :
2588 d->control->textCursor().atEnd();
2589 d->control->append(text);
2590 if (atBottom)
2591 d->vbar->setValue(d->vbar->maximum());
2592}
2593
2594/*!
2595 Ensures that the cursor is visible by scrolling the text edit if
2596 necessary.
2597*/
2598void QTextEdit::ensureCursorVisible()
2599{
2600 Q_D(QTextEdit);
2601 d->control->ensureCursorVisible();
2602}
2603
2604/*!
2605 \fn void QTextEdit::textChanged()
2606
2607 This signal is emitted whenever the document's content changes; for
2608 example, when text is inserted or deleted, or when formatting is applied.
2609*/
2610
2611/*!
2612 \fn void QTextEdit::undoAvailable(bool available)
2613
2614 This signal is emitted whenever undo operations become available
2615 (\a available is true) or unavailable (\a available is false).
2616*/
2617
2618/*!
2619 \fn void QTextEdit::redoAvailable(bool available)
2620
2621 This signal is emitted whenever redo operations become available
2622 (\a available is true) or unavailable (\a available is false).
2623*/
2624
2625QT_END_NAMESPACE
2626
2627#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