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
qplaintextedit.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
6
7
8#include <qgesture.h>
9#include <qfont.h>
10#include <qpainter.h>
11#include <qevent.h>
12#include <qdebug.h>
13#if QT_CONFIG(draganddrop)
14#include <qdrag.h>
15#endif
16#include <qclipboard.h>
17#include <qmath.h>
18#if QT_CONFIG(menu)
19#include <qmenu.h>
20#endif
21#include <qstyle.h>
22#include "private/qapplication_p.h"
23#include "private/qtextdocumentlayout_p.h"
24#include "private/qabstracttextdocumentlayout_p.h"
25#include "qtextdocument.h"
26#include "private/qtextdocument_p.h"
27#include "qtextlist.h"
28#include "qaccessible.h"
29
30#include <qtextformat.h>
31#include <qdatetime.h>
32#include <qapplication.h>
33#include <limits.h>
34#include <qtexttable.h>
35#include <qvariant.h>
36
38
39static inline bool shouldEnableInputMethod(QPlainTextEdit *control)
40{
41#if defined(Q_OS_ANDROID)
42 Q_UNUSED(control);
43 return !control->isReadOnly() || (control->textInteractionFlags() & Qt::TextSelectableByMouse);
44#else
45 return !control->isReadOnly();
46#endif
47}
48
79
80
81
82/*! \class QPlainTextDocumentLayout
83 \since 4.4
84 \brief The QPlainTextDocumentLayout class implements a plain text layout for QTextDocument.
85
86 \ingroup richtext-processing
87 \inmodule QtWidgets
88
89 A QPlainTextDocumentLayout is required for text documents that can
90 be display or edited in a QPlainTextEdit. See
91 QTextDocument::setDocumentLayout().
92
93 QPlainTextDocumentLayout uses the QAbstractTextDocumentLayout API
94 that QTextDocument requires, but redefines it partially in order to
95 support plain text better. For instances, it does not operate on
96 vertical pixels, but on paragraphs (called blocks) instead. The
97 height of a document is identical to the number of paragraphs it
98 contains. The layout also doesn't support tables or nested frames,
99 or any sort of advanced text layout that goes beyond a list of
100 paragraphs with syntax highlighting.
101
102*/
103
104
105
106/*!
107 Constructs a plain text document layout for the text \a document.
108 */
109QPlainTextDocumentLayout::QPlainTextDocumentLayout(QTextDocument *document)
110 :QAbstractTextDocumentLayout(* new QPlainTextDocumentLayoutPrivate, document) {
111}
112/*!
113 Destructs a plain text document layout.
114 */
115QPlainTextDocumentLayout::~QPlainTextDocumentLayout() {}
116
117
118/*!
119 \reimp
120 */
121void QPlainTextDocumentLayout::draw(QPainter *, const PaintContext &)
122{
123}
124
125/*!
126 \reimp
127 */
128int QPlainTextDocumentLayout::hitTest(const QPointF &, Qt::HitTestAccuracy ) const
129{
130// this function is used from
131// QAbstractTextDocumentLayout::anchorAt(), but is not
132// implementable in a plain text document layout, because the
133// layout depends on the top block and top line which depends on
134// the view
135 return -1;
136}
137
138/*!
139 \reimp
140 */
141int QPlainTextDocumentLayout::pageCount() const
142{ return 1; }
143
144/*!
145 \reimp
146 */
147QSizeF QPlainTextDocumentLayout::documentSize() const
148{
149 Q_D(const QPlainTextDocumentLayout);
150 return QSizeF(d->maximumWidth, document()->lineCount());
151}
152
153/*!
154 \reimp
155 */
156QRectF QPlainTextDocumentLayout::frameBoundingRect(QTextFrame *) const
157{
158 Q_D(const QPlainTextDocumentLayout);
159 return QRectF(0, 0, qMax(d->width, d->maximumWidth), qreal(INT_MAX));
160}
161
162/*!
163 \reimp
164 */
165QRectF QPlainTextDocumentLayout::blockBoundingRect(const QTextBlock &block) const
166{
167 if (!block.isValid()) { return QRectF(); }
168 QTextLayout *tl = block.layout();
169 if (!tl->lineCount())
170 const_cast<QPlainTextDocumentLayout*>(this)->layoutBlock(block);
171 QRectF br;
172 if (block.isVisible()) {
173 br = QRectF(QPointF(0, 0), tl->boundingRect().bottomRight());
174 if (tl->lineCount() == 1)
175 br.setWidth(qMax(br.width(), tl->lineAt(0).naturalTextWidth()));
176 qreal margin = document()->documentMargin();
177 br.adjust(0, 0, margin, 0);
178 if (!block.next().isValid())
179 br.adjust(0, 0, 0, margin);
180 }
181 return br;
182
183}
184
185/*!
186 Ensures that \a block has a valid layout
187 */
188void QPlainTextDocumentLayout::ensureBlockLayout(const QTextBlock &block) const
189{
190 if (!block.isValid())
191 return;
192 QTextLayout *tl = block.layout();
193 if (!tl->lineCount())
194 const_cast<QPlainTextDocumentLayout*>(this)->layoutBlock(block);
195}
196
197
198/*! \property QPlainTextDocumentLayout::cursorWidth
199
200 This property specifies the width of the cursor in pixels. The default value is 1.
201*/
202void QPlainTextDocumentLayout::setCursorWidth(int width)
203{
204 Q_D(QPlainTextDocumentLayout);
205 d->cursorWidth = width;
206}
207
208int QPlainTextDocumentLayout::cursorWidth() const
209{
210 Q_D(const QPlainTextDocumentLayout);
211 return d->cursorWidth;
212}
213
214QPlainTextDocumentLayoutPrivate *QPlainTextDocumentLayout::priv() const
215{
216 Q_D(const QPlainTextDocumentLayout);
217 return const_cast<QPlainTextDocumentLayoutPrivate*>(d);
218}
219
220
221/*!
222
223 Requests a complete update on all views.
224 */
225void QPlainTextDocumentLayout::requestUpdate()
226{
227 emit update(QRectF(0., -document()->documentMargin(), 1000000000., 1000000000.));
228}
229
230
231void QPlainTextDocumentLayout::setTextWidth(qreal newWidth)
232{
233 Q_D(QPlainTextDocumentLayout);
234 d->width = d->maximumWidth = newWidth;
235 d->relayout();
236}
237
238qreal QPlainTextDocumentLayout::textWidth() const
239{
240 Q_D(const QPlainTextDocumentLayout);
241 return d->width;
242}
243
245{
246 Q_Q(QPlainTextDocumentLayout);
247 QTextBlock block = q->document()->firstBlock();
248 while (block.isValid()) {
249 block.layout()->clearLayout();
250 block.setLineCount(block.isVisible() ? 1 : 0);
251 block = block.next();
252 }
253 emit q->update();
254}
255
256
257/*! \reimp
258 */
259void QPlainTextDocumentLayout::documentChanged(int from, int charsRemoved, int charsAdded)
260{
261 Q_D(QPlainTextDocumentLayout);
262 QTextDocument *doc = document();
263 int newBlockCount = doc->blockCount();
264 int charsChanged = charsRemoved + charsAdded;
265
266 QTextBlock changeStartBlock = doc->findBlock(from);
267 QTextBlock changeEndBlock = doc->findBlock(qMax(0, from + charsChanged - 1));
268 bool blockVisibilityChanged = false;
269
270 if (changeStartBlock == changeEndBlock && newBlockCount == d->blockCount) {
271 QTextBlock block = changeStartBlock;
272 if (block.isValid() && block.length()) {
273 QRectF oldBr = blockBoundingRect(block);
274 layoutBlock(block);
275 QRectF newBr = blockBoundingRect(block);
276 if (newBr.height() == oldBr.height()) {
277 if (!d->blockUpdate)
278 emit updateBlock(block);
279 return;
280 }
281 }
282 } else {
283 QTextBlock block = changeStartBlock;
284 do {
285 block.clearLayout();
286 if (block.isVisible()
287 ? (block.lineCount() == 0)
288 : (block.lineCount() > 0)) {
289 blockVisibilityChanged = true;
290 block.setLineCount(block.isVisible() ? 1 : 0);
291 }
292 if (block == changeEndBlock)
293 break;
294 block = block.next();
295 } while(block.isValid());
296 }
297
298 if (newBlockCount != d->blockCount || blockVisibilityChanged) {
299 int changeEnd = changeEndBlock.blockNumber();
300 int blockDiff = newBlockCount - d->blockCount;
301 int oldChangeEnd = changeEnd - blockDiff;
302
303 if (d->maximumWidthBlockNumber > oldChangeEnd)
304 d->maximumWidthBlockNumber += blockDiff;
305
306 d->blockCount = newBlockCount;
307 if (d->blockCount == 1)
308 d->maximumWidth = blockWidth(doc->firstBlock());
309
310 if (!d->blockDocumentSizeChanged)
311 emit documentSizeChanged(documentSize());
312
313 if (blockDiff == 1 && changeEnd == newBlockCount -1 ) {
314 if (!d->blockUpdate) {
315 QTextBlock b = changeStartBlock;
316 for(;;) {
317 emit updateBlock(b);
318 if (b == changeEndBlock)
319 break;
320 b = b.next();
321 }
322 }
323 return;
324 }
325 }
326
327 if (!d->blockUpdate)
328 emit update(QRectF(0., -doc->documentMargin(), 1000000000., 1000000000.)); // optimization potential
329}
330
331
332void QPlainTextDocumentLayout::layoutBlock(const QTextBlock &block)
333{
334 Q_D(QPlainTextDocumentLayout);
335 QTextDocument *doc = document();
336 qreal margin = doc->documentMargin();
337 qreal blockMaximumWidth = 0;
338
339 qreal height = 0;
340 QTextLayout *tl = block.layout();
341 QTextOption option = doc->defaultTextOption();
342 tl->setTextOption(option);
343
344 int extraMargin = 0;
345 if (option.flags() & QTextOption::AddSpaceForLineAndParagraphSeparators) {
346 QFontMetrics fm(block.charFormat().font());
347 extraMargin += fm.horizontalAdvance(QChar(0x21B5));
348 }
349 tl->beginLayout();
350 qreal availableWidth = d->width;
351 if (availableWidth <= 0) {
352 availableWidth = qreal(INT_MAX); // similar to text edit with pageSize.width == 0
353 }
354 availableWidth -= 2*margin + extraMargin;
355 while (1) {
356 QTextLine line = tl->createLine();
357 if (!line.isValid())
358 break;
359 line.setLeadingIncluded(true);
360 line.setLineWidth(availableWidth);
361 line.setPosition(QPointF(margin, height));
362 height += line.height();
363 if (line.leading() < 0)
364 height += qCeil(line.leading());
365 blockMaximumWidth = qMax(blockMaximumWidth, line.naturalTextWidth() + 2*margin);
366 }
367 tl->endLayout();
368
369 int previousLineCount = doc->lineCount();
370 const_cast<QTextBlock&>(block).setLineCount(block.isVisible() ? tl->lineCount() : 0);
371 int lineCount = doc->lineCount();
372
373 bool emitDocumentSizeChanged = previousLineCount != lineCount;
374 if (blockMaximumWidth > d->maximumWidth) {
375 // new longest line
376 d->maximumWidth = blockMaximumWidth;
377 d->maximumWidthBlockNumber = block.blockNumber();
378 emitDocumentSizeChanged = true;
379 } else if (block.blockNumber() == d->maximumWidthBlockNumber && blockMaximumWidth < d->maximumWidth) {
380 // longest line shrinking
381 QTextBlock b = doc->firstBlock();
382 d->maximumWidth = 0;
383 QTextBlock maximumBlock;
384 while (b.isValid()) {
385 qreal blockMaximumWidth = blockWidth(b);
386 if (blockMaximumWidth > d->maximumWidth) {
387 d->maximumWidth = blockMaximumWidth;
388 maximumBlock = b;
389 }
390 b = b.next();
391 }
392 if (maximumBlock.isValid()) {
393 d->maximumWidthBlockNumber = maximumBlock.blockNumber();
394 emitDocumentSizeChanged = true;
395 }
396 }
397 if (emitDocumentSizeChanged && !d->blockDocumentSizeChanged)
398 emit documentSizeChanged(documentSize());
399}
400
401qreal QPlainTextDocumentLayout::blockWidth(const QTextBlock &block)
402{
403 QTextLayout *layout = block.layout();
404 if (!layout->lineCount())
405 return 0; // only for layouted blocks
406 qreal blockWidth = 0;
407 for (int i = 0; i < layout->lineCount(); ++i) {
408 QTextLine line = layout->lineAt(i);
409 blockWidth = qMax(line.naturalTextWidth() + 8, blockWidth);
410 }
411 return blockWidth;
412}
413
414
415QPlainTextEditControl::QPlainTextEditControl(QPlainTextEdit *parent)
416 : QWidgetTextControl(parent), textEdit(parent),
417 topBlock(0)
418{
419 setAcceptRichText(false);
420}
421
423{
424 pageUpDownLastCursorYIsValid = false;
425 Q_Q(QPlainTextEdit);
426#if QT_CONFIG(accessibility)
427 QAccessibleTextCursorEvent ev(q, q->textCursor().position());
428 QAccessible::updateAccessibility(&ev);
429#endif
430 emit q->cursorPositionChanged();
431}
432
434
435 const auto a = static_cast<QAbstractSlider::SliderAction>(action);
436 switch (a) {
437 case QAbstractSlider::SliderPageStepAdd:
438 pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor, false);
439 break;
440 case QAbstractSlider::SliderPageStepSub:
441 pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor, false);
442 break;
443 default:
444 break;
445 }
446}
447
449 QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
450 if (!ed)
451 return QWidgetTextControl::createMimeDataFromSelection();
452 return ed->createMimeDataFromSelection();
453 }
454bool QPlainTextEditControl::canInsertFromMimeData(const QMimeData *source) const {
455 QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
456 if (!ed)
457 return QWidgetTextControl::canInsertFromMimeData(source);
458 return ed->canInsertFromMimeData(source);
459}
460void QPlainTextEditControl::insertFromMimeData(const QMimeData *source) {
461 QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(parent());
462 if (!ed)
463 QWidgetTextControl::insertFromMimeData(source);
464 else
465 ed->insertFromMimeData(source);
466}
467
468qreal QPlainTextEditPrivate::verticalOffset(int topBlock, int topLine) const
469{
470 qreal offset = 0;
471 QTextDocument *doc = control->document();
472
473 if (topLine) {
474 QTextBlock currentBlock = doc->findBlockByNumber(topBlock);
475 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
476 Q_ASSERT(documentLayout);
477 QRectF r = documentLayout->blockBoundingRect(currentBlock);
478 Q_UNUSED(r);
479 QTextLayout *layout = currentBlock.layout();
480 if (layout && topLine <= layout->lineCount()) {
481 QTextLine line = layout->lineAt(topLine - 1);
482 const QRectF lr = line.naturalTextRect();
483 offset = lr.bottom();
484 }
485 }
486 if (topBlock == 0 && topLine == 0)
487 offset -= doc->documentMargin(); // top margin
488 return offset;
489}
490
491
493 return verticalOffset(control->topBlock, topLine) + topLineFracture;
494}
495
496
498{
499 return document()->findBlockByNumber(topBlock);
500}
501
502
503
504int QPlainTextEditControl::hitTest(const QPointF &point, Qt::HitTestAccuracy ) const {
505 int currentBlockNumber = topBlock;
506 QTextBlock currentBlock = document()->findBlockByNumber(currentBlockNumber);
507 if (!currentBlock.isValid())
508 return -1;
509
510 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout());
511 Q_ASSERT(documentLayout);
512
513 QPointF offset;
514 QRectF r = documentLayout->blockBoundingRect(currentBlock);
515 while (currentBlock.next().isValid() && r.bottom() + offset.y() <= point.y()) {
516 offset.ry() += r.height();
517 currentBlock = currentBlock.next();
518 ++currentBlockNumber;
519 r = documentLayout->blockBoundingRect(currentBlock);
520 }
521 while (currentBlock.previous().isValid() && r.top() + offset.y() > point.y()) {
522 offset.ry() -= r.height();
523 currentBlock = currentBlock.previous();
524 --currentBlockNumber;
525 r = documentLayout->blockBoundingRect(currentBlock);
526 }
527
528
529 if (!currentBlock.isValid())
530 return -1;
531 QTextLayout *layout = currentBlock.layout();
532 int off = 0;
533 QPointF pos = point - offset;
534 for (int i = 0; i < layout->lineCount(); ++i) {
535 QTextLine line = layout->lineAt(i);
536 const QRectF lr = line.naturalTextRect();
537 if (lr.top() > pos.y()) {
538 off = qMin(off, line.textStart());
539 } else if (lr.bottom() <= pos.y()) {
540 off = qMax(off, line.textStart() + line.textLength());
541 } else {
542 off = line.xToCursor(pos.x(), overwriteMode() ?
543 QTextLine::CursorOnCharacter : QTextLine::CursorBetweenCharacters);
544 break;
545 }
546 }
547
548 return currentBlock.position() + off;
549}
550
551QRectF QPlainTextEditControl::blockBoundingRect(const QTextBlock &block) const {
552 int currentBlockNumber = topBlock;
553 int blockNumber = block.blockNumber();
554 QTextBlock currentBlock = document()->findBlockByNumber(currentBlockNumber);
555 if (!currentBlock.isValid())
556 return QRectF();
557 Q_ASSERT(currentBlock.blockNumber() == currentBlockNumber);
558 QTextDocument *doc = document();
559 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
560 Q_ASSERT(documentLayout);
561
562 QPointF offset;
563 if (!block.isValid())
564 return QRectF();
565 QRectF r = documentLayout->blockBoundingRect(currentBlock);
566 int maxVerticalOffset = r.height();
567 while (currentBlockNumber < blockNumber && offset.y() - maxVerticalOffset <= 2* textEdit->viewport()->height()) {
568 offset.ry() += r.height();
569 currentBlock = currentBlock.next();
570 ++currentBlockNumber;
571 if (!currentBlock.isVisible()) {
572 currentBlock = doc->findBlockByLineNumber(currentBlock.firstLineNumber());
573 currentBlockNumber = currentBlock.blockNumber();
574 }
575 r = documentLayout->blockBoundingRect(currentBlock);
576 }
577 while (currentBlockNumber > blockNumber && offset.y() + maxVerticalOffset >= -textEdit->viewport()->height()) {
578 currentBlock = currentBlock.previous();
579 --currentBlockNumber;
580 while (!currentBlock.isVisible()) {
581 currentBlock = currentBlock.previous();
582 --currentBlockNumber;
583 }
584 if (!currentBlock.isValid())
585 break;
586
587 r = documentLayout->blockBoundingRect(currentBlock);
588 offset.ry() -= r.height();
589 }
590
591 if (currentBlockNumber != blockNumber) {
592 // fallback for blocks out of reach. Give it some geometry at
593 // least, and ensure the layout is up to date.
594 r = documentLayout->blockBoundingRect(block);
595 if (currentBlockNumber > blockNumber)
596 offset.ry() -= r.height();
597 }
598 r.translate(offset);
599 return r;
600}
601
602QString QPlainTextEditControl::anchorAt(const QPointF &pos) const
603{
604 return textEdit->anchorAt(pos.toPoint());
605}
606
607void QPlainTextEditPrivate::setTopLine(int visualTopLine, int dx)
608{
609 QTextDocument *doc = control->document();
610 QTextBlock block = doc->findBlockByLineNumber(visualTopLine);
611 int blockNumber = block.blockNumber();
612 int lineNumber = visualTopLine - block.firstLineNumber();
613 setTopBlock(blockNumber, lineNumber, dx);
614}
615
616void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx)
617{
618 Q_Q(QPlainTextEdit);
619 blockNumber = qMax(0, blockNumber);
620 lineNumber = qMax(0, lineNumber);
621 QTextDocument *doc = control->document();
622 QTextBlock block = doc->findBlockByNumber(blockNumber);
623
624 int newTopLine = block.firstLineNumber() + lineNumber;
625 int maxTopLine = vbar->maximum();
626
627 if (newTopLine > maxTopLine) {
628 block = doc->findBlockByLineNumber(maxTopLine);
629 blockNumber = block.blockNumber();
630 lineNumber = maxTopLine - block.firstLineNumber();
631 }
632
633 vbar->setValue(newTopLine);
634
635 if (!dx && blockNumber == control->topBlock && lineNumber == topLine)
636 return;
637
638 if (viewport->updatesEnabled() && viewport->isVisible()) {
639 int dy = 0;
640 if (doc->findBlockByNumber(control->topBlock).isValid()) {
641 qreal realdy = -q->blockBoundingGeometry(block).y()
642 + verticalOffset() - verticalOffset(blockNumber, lineNumber);
643 dy = (int)realdy;
644 topLineFracture = realdy - dy;
645 }
646 control->topBlock = blockNumber;
647 topLine = lineNumber;
648
649 vbar->setValue(block.firstLineNumber() + lineNumber);
650
651 if (dx || dy) {
652 viewport->scroll(q->isRightToLeft() ? -dx : dx, dy);
653 QGuiApplication::inputMethod()->update(Qt::ImCursorRectangle | Qt::ImAnchorRectangle);
654 } else {
655 viewport->update();
656 topLineFracture = 0;
657 }
658 emit q->updateRequest(viewport->rect(), dy);
659 } else {
660 control->topBlock = blockNumber;
661 topLine = lineNumber;
662 topLineFracture = 0;
663 }
664
665}
666
667
668
669void QPlainTextEditPrivate::ensureVisible(int position, bool center, bool forceCenter) {
670 Q_Q(QPlainTextEdit);
671 QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
672 QTextBlock block = control->document()->findBlock(position);
673 if (!block.isValid())
674 return;
675 QRectF br = control->blockBoundingRect(block);
676 if (!br.isValid())
677 return;
678 QTextLine line = block.layout()->lineForTextPosition(position - block.position());
679 Q_ASSERT(line.isValid());
680 QRectF lr = line.naturalTextRect().translated(br.topLeft());
681
682 if (lr.bottom() >= visible.bottom() || (center && lr.top() < visible.top()) || forceCenter){
683
684 qreal height = visible.height();
685 if (center)
686 height /= 2;
687
688 qreal h = center ? line.naturalTextRect().center().y() : line.naturalTextRect().bottom();
689
690 QTextBlock previousVisibleBlock = block;
691 while (h < height && block.previous().isValid()) {
692 previousVisibleBlock = block;
693 do {
694 block = block.previous();
695 } while (!block.isVisible() && block.previous().isValid());
696 h += q->blockBoundingRect(block).height();
697 }
698
699 int l = 0;
700 int lineCount = block.layout()->lineCount();
701 qreal voffset = verticalOffset(block.blockNumber(), 0);
702 while (l < lineCount) {
703 QRectF lineRect = block.layout()->lineAt(l).naturalTextRect();
704 if (h - voffset - lineRect.top() <= height)
705 break;
706 ++l;
707 }
708
709 if (l >= lineCount) {
710 block = previousVisibleBlock;
711 l = 0;
712 }
713 setTopBlock(block.blockNumber(), l);
714 } else if (lr.top() < visible.top()) {
715 setTopBlock(block.blockNumber(), line.lineNumber());
716 }
717
718}
719
720
722{
723 Q_Q(QPlainTextEdit);
724 viewport->update();
725 emit q->updateRequest(viewport->rect(), 0);
726}
727
728QPlainTextEditPrivate::QPlainTextEditPrivate()
729 : tabChangesFocus(false)
730 , showCursorOnInitialShow(false)
731 , backgroundVisible(false)
732 , centerOnScroll(false)
733 , inDrag(false)
734 , clickCausedFocus(false)
735 , pageUpDownLastCursorYIsValid(false)
736 , placeholderTextShown(false)
737{
738}
739
740void QPlainTextEditPrivate::init(const QString &txt)
741{
742 Q_Q(QPlainTextEdit);
743 control = new QPlainTextEditControl(q);
744
745 QTextDocument *doc = new QTextDocument(control);
746 QAbstractTextDocumentLayout *layout = new QPlainTextDocumentLayout(doc);
747 doc->setDocumentLayout(layout);
748 control->setDocument(doc);
749
750 control->setPalette(q->palette());
751
752 QObjectPrivate::connect(vbar, &QAbstractSlider::actionTriggered,
753 this, &QPlainTextEditPrivate::verticalScrollbarActionTriggered);
754 QObject::connect(control, &QWidgetTextControl::microFocusChanged, q,
755 [q](){q->updateMicroFocus(); });
756 QObjectPrivate::connect(control, &QWidgetTextControl::documentSizeChanged,
757 this, &QPlainTextEditPrivate::adjustScrollbars);
758 QObject::connect(control, &QWidgetTextControl::blockCountChanged,
759 q, &QPlainTextEdit::blockCountChanged);
760 QObjectPrivate::connect(control, &QWidgetTextControl::updateRequest,
761 this, &QPlainTextEditPrivate::repaintContents);
762 QObject::connect(control, &QWidgetTextControl::modificationChanged,
763 q, &QPlainTextEdit::modificationChanged);
764 QObject::connect(control, &QWidgetTextControl::textChanged, q, &QPlainTextEdit::textChanged);
765 QObject::connect(control, &QWidgetTextControl::undoAvailable, q, &QPlainTextEdit::undoAvailable);
766 QObject::connect(control, &QWidgetTextControl::redoAvailable, q, &QPlainTextEdit::redoAvailable);
767 QObject::connect(control, &QWidgetTextControl::copyAvailable, q, &QPlainTextEdit::copyAvailable);
768 QObject::connect(control, &QWidgetTextControl::selectionChanged, q, &QPlainTextEdit::selectionChanged);
769 QObjectPrivate::connect(control, &QWidgetTextControl::cursorPositionChanged,
770 this, &QPlainTextEditPrivate::cursorPositionChanged);
771 QObjectPrivate::connect(control, &QWidgetTextControl::textChanged,
772 this, &QPlainTextEditPrivate::updatePlaceholderVisibility);
773 QObject::connect(control, &QWidgetTextControl::textChanged, q, [q](){q->updateMicroFocus(); });
774
775 // set a null page size initially to avoid any relayouting until the textedit
776 // is shown. relayoutDocument() will take care of setting the page size to the
777 // viewport dimensions later.
778 doc->setTextWidth(-1);
779 doc->documentLayout()->setPaintDevice(viewport);
780 doc->setDefaultFont(q->font());
781
782
783 if (!txt.isEmpty())
784 control->setPlainText(txt);
785
786 hbar->setSingleStep(defaultSingleStep());
787 vbar->setSingleStep(1);
788
789 viewport->setBackgroundRole(QPalette::Base);
790 q->setAcceptDrops(true);
791 q->setFocusPolicy(Qt::StrongFocus);
792 q->setAttribute(Qt::WA_KeyCompression);
793 q->setAttribute(Qt::WA_InputMethodEnabled);
794 q->setInputMethodHints(Qt::ImhMultiLine);
795
796#ifndef QT_NO_CURSOR
797 viewport->setCursor(Qt::IBeamCursor);
798#endif
799}
800
802{
803 // We normally only repaint the part of view that contains text in the
804 // document that has changed (in repaintContents). But the placeholder
805 // text is not a part of the document, but is drawn on separately. So whenever
806 // we either show or hide the placeholder text, we issue a full update.
807 if (placeholderTextShown != placeHolderTextToBeShown()) {
808 viewport->update();
809 placeholderTextShown = placeHolderTextToBeShown();
810 }
811}
812
813void QPlainTextEditPrivate::repaintContents(const QRectF &contentsRect)
814{
815 Q_Q(QPlainTextEdit);
816 if (!contentsRect.isValid()) {
818 return;
819 }
820 const int xOffset = horizontalOffset();
821 const int yOffset = (int)verticalOffset();
822 const QRect visibleRect(xOffset, yOffset, viewport->width(), viewport->height());
823
824 QRect r = contentsRect.adjusted(-1, -1, 1, 1).intersected(visibleRect).toAlignedRect();
825 if (r.isEmpty())
826 return;
827
828 r.translate(-xOffset, -yOffset);
829 viewport->update(r);
830 emit q->updateRequest(r, 0);
831}
832
833void QPlainTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode, bool moveCursor)
834{
835
836 Q_Q(QPlainTextEdit);
837
838 QTextCursor cursor = control->textCursor();
839 if (moveCursor) {
841 if (!pageUpDownLastCursorYIsValid)
842 pageUpDownLastCursorY = control->cursorRect(cursor).top() - verticalOffset();
843 }
844
845 qreal lastY = pageUpDownLastCursorY;
846
847
848 if (op == QTextCursor::Down) {
849 QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
850 QTextBlock firstVisibleBlock = q->firstVisibleBlock();
851 QTextBlock block = firstVisibleBlock;
852 QRectF br = q->blockBoundingRect(block);
853 qreal h = 0;
854 int atEnd = false;
855 while (h + br.height() <= visible.bottom()) {
856 if (!block.next().isValid()) {
857 atEnd = true;
858 lastY = visible.bottom(); // set cursor to last line
859 break;
860 }
861 h += br.height();
862 block = block.next();
863 br = q->blockBoundingRect(block);
864 }
865
866 if (!atEnd) {
867 int line = 0;
868 qreal diff = visible.bottom() - h;
869 int lineCount = block.layout()->lineCount();
870 while (line < lineCount - 1) {
871 if (block.layout()->lineAt(line).naturalTextRect().bottom() > diff) {
872 // the first line that did not completely fit the screen
873 break;
874 }
875 ++line;
876 }
877 setTopBlock(block.blockNumber(), line);
878 }
879
880 if (moveCursor) {
881 // move using movePosition to keep the cursor's x
882 lastY += verticalOffset();
883 bool moved = false;
884 do {
885 moved = cursor.movePosition(op, moveMode);
886 } while (moved && control->cursorRect(cursor).top() < lastY);
887 }
888
889 } else if (op == QTextCursor::Up) {
890
891 QRectF visible = QRectF(viewport->rect()).translated(-q->contentOffset());
892 visible.translate(0, -visible.height()); // previous page
893 QTextBlock block = q->firstVisibleBlock();
894 qreal h = 0;
895 while (h >= visible.top()) {
896 if (!block.previous().isValid()) {
897 if (control->topBlock == 0 && topLine == 0) {
898 lastY = 0; // set cursor to first line
899 }
900 break;
901 }
902 block = block.previous();
903 QRectF br = q->blockBoundingRect(block);
904 h -= br.height();
905 }
906
907 int line = 0;
908 if (block.isValid()) {
909 qreal diff = visible.top() - h;
910 int lineCount = block.layout()->lineCount();
911 while (line < lineCount) {
912 if (block.layout()->lineAt(line).naturalTextRect().top() >= diff)
913 break;
914 ++line;
915 }
916 if (line == lineCount) {
917 if (block.next().isValid() && block.next() != q->firstVisibleBlock()) {
918 block = block.next();
919 line = 0;
920 } else {
921 --line;
922 }
923 }
924 }
925 setTopBlock(block.blockNumber(), line);
926
927 if (moveCursor) {
928 cursor.setVisualNavigation(true);
929 // move using movePosition to keep the cursor's x
930 lastY += verticalOffset();
931 bool moved = false;
932 do {
933 moved = cursor.movePosition(op, moveMode);
934 } while (moved && control->cursorRect(cursor).top() > lastY);
935 }
936 }
937
938 if (moveCursor) {
939 control->setTextCursor(cursor, moveMode == QTextCursor::KeepAnchor);
940 pageUpDownLastCursorYIsValid = true;
941 }
942}
943
944#if QT_CONFIG(scrollbar)
945
946void QPlainTextEditPrivate::adjustScrollbars()
947{
948 Q_Q(QPlainTextEdit);
949 QTextDocument *doc = control->document();
950 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
951 Q_ASSERT(documentLayout);
952 bool documentSizeChangedBlocked = documentLayout->priv()->blockDocumentSizeChanged;
953 documentLayout->priv()->blockDocumentSizeChanged = true;
954 qreal margin = doc->documentMargin();
955
956 int vmax = 0;
957
958 int vSliderLength = 0;
959 if (!centerOnScroll && q->isVisible()) {
960 QTextBlock block = doc->lastBlock();
961 const qreal visible = viewport->rect().height() - margin - 1;
962 qreal y = 0;
963 int visibleFromBottom = 0;
964
965 while (block.isValid()) {
966 if (!block.isVisible()) {
967 block = block.previous();
968 continue;
969 }
970 y += documentLayout->blockBoundingRect(block).height();
971
972 QTextLayout *layout = block.layout();
973 int layoutLineCount = layout->lineCount();
974 if (y > visible) {
975 int lineNumber = 0;
976 while (lineNumber < layoutLineCount) {
977 QTextLine line = layout->lineAt(lineNumber);
978 const QRectF lr = line.naturalTextRect();
979 if (lr.top() >= y - visible)
980 break;
981 ++lineNumber;
982 }
983 if (lineNumber < layoutLineCount)
984 visibleFromBottom += (layoutLineCount - lineNumber);
985 break;
986
987 }
988 visibleFromBottom += layoutLineCount;
989 block = block.previous();
990 }
991 vmax = qMax(0, doc->lineCount() - visibleFromBottom);
992 vSliderLength = visibleFromBottom;
993
994 } else {
995 vmax = qMax(0, doc->lineCount() - 1);
996 int lineSpacing = q->fontMetrics().lineSpacing();
997 vSliderLength = lineSpacing != 0 ? viewport->height() / lineSpacing : 0;
998 }
999
1000 QSizeF documentSize = documentLayout->documentSize();
1001 vbar->setRange(0, qMax(0, vmax));
1002 vbar->setPageStep(vSliderLength);
1003 int visualTopLine = vmax;
1004 QTextBlock firstVisibleBlock = q->firstVisibleBlock();
1005 if (firstVisibleBlock.isValid())
1006 visualTopLine = firstVisibleBlock.firstLineNumber() + topLine;
1007
1008 vbar->setValue(visualTopLine);
1009
1010 hbar->setRange(0, (int)documentSize.width() - viewport->width());
1011 hbar->setPageStep(viewport->width());
1012 documentLayout->priv()->blockDocumentSizeChanged = documentSizeChangedBlocked;
1013 setTopLine(vbar->value());
1014}
1015
1016#endif
1017
1018
1022
1023/*!
1024 \class QPlainTextEdit
1025 \since 4.4
1026 \brief The QPlainTextEdit class provides a widget that is used to edit and display
1027 plain text.
1028
1029 \ingroup richtext-processing
1030 \inmodule QtWidgets
1031
1032 \section1 Introduction and Concepts
1033
1034 QPlainTextEdit is an advanced viewer/editor supporting plain
1035 text. It is optimized to handle large documents and to respond
1036 quickly to user input.
1037
1038 QPlainText uses very much the same technology and concepts as
1039 QTextEdit, but is optimized for plain text handling.
1040
1041 QPlainTextEdit works on paragraphs and characters. A paragraph is
1042 a formatted string which is word-wrapped to fit into the width of
1043 the widget. By default when reading plain text, one newline
1044 signifies a paragraph. A document consists of zero or more
1045 paragraphs. Paragraphs are separated by hard line breaks. Each
1046 character within a paragraph has its own attributes, for example,
1047 font and color.
1048
1049 The shape of the mouse cursor on a QPlainTextEdit is
1050 Qt::IBeamCursor by default. It can be changed through the
1051 viewport()'s cursor property.
1052
1053 \section1 Using QPlainTextEdit as a Display Widget
1054
1055 The text is set or replaced using setPlainText() which deletes the
1056 existing text and replaces it with the text passed to setPlainText().
1057
1058 Text can be inserted using the QTextCursor class or using the
1059 convenience functions insertPlainText(), appendPlainText() or
1060 paste().
1061
1062 By default, the text edit wraps words at whitespace to fit within
1063 the text edit widget. The setLineWrapMode() function is used to
1064 specify the kind of line wrap you want, \l WidgetWidth or \l
1065 NoWrap if you don't want any wrapping. If you use word wrap to
1066 the widget's width \l WidgetWidth, you can specify whether to
1067 break on whitespace or anywhere with setWordWrapMode().
1068
1069 The find() function can be used to find and select a given string
1070 within the text.
1071
1072 If you want to limit the total number of paragraphs in a
1073 QPlainTextEdit, as it is for example useful in a log viewer, then
1074 you can use the maximumBlockCount property. The combination of
1075 setMaximumBlockCount() and appendPlainText() turns QPlainTextEdit
1076 into an efficient viewer for log text. The scrolling can be
1077 reduced with the centerOnScroll() property, making the log viewer
1078 even faster. Text can be formatted in a limited way, either using
1079 a syntax highlighter (see below), or by appending html-formatted
1080 text with appendHtml(). While QPlainTextEdit does not support
1081 complex rich text rendering with tables and floats, it does
1082 support limited paragraph-based formatting that you may need in a
1083 log viewer.
1084
1085 \section2 Read-only Key Bindings
1086
1087 When QPlainTextEdit is used read-only the key bindings are limited to
1088 navigation, and text may only be selected with the mouse:
1089 \table
1090 \header \li Keypresses \li Action
1091 \row \li Qt::UpArrow \li Moves one line up.
1092 \row \li Qt::DownArrow \li Moves one line down.
1093 \row \li Qt::LeftArrow \li Moves one character to the left.
1094 \row \li Qt::RightArrow \li Moves one character to the right.
1095 \row \li PageUp \li Moves one (viewport) page up.
1096 \row \li PageDown \li Moves one (viewport) page down.
1097 \row \li Home \li Moves to the beginning of the text.
1098 \row \li End \li Moves to the end of the text.
1099 \row \li Alt+Wheel
1100 \li Scrolls the page horizontally (the Wheel is the mouse wheel).
1101 \row \li Ctrl+Wheel \li Zooms the text.
1102 \row \li Ctrl+A \li Selects all text.
1103 \endtable
1104
1105
1106 \section1 Using QPlainTextEdit as an Editor
1107
1108 All the information about using QPlainTextEdit as a display widget also
1109 applies here.
1110
1111 Selection of text is handled by the QTextCursor class, which provides
1112 functionality for creating selections, retrieving the text contents or
1113 deleting selections. You can retrieve the object that corresponds with
1114 the user-visible cursor using the textCursor() method. If you want to set
1115 a selection in QPlainTextEdit just create one on a QTextCursor object and
1116 then make that cursor the visible cursor using setCursor(). The selection
1117 can be copied to the clipboard with copy(), or cut to the clipboard with
1118 cut(). The entire text can be selected using selectAll().
1119
1120 QPlainTextEdit holds a QTextDocument object which can be retrieved using the
1121 document() method. You can also set your own document object using setDocument().
1122 QTextDocument emits a textChanged() signal if the text changes and it also
1123 provides a isModified() function which will return true if the text has been
1124 modified since it was either loaded or since the last call to setModified
1125 with false as argument. In addition it provides methods for undo and redo.
1126
1127 \section2 Syntax Highlighting
1128
1129 Just like QTextEdit, QPlainTextEdit works together with
1130 QSyntaxHighlighter.
1131
1132 \section2 Editing Key Bindings
1133
1134 The list of key bindings which are implemented for editing:
1135 \table
1136 \header \li Keypresses \li Action
1137 \row \li Backspace \li Deletes the character to the left of the cursor.
1138 \row \li Delete \li Deletes the character to the right of the cursor.
1139 \row \li Ctrl+C \li Copy the selected text to the clipboard.
1140 \row \li Ctrl+Insert \li Copy the selected text to the clipboard.
1141 \row \li Ctrl+K \li Deletes to the end of the line.
1142 \row \li Ctrl+V \li Pastes the clipboard text into text edit.
1143 \row \li Shift+Insert \li Pastes the clipboard text into text edit.
1144 \row \li Ctrl+X \li Deletes the selected text and copies it to the clipboard.
1145 \row \li Shift+Delete \li Deletes the selected text and copies it to the clipboard.
1146 \row \li Ctrl+Z \li Undoes the last operation.
1147 \row \li Ctrl+Y \li Redoes the last operation.
1148 \row \li LeftArrow \li Moves the cursor one character to the left.
1149 \row \li Ctrl+LeftArrow \li Moves the cursor one word to the left.
1150 \row \li RightArrow \li Moves the cursor one character to the right.
1151 \row \li Ctrl+RightArrow \li Moves the cursor one word to the right.
1152 \row \li UpArrow \li Moves the cursor one line up.
1153 \row \li Ctrl+UpArrow \li Moves the cursor one word up.
1154 \row \li DownArrow \li Moves the cursor one line down.
1155 \row \li Ctrl+Down Arrow \li Moves the cursor one word down.
1156 \row \li PageUp \li Moves the cursor one page up.
1157 \row \li PageDown \li Moves the cursor one page down.
1158 \row \li Home \li Moves the cursor to the beginning of the line.
1159 \row \li Ctrl+Home \li Moves the cursor to the beginning of the text.
1160 \row \li End \li Moves the cursor to the end of the line.
1161 \row \li Ctrl+End \li Moves the cursor to the end of the text.
1162 \row \li Alt+Wheel \li Scrolls the page horizontally (the Wheel is the mouse wheel).
1163 \row \li Ctrl+Wheel \li Zooms the text.
1164 \endtable
1165
1166 To select (mark) text hold down the Shift key whilst pressing one
1167 of the movement keystrokes, for example, \e{Shift+Right Arrow}
1168 will select the character to the right, and \e{Shift+Ctrl+Right
1169 Arrow} will select the word to the right, etc.
1170
1171 \section1 Differences to QTextEdit
1172
1173 QPlainTextEdit is a thin class, implemented by using most of the
1174 technology that is behind QTextEdit and QTextDocument. Its
1175 performance benefits over QTextEdit stem mostly from using a
1176 different and simplified text layout called
1177 QPlainTextDocumentLayout on the text document (see
1178 QTextDocument::setDocumentLayout()). The plain text document layout
1179 does not support tables nor embedded frames, and \e{replaces a
1180 pixel-exact height calculation with a line-by-line respectively
1181 paragraph-by-paragraph scrolling approach}. This makes it possible
1182 to handle significantly larger documents, and still resize the
1183 editor with line wrap enabled in real time. It also makes for a
1184 fast log viewer (see setMaximumBlockCount()).
1185
1186 \sa QTextDocument, QTextCursor
1187 {Syntax Highlighter Example}, {Rich Text Processing}
1188
1189*/
1190
1191/*!
1192 \property QPlainTextEdit::plainText
1193
1194 This property gets and sets the plain text editor's contents. The previous
1195 contents are removed and undo/redo history is reset when this property is set.
1196 currentCharFormat() is also reset, unless textCursor() is already at the
1197 beginning of the document.
1198
1199 By default, for an editor with no contents, this property contains an empty string.
1200*/
1201
1202/*!
1203 \property QPlainTextEdit::undoRedoEnabled
1204 \brief whether undo and redo are enabled
1205
1206 Users are only able to undo or redo actions if this property is
1207 true, and if there is an action that can be undone (or redone).
1208
1209 By default, this property is \c true.
1210*/
1211
1212/*!
1213 \enum QPlainTextEdit::LineWrapMode
1214
1215 \value NoWrap
1216 \value WidgetWidth
1217*/
1218
1219
1220/*!
1221 Constructs an empty QPlainTextEdit with parent \a
1222 parent.
1223*/
1224QPlainTextEdit::QPlainTextEdit(QWidget *parent)
1225 : QAbstractScrollArea(*new QPlainTextEditPrivate, parent)
1226{
1227 Q_D(QPlainTextEdit);
1228 d->init();
1229}
1230
1231/*!
1232 \internal
1233*/
1234QPlainTextEdit::QPlainTextEdit(QPlainTextEditPrivate &dd, QWidget *parent)
1235 : QAbstractScrollArea(dd, parent)
1236{
1237 Q_D(QPlainTextEdit);
1238 d->init();
1239}
1240
1241/*!
1242 Constructs a QPlainTextEdit with parent \a parent. The text edit will display
1243 the plain text \a text.
1244*/
1245QPlainTextEdit::QPlainTextEdit(const QString &text, QWidget *parent)
1246 : QAbstractScrollArea(*new QPlainTextEditPrivate, parent)
1247{
1248 Q_D(QPlainTextEdit);
1249 d->init(text);
1250}
1251
1252
1253/*!
1254 Destructor.
1255*/
1256QPlainTextEdit::~QPlainTextEdit()
1257{
1258 Q_D(QPlainTextEdit);
1259 if (d->documentLayoutPtr) {
1260 if (d->documentLayoutPtr->priv()->mainViewPrivate == d)
1261 d->documentLayoutPtr->priv()->mainViewPrivate = nullptr;
1262 }
1263}
1264
1265/*!
1266 Makes \a document the new document of the text editor.
1267
1268 The parent QObject of the provided document remains the owner
1269 of the object. If the current document is a child of the text
1270 editor, then it is deleted.
1271
1272 The document must have a document layout that inherits
1273 QPlainTextDocumentLayout (see QTextDocument::setDocumentLayout()).
1274
1275 \sa document()
1276*/
1277void QPlainTextEdit::setDocument(QTextDocument *document)
1278{
1279 Q_D(QPlainTextEdit);
1280 QPlainTextDocumentLayout *documentLayout = nullptr;
1281
1282 if (!document) {
1283 document = new QTextDocument(d->control);
1284 documentLayout = new QPlainTextDocumentLayout(document);
1285 document->setDocumentLayout(documentLayout);
1286 } else {
1287 documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document->documentLayout());
1288 if (Q_UNLIKELY(!documentLayout)) {
1289 qWarning("QPlainTextEdit::setDocument: Document set does not support QPlainTextDocumentLayout");
1290 return;
1291 }
1292 }
1293 d->control->setDocument(document);
1294 if (!documentLayout->priv()->mainViewPrivate)
1295 documentLayout->priv()->mainViewPrivate = d;
1296 d->documentLayoutPtr = documentLayout;
1297 d->updateDefaultTextOption();
1298 d->relayoutDocument();
1299 d->adjustScrollbars();
1300}
1301
1302/*!
1303 Returns a pointer to the underlying document.
1304
1305 \sa setDocument()
1306*/
1307QTextDocument *QPlainTextEdit::document() const
1308{
1309 Q_D(const QPlainTextEdit);
1310 return d->control->document();
1311}
1312
1313/*!
1314 \since 5.3
1315
1316 \property QPlainTextEdit::placeholderText
1317 \brief the editor placeholder text
1318
1319 Setting this property makes the editor display a grayed-out
1320 placeholder text as long as the document() is empty.
1321
1322 By default, this property contains an empty string.
1323
1324 \sa document()
1325*/
1326void QPlainTextEdit::setPlaceholderText(const QString &placeholderText)
1327{
1328 Q_D(QPlainTextEdit);
1329 if (d->placeholderText != placeholderText) {
1330 d->placeholderText = placeholderText;
1331 d->updatePlaceholderVisibility();
1332 }
1333}
1334
1335QString QPlainTextEdit::placeholderText() const
1336{
1337 Q_D(const QPlainTextEdit);
1338 return d->placeholderText;
1339}
1340
1341/*!
1342 Sets the visible \a cursor.
1343*/
1344void QPlainTextEdit::setTextCursor(const QTextCursor &cursor)
1345{
1346 doSetTextCursor(cursor);
1347}
1348
1349/*!
1350 \internal
1351
1352 This provides a hook for subclasses to intercept cursor changes.
1353*/
1354
1355void QPlainTextEdit::doSetTextCursor(const QTextCursor &cursor)
1356{
1357 Q_D(QPlainTextEdit);
1358 d->control->setTextCursor(cursor);
1359}
1360
1361/*!
1362 Returns a copy of the QTextCursor that represents the currently visible cursor.
1363 Note that changes on the returned cursor do not affect QPlainTextEdit's cursor; use
1364 setTextCursor() to update the visible cursor.
1365 */
1366QTextCursor QPlainTextEdit::textCursor() const
1367{
1368 Q_D(const QPlainTextEdit);
1369 return d->control->textCursor();
1370}
1371
1372/*!
1373 Returns the reference of the anchor at position \a pos, or an
1374 empty string if no anchor exists at that point.
1375
1376 \since 4.7
1377 */
1378QString QPlainTextEdit::anchorAt(const QPoint &pos) const
1379{
1380 Q_D(const QPlainTextEdit);
1381 int cursorPos = d->control->hitTest(pos + QPointF(d->horizontalOffset(),
1382 d->verticalOffset()),
1383 Qt::ExactHit);
1384 if (cursorPos < 0)
1385 return QString();
1386
1387 QTextDocumentPrivate *pieceTable = QTextDocumentPrivate::get(document());
1388 QTextDocumentPrivate::FragmentIterator it = pieceTable->find(cursorPos);
1389 QTextCharFormat fmt = pieceTable->formatCollection()->charFormat(it->format);
1390 return fmt.anchorHref();
1391}
1392
1393/*!
1394 Undoes the last operation.
1395
1396 If there is no operation to undo, i.e. there is no undo step in
1397 the undo/redo history, nothing happens.
1398
1399 \sa redo()
1400*/
1401void QPlainTextEdit::undo()
1402{
1403 Q_D(QPlainTextEdit);
1404 d->control->undo();
1405}
1406
1407void QPlainTextEdit::redo()
1408{
1409 Q_D(QPlainTextEdit);
1410 d->control->redo();
1411}
1412
1413/*!
1414 \fn void QPlainTextEdit::redo()
1415
1416 Redoes the last operation.
1417
1418 If there is no operation to redo, i.e. there is no redo step in
1419 the undo/redo history, nothing happens.
1420
1421 \sa undo()
1422*/
1423
1424#ifndef QT_NO_CLIPBOARD
1425/*!
1426 Copies the selected text to the clipboard and deletes it from
1427 the text edit.
1428
1429 If there is no selected text nothing happens.
1430
1431 \sa copy(), paste()
1432*/
1433
1434void QPlainTextEdit::cut()
1435{
1436 Q_D(QPlainTextEdit);
1437 d->control->cut();
1438}
1439
1440/*!
1441 Copies any selected text to the clipboard.
1442
1443 \sa copyAvailable()
1444*/
1445
1446void QPlainTextEdit::copy()
1447{
1448 Q_D(QPlainTextEdit);
1449 d->control->copy();
1450}
1451
1452/*!
1453 Pastes the text from the clipboard into the text edit at the
1454 current cursor position.
1455
1456 If there is no text in the clipboard nothing happens.
1457
1458 To change the behavior of this function, i.e. to modify what
1459 QPlainTextEdit can paste and how it is being pasted, reimplement the
1460 virtual canInsertFromMimeData() and insertFromMimeData()
1461 functions.
1462
1463 \sa cut(), copy()
1464*/
1465
1466void QPlainTextEdit::paste()
1467{
1468 Q_D(QPlainTextEdit);
1469 d->control->paste();
1470}
1471#endif
1472
1473/*!
1474 Deletes all the text in the text edit.
1475
1476 Notes:
1477 \list
1478 \li The undo/redo history is also cleared.
1479 \li currentCharFormat() is reset, unless textCursor()
1480 is already at the beginning of the document.
1481 \endlist
1482
1483 \sa cut(), setPlainText()
1484*/
1485void QPlainTextEdit::clear()
1486{
1487 Q_D(QPlainTextEdit);
1488 // clears and sets empty content
1489 d->control->topBlock = d->topLine = d->topLineFracture = 0;
1490 d->control->clear();
1491}
1492
1493
1494/*!
1495 Selects all text.
1496
1497 \sa copy(), cut(), textCursor()
1498 */
1499void QPlainTextEdit::selectAll()
1500{
1501 Q_D(QPlainTextEdit);
1502 d->control->selectAll();
1503}
1504
1505/*! \internal
1506*/
1507bool QPlainTextEdit::event(QEvent *e)
1508{
1509 Q_D(QPlainTextEdit);
1510
1511 switch (e->type()) {
1512#ifndef QT_NO_CONTEXTMENU
1513 case QEvent::ContextMenu: {
1514 auto *contextMenuEvent = static_cast<QContextMenuEvent *>(e);
1515 if (contextMenuEvent->reason() == QContextMenuEvent::Keyboard) {
1516 ensureCursorVisible();
1517 const QPoint cursorPos = cursorRect().center();
1518 QContextMenuEvent ce(cursorPos, d->viewport->mapToGlobal(cursorPos), Qt::NoModifier,
1519 contextMenuEvent->device());
1520 ce.setAccepted(e->isAccepted());
1521 const bool result = QAbstractScrollArea::event(&ce);
1522 e->setAccepted(ce.isAccepted());
1523 return result;
1524 }
1525 break;
1526 }
1527#endif // QT_NO_CONTEXTMENU
1528 case QEvent::ShortcutOverride:
1529 case QEvent::ToolTip:
1530 d->sendControlEvent(e);
1531 break;
1532#ifndef QT_NO_GESTURES
1533 case QEvent::Gesture:
1534 if (auto *g = static_cast<QGestureEvent *>(e)->gesture(Qt::PanGesture)) {
1535 QPanGesture *panGesture = static_cast<QPanGesture *>(g);
1536 QScrollBar *hBar = horizontalScrollBar();
1537 QScrollBar *vBar = verticalScrollBar();
1538 if (panGesture->state() == Qt::GestureStarted)
1539 d->originalOffsetY = vBar->value();
1540 QPointF offset = panGesture->offset();
1541 if (!offset.isNull()) {
1542 if (QGuiApplication::isRightToLeft())
1543 offset.rx() *= -1;
1544 // QPlainTextEdit scrolls by lines only in vertical direction
1545 QFontMetrics fm(document()->defaultFont());
1546 int lineHeight = fm.height();
1547 int newX = hBar->value() - panGesture->delta().x();
1548 int newY = d->originalOffsetY - offset.y()/lineHeight;
1549 hBar->setValue(newX);
1550 vBar->setValue(newY);
1551 }
1552 }
1553 return true;
1554#endif // QT_NO_GESTURES
1555 case QEvent::WindowActivate:
1556 case QEvent::WindowDeactivate:
1557 d->control->setPalette(palette());
1558 break;
1559 default:
1560 break;
1561 }
1562 return QAbstractScrollArea::event(e);
1563}
1564
1565/*! \internal
1566*/
1567
1568void QPlainTextEdit::timerEvent(QTimerEvent *e)
1569{
1570 Q_D(QPlainTextEdit);
1571 if (e->timerId() == d->autoScrollTimer.timerId()) {
1572 QRect visible = d->viewport->rect();
1573 QPoint pos;
1574 if (d->inDrag) {
1575 pos = d->autoScrollDragPos;
1576 visible.adjust(qMin(visible.width()/3,20), qMin(visible.height()/3,20),
1577 -qMin(visible.width()/3,20), -qMin(visible.height()/3,20));
1578 } else {
1579 const QPoint globalPos = QCursor::pos();
1580 pos = d->viewport->mapFromGlobal(globalPos);
1581 QMouseEvent ev(QEvent::MouseMove, pos, d->viewport->mapTo(d->viewport->topLevelWidget(), pos), globalPos,
1582 Qt::LeftButton, Qt::LeftButton, QGuiApplication::keyboardModifiers());
1583 mouseMoveEvent(&ev);
1584 }
1585 int deltaY = qMax(pos.y() - visible.top(), visible.bottom() - pos.y()) - visible.height();
1586 int deltaX = qMax(pos.x() - visible.left(), visible.right() - pos.x()) - visible.width();
1587 int delta = qMax(deltaX, deltaY);
1588 if (delta >= 0) {
1589 if (delta < 7)
1590 delta = 7;
1591 const auto timeout = std::chrono::milliseconds(4900 / (delta * delta));
1592 d->autoScrollTimer.start(timeout, this);
1593
1594 if (deltaY > 0)
1595 d->vbar->triggerAction(pos.y() < visible.center().y() ?
1596 QAbstractSlider::SliderSingleStepSub
1597 : QAbstractSlider::SliderSingleStepAdd);
1598 if (deltaX > 0)
1599 d->hbar->triggerAction(pos.x() < visible.center().x() ?
1600 QAbstractSlider::SliderSingleStepSub
1601 : QAbstractSlider::SliderSingleStepAdd);
1602 }
1603 }
1604}
1605
1606/*!
1607 Changes the text of the text edit to the string \a text.
1608 Any previous text is removed.
1609
1610 \a text is interpreted as plain text.
1611
1612 Notes:
1613 \list
1614 \li The undo/redo history is also cleared.
1615 \li currentCharFormat() is reset, unless textCursor()
1616 is already at the beginning of the document.
1617 \endlist
1618
1619 \sa toPlainText()
1620*/
1621
1622void QPlainTextEdit::setPlainText(const QString &text)
1623{
1624 Q_D(QPlainTextEdit);
1625 d->control->setPlainText(text);
1626}
1627
1628/*!
1629 \fn QString QPlainTextEdit::toPlainText() const
1630
1631 Returns the text of the text edit as plain text.
1632
1633 \sa QPlainTextEdit::setPlainText()
1634 */
1635
1636/*! \reimp
1637*/
1638void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
1639{
1640 Q_D(QPlainTextEdit);
1641
1642#ifndef QT_NO_SHORTCUT
1643
1644 Qt::TextInteractionFlags tif = d->control->textInteractionFlags();
1645
1646 if (tif & Qt::TextSelectableByKeyboard){
1647 if (e == QKeySequence::SelectPreviousPage) {
1648 e->accept();
1649 d->pageUpDown(QTextCursor::Up, QTextCursor::KeepAnchor);
1650 return;
1651 } else if (e ==QKeySequence::SelectNextPage) {
1652 e->accept();
1653 d->pageUpDown(QTextCursor::Down, QTextCursor::KeepAnchor);
1654 return;
1655 }
1656 }
1657 if (tif & (Qt::TextSelectableByKeyboard | Qt::TextEditable)) {
1658 if (e == QKeySequence::MoveToPreviousPage) {
1659 e->accept();
1660 d->pageUpDown(QTextCursor::Up, QTextCursor::MoveAnchor);
1661 return;
1662 } else if (e == QKeySequence::MoveToNextPage) {
1663 e->accept();
1664 d->pageUpDown(QTextCursor::Down, QTextCursor::MoveAnchor);
1665 return;
1666 }
1667 }
1668
1669 if (!(tif & Qt::TextEditable)) {
1670 switch (e->key()) {
1671 case Qt::Key_Space:
1672 e->accept();
1673 if (e->modifiers() & Qt::ShiftModifier)
1674 d->vbar->triggerAction(QAbstractSlider::SliderPageStepSub);
1675 else
1676 d->vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);
1677 break;
1678 default:
1679 d->sendControlEvent(e);
1680 if (!e->isAccepted() && e->modifiers() == Qt::NoModifier) {
1681 if (e->key() == Qt::Key_Home) {
1682 d->vbar->triggerAction(QAbstractSlider::SliderToMinimum);
1683 e->accept();
1684 } else if (e->key() == Qt::Key_End) {
1685 d->vbar->triggerAction(QAbstractSlider::SliderToMaximum);
1686 e->accept();
1687 }
1688 }
1689 if (!e->isAccepted()) {
1690 QAbstractScrollArea::keyPressEvent(e);
1691 }
1692 }
1693 return;
1694 }
1695#endif // QT_NO_SHORTCUT
1696
1697 d->sendControlEvent(e);
1698}
1699
1700/*! \reimp
1701*/
1702void QPlainTextEdit::keyReleaseEvent(QKeyEvent *e)
1703{
1704 Q_D(QPlainTextEdit);
1705 if (!isReadOnly())
1706 d->handleSoftwareInputPanel();
1707
1708 QWidget::keyReleaseEvent(e);
1709}
1710
1711/*!
1712 Loads the resource specified by the given \a type and \a name.
1713
1714 This function is an extension of QTextDocument::loadResource().
1715
1716 \sa QTextDocument::loadResource()
1717*/
1718QVariant QPlainTextEdit::loadResource(int type, const QUrl &name)
1719{
1720 Q_UNUSED(type);
1721 Q_UNUSED(name);
1722 return QVariant();
1723}
1724
1725/*! \reimp
1726*/
1727void QPlainTextEdit::resizeEvent(QResizeEvent *e)
1728{
1729 Q_D(QPlainTextEdit);
1730 if (e->oldSize().width() != e->size().width())
1731 d->relayoutDocument();
1732 d->adjustScrollbars();
1733}
1734
1736{
1737 QTextDocument *doc = control->document();
1738 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(doc->documentLayout());
1739 Q_ASSERT(documentLayout);
1740 documentLayoutPtr = documentLayout;
1741
1742 int width = viewport->width();
1743
1744 if (documentLayout->priv()->mainViewPrivate == nullptr
1745 || documentLayout->priv()->mainViewPrivate == this
1746 || width > documentLayout->textWidth()) {
1747 documentLayout->priv()->mainViewPrivate = this;
1748 documentLayout->setTextWidth(width);
1749 }
1750}
1751
1752static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, const QRectF &gradientRect = QRectF())
1753{
1754 p->save();
1755 if (brush.style() >= Qt::LinearGradientPattern && brush.style() <= Qt::ConicalGradientPattern) {
1756 if (!gradientRect.isNull()) {
1757 QTransform m = QTransform::fromTranslate(gradientRect.left(), gradientRect.top());
1758 m.scale(gradientRect.width(), gradientRect.height());
1759 brush.setTransform(m);
1760 const_cast<QGradient *>(brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
1761 }
1762 } else {
1763 p->setBrushOrigin(rect.topLeft());
1764 }
1765 p->fillRect(rect, brush);
1766 p->restore();
1767}
1768
1769
1770
1771/*! \reimp
1772*/
1773void QPlainTextEdit::paintEvent(QPaintEvent *e)
1774{
1775 Q_D(QPlainTextEdit);
1776 QPainter painter(viewport());
1777 Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout()));
1778
1779 QPointF offset(contentOffset());
1780
1781 QRect er = e->rect();
1782 QRect viewportRect = viewport()->rect();
1783
1784 bool editable = !isReadOnly();
1785
1786 QTextBlock block = firstVisibleBlock();
1787 qreal maximumWidth = document()->documentLayout()->documentSize().width();
1788
1789 // Set a brush origin so that the WaveUnderline knows where the wave started
1790 painter.setBrushOrigin(offset);
1791
1792 // keep right margin clean from full-width selection
1793 int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
1794 - document()->documentMargin() + cursorWidth();
1795 er.setRight(qMin(er.right(), maxX));
1796 painter.setClipRect(er);
1797
1798 if (d->placeHolderTextToBeShown()) {
1799 const QColor col = d->control->palette().placeholderText().color();
1800 painter.setPen(col);
1801 painter.setClipRect(e->rect());
1802 const int margin = int(document()->documentMargin());
1803 QRectF textRect = viewportRect.adjusted(margin, margin, 0, 0);
1804 painter.drawText(textRect, Qt::AlignTop | Qt::TextWordWrap, placeholderText());
1805 }
1806
1807 QAbstractTextDocumentLayout::PaintContext context = getPaintContext();
1808 painter.setPen(context.palette.text().color());
1809
1810 while (block.isValid()) {
1811
1812 QRectF r = blockBoundingRect(block).translated(offset);
1813 QTextLayout *layout = block.layout();
1814
1815 if (!block.isVisible()) {
1816 offset.ry() += r.height();
1817 block = block.next();
1818 continue;
1819 }
1820
1821 if (r.bottom() >= er.top() && r.top() <= er.bottom()) {
1822
1823 QTextBlockFormat blockFormat = block.blockFormat();
1824
1825 QBrush bg = blockFormat.background();
1826 if (bg != Qt::NoBrush) {
1827 QRectF contentsRect = r;
1828 contentsRect.setWidth(qMax(r.width(), maximumWidth));
1829 fillBackground(&painter, contentsRect, bg);
1830 }
1831
1832 QList<QTextLayout::FormatRange> selections;
1833 int blpos = block.position();
1834 int bllen = block.length();
1835 for (int i = 0; i < context.selections.size(); ++i) {
1836 const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
1837 const int selStart = range.cursor.selectionStart() - blpos;
1838 const int selEnd = range.cursor.selectionEnd() - blpos;
1839 if (selStart < bllen && selEnd > 0
1840 && selEnd > selStart) {
1841 QTextLayout::FormatRange o;
1842 o.start = selStart;
1843 o.length = selEnd - selStart;
1844 o.format = range.format;
1845 selections.append(o);
1846 } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
1847 && block.contains(range.cursor.position())) {
1848 // for full width selections we don't require an actual selection, just
1849 // a position to specify the line. that's more convenience in usage.
1850 QTextLayout::FormatRange o;
1851 QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
1852 o.start = l.textStart();
1853 o.length = l.textLength();
1854 if (o.start + o.length == bllen - 1)
1855 ++o.length; // include newline
1856 o.format = range.format;
1857 selections.append(o);
1858 }
1859 }
1860
1861 bool drawCursor = ((editable || (textInteractionFlags() & Qt::TextSelectableByKeyboard))
1862 && context.cursorPosition >= blpos
1863 && context.cursorPosition < blpos + bllen);
1864
1865 bool drawCursorAsBlock = drawCursor && overwriteMode() ;
1866
1867 if (drawCursorAsBlock) {
1868 if (context.cursorPosition == blpos + bllen - 1) {
1869 drawCursorAsBlock = false;
1870 } else {
1871 QTextLayout::FormatRange o;
1872 o.start = context.cursorPosition - blpos;
1873 o.length = 1;
1874 o.format.setForeground(palette().base());
1875 o.format.setBackground(palette().text());
1876 selections.append(o);
1877 }
1878 }
1879
1880 layout->draw(&painter, offset, selections, er);
1881
1882 if ((drawCursor && !drawCursorAsBlock)
1883 || (editable && context.cursorPosition < -1
1884 && !layout->preeditAreaText().isEmpty())) {
1885 int cpos = context.cursorPosition;
1886 if (cpos < -1)
1887 cpos = layout->preeditAreaPosition() - (cpos + 2);
1888 else
1889 cpos -= blpos;
1890 layout->drawCursor(&painter, offset, cpos, cursorWidth());
1891 }
1892 }
1893
1894 offset.ry() += r.height();
1895 if (offset.y() > viewportRect.height())
1896 break;
1897 block = block.next();
1898 }
1899
1900 if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom()
1901 && (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) {
1902 painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().window());
1903 }
1904}
1905
1906
1908{
1909 QTextDocument *doc = control->document();
1910
1911 QTextOption opt = doc->defaultTextOption();
1912 QTextOption::WrapMode oldWrapMode = opt.wrapMode();
1913
1914 if (lineWrap == QPlainTextEdit::NoWrap)
1915 opt.setWrapMode(QTextOption::NoWrap);
1916 else
1917 opt.setWrapMode(wordWrap);
1918
1919 if (opt.wrapMode() != oldWrapMode)
1920 doc->setDefaultTextOption(opt);
1921}
1922
1923
1924/*! \reimp
1925*/
1926void QPlainTextEdit::mousePressEvent(QMouseEvent *e)
1927{
1928 Q_D(QPlainTextEdit);
1929 d->sendControlEvent(e);
1930}
1931
1932/*! \reimp
1933*/
1934void QPlainTextEdit::mouseMoveEvent(QMouseEvent *e)
1935{
1936 Q_D(QPlainTextEdit);
1937 d->inDrag = false; // paranoia
1938 const QPoint pos = e->position().toPoint();
1939 d->sendControlEvent(e);
1940 if (!(e->buttons() & Qt::LeftButton))
1941 return;
1942 if (e->source() == Qt::MouseEventNotSynthesized) {
1943 const QRect visible = d->viewport->rect();
1944 if (visible.contains(pos))
1945 d->autoScrollTimer.stop();
1946 else if (!d->autoScrollTimer.isActive())
1947 d->autoScrollTimer.start(100, this);
1948 }
1949}
1950
1951/*! \reimp
1952*/
1953void QPlainTextEdit::mouseReleaseEvent(QMouseEvent *e)
1954{
1955 Q_D(QPlainTextEdit);
1956 d->sendControlEvent(e);
1957 if (e->source() == Qt::MouseEventNotSynthesized && d->autoScrollTimer.isActive()) {
1958 d->autoScrollTimer.stop();
1959 d->ensureCursorVisible();
1960 }
1961
1962 if (!isReadOnly() && rect().contains(e->position().toPoint()))
1963 d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
1964 d->clickCausedFocus = 0;
1965}
1966
1967/*! \reimp
1968*/
1969void QPlainTextEdit::mouseDoubleClickEvent(QMouseEvent *e)
1970{
1971 Q_D(QPlainTextEdit);
1972 d->sendControlEvent(e);
1973}
1974
1975/*! \reimp
1976*/
1977bool QPlainTextEdit::focusNextPrevChild(bool next)
1978{
1979 Q_D(const QPlainTextEdit);
1980 if (!d->tabChangesFocus && d->control->textInteractionFlags() & Qt::TextEditable)
1981 return false;
1982 return QAbstractScrollArea::focusNextPrevChild(next);
1983}
1984
1985#ifndef QT_NO_CONTEXTMENU
1986/*!
1987 \fn void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
1988
1989 Shows the standard context menu created with createStandardContextMenu().
1990
1991 If you do not want the text edit to have a context menu, you can set
1992 its \l contextMenuPolicy to Qt::NoContextMenu. If you want to
1993 customize the context menu, reimplement this function. If you want
1994 to extend the standard context menu, reimplement this function, call
1995 createStandardContextMenu() and extend the menu returned.
1996
1997 Information about the event is passed in the \a event object.
1998
1999 \snippet code/src_gui_widgets_qplaintextedit.cpp 0
2000*/
2001void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *e)
2002{
2003 Q_D(QPlainTextEdit);
2004 d->sendControlEvent(e);
2005}
2006#endif // QT_NO_CONTEXTMENU
2007
2008#if QT_CONFIG(draganddrop)
2009/*! \reimp
2010*/
2011void QPlainTextEdit::dragEnterEvent(QDragEnterEvent *e)
2012{
2013 Q_D(QPlainTextEdit);
2014 d->inDrag = true;
2015 d->sendControlEvent(e);
2016}
2017
2018/*! \reimp
2019*/
2020void QPlainTextEdit::dragLeaveEvent(QDragLeaveEvent *e)
2021{
2022 Q_D(QPlainTextEdit);
2023 d->inDrag = false;
2024 d->autoScrollTimer.stop();
2025 d->sendControlEvent(e);
2026}
2027
2028/*! \reimp
2029*/
2030void QPlainTextEdit::dragMoveEvent(QDragMoveEvent *e)
2031{
2032 Q_D(QPlainTextEdit);
2033 d->autoScrollDragPos = e->position().toPoint();
2034 if (!d->autoScrollTimer.isActive())
2035 d->autoScrollTimer.start(100, this);
2036 d->sendControlEvent(e);
2037}
2038
2039/*! \reimp
2040*/
2041void QPlainTextEdit::dropEvent(QDropEvent *e)
2042{
2043 Q_D(QPlainTextEdit);
2044 d->inDrag = false;
2045 d->autoScrollTimer.stop();
2046 d->sendControlEvent(e);
2047}
2048
2049#endif // QT_CONFIG(draganddrop)
2050
2051/*! \reimp
2052 */
2053void QPlainTextEdit::inputMethodEvent(QInputMethodEvent *e)
2054{
2055 Q_D(QPlainTextEdit);
2056 d->sendControlEvent(e);
2057 const bool emptyEvent = e->preeditString().isEmpty() && e->commitString().isEmpty()
2058 && e->attributes().isEmpty();
2059 if (emptyEvent)
2060 return;
2061 ensureCursorVisible();
2062}
2063
2064/*!\reimp
2065*/
2066void QPlainTextEdit::scrollContentsBy(int dx, int /*dy*/)
2067{
2068 Q_D(QPlainTextEdit);
2069 d->setTopLine(d->vbar->value(), dx);
2070}
2071
2072/*!\reimp
2073*/
2074QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const
2075{
2076 return inputMethodQuery(property, QVariant());
2077}
2078
2079/*!\internal
2080 */
2081QVariant QPlainTextEdit::inputMethodQuery(Qt::InputMethodQuery query, QVariant argument) const
2082{
2083 Q_D(const QPlainTextEdit);
2084 switch (query) {
2085 case Qt::ImEnabled:
2086 return isEnabled() && !isReadOnly();
2087 case Qt::ImHints:
2088 case Qt::ImInputItemClipRectangle:
2089 return QWidget::inputMethodQuery(query);
2090 case Qt::ImReadOnly:
2091 return isReadOnly();
2092 default:
2093 break;
2094 }
2095
2096 const QPointF offset = contentOffset() + d->viewport->mapTo(this, QPointF());
2097 switch (argument.userType()) {
2098 case QMetaType::QRectF:
2099 argument = argument.toRectF().translated(-offset);
2100 break;
2101 case QMetaType::QPointF:
2102 argument = argument.toPointF() - offset;
2103 break;
2104 case QMetaType::QRect:
2105 argument = argument.toRect().translated(-offset.toPoint());
2106 break;
2107 case QMetaType::QPoint:
2108 argument = argument.toPoint() - offset;
2109 break;
2110 default:
2111 break;
2112 }
2113
2114 const QVariant v = d->control->inputMethodQuery(query, argument);
2115 switch (v.userType()) {
2116 case QMetaType::QRectF:
2117 return v.toRectF().translated(offset);
2118 case QMetaType::QPointF:
2119 return v.toPointF() + offset;
2120 case QMetaType::QRect:
2121 return v.toRect().translated(offset.toPoint());
2122 case QMetaType::QPoint:
2123 return v.toPoint() + offset.toPoint();
2124 default:
2125 break;
2126 }
2127 return v;
2128}
2129
2130/*! \reimp
2131*/
2132void QPlainTextEdit::focusInEvent(QFocusEvent *e)
2133{
2134 Q_D(QPlainTextEdit);
2135 if (e->reason() == Qt::MouseFocusReason) {
2136 d->clickCausedFocus = 1;
2137 }
2138 QAbstractScrollArea::focusInEvent(e);
2139 d->sendControlEvent(e);
2140}
2141
2142/*! \reimp
2143*/
2144void QPlainTextEdit::focusOutEvent(QFocusEvent *e)
2145{
2146 Q_D(QPlainTextEdit);
2147 QAbstractScrollArea::focusOutEvent(e);
2148 d->sendControlEvent(e);
2149}
2150
2151/*! \reimp
2152*/
2153void QPlainTextEdit::showEvent(QShowEvent *)
2154{
2155 Q_D(QPlainTextEdit);
2156 if (d->showCursorOnInitialShow) {
2157 d->showCursorOnInitialShow = false;
2158 ensureCursorVisible();
2159 }
2160 d->adjustScrollbars();
2161}
2162
2163/*! \reimp
2164*/
2165void QPlainTextEdit::changeEvent(QEvent *e)
2166{
2167 Q_D(QPlainTextEdit);
2168 QAbstractScrollArea::changeEvent(e);
2169
2170 switch (e->type()) {
2171 case QEvent::ApplicationFontChange:
2172 case QEvent::FontChange:
2173 d->control->document()->setDefaultFont(font());
2174 break;
2175 case QEvent::ActivationChange:
2176 if (!isActiveWindow())
2177 d->autoScrollTimer.stop();
2178 break;
2179 case QEvent::EnabledChange:
2180 e->setAccepted(isEnabled());
2181 d->control->setPalette(palette());
2182 d->sendControlEvent(e);
2183 break;
2184 case QEvent::PaletteChange:
2185 d->control->setPalette(palette());
2186 break;
2187 case QEvent::LayoutDirectionChange:
2188 d->sendControlEvent(e);
2189 break;
2190 default:
2191 break;
2192 }
2193}
2194
2195/*! \reimp
2196*/
2197#if QT_CONFIG(wheelevent)
2198void QPlainTextEdit::wheelEvent(QWheelEvent *e)
2199{
2200 Q_D(QPlainTextEdit);
2201 if (!(d->control->textInteractionFlags() & Qt::TextEditable)) {
2202 if (e->modifiers() & Qt::ControlModifier) {
2203 float delta = e->angleDelta().y() / 120.f;
2204 zoomInF(delta);
2205 return;
2206 }
2207 }
2208 QAbstractScrollArea::wheelEvent(e);
2209 updateMicroFocus();
2210}
2211#endif
2212
2213/*!
2214 Zooms in on the text by making the base font size \a range
2215 points larger and recalculating all font sizes to be the new size.
2216 This does not change the size of any images.
2217
2218 \sa zoomOut()
2219*/
2220void QPlainTextEdit::zoomIn(int range)
2221{
2222 zoomInF(range);
2223}
2224
2225/*!
2226 Zooms out on the text by making the base font size \a range points
2227 smaller and recalculating all font sizes to be the new size. This
2228 does not change the size of any images.
2229
2230 \sa zoomIn()
2231*/
2232void QPlainTextEdit::zoomOut(int range)
2233{
2234 zoomInF(-range);
2235}
2236
2237/*!
2238 \internal
2239*/
2240void QPlainTextEdit::zoomInF(float range)
2241{
2242 if (range == 0.f)
2243 return;
2244 QFont f = font();
2245 const float newSize = f.pointSizeF() + range;
2246 if (newSize <= 0)
2247 return;
2248 f.setPointSizeF(newSize);
2249 setFont(f);
2250}
2251
2252#ifndef QT_NO_CONTEXTMENU
2253/*! This function creates the standard context menu which is shown
2254 when the user clicks on the text edit with the right mouse
2255 button. It is called from the default contextMenuEvent() handler.
2256 The popup menu's ownership is transferred to the caller.
2257
2258 We recommend that you use the createStandardContextMenu(QPoint) version instead
2259 which will enable the actions that are sensitive to where the user clicked.
2260*/
2261
2262QMenu *QPlainTextEdit::createStandardContextMenu()
2263{
2264 Q_D(QPlainTextEdit);
2265 return d->control->createStandardContextMenu(QPointF(), this);
2266}
2267
2268/*!
2269 \since 5.5
2270 This function creates the standard context menu which is shown
2271 when the user clicks on the text edit with the right mouse
2272 button. It is called from the default contextMenuEvent() handler
2273 and it takes the \a position in document coordinates where the mouse click was.
2274 This can enable actions that are sensitive to the position where the user clicked.
2275 The popup menu's ownership is transferred to the caller.
2276*/
2277
2278QMenu *QPlainTextEdit::createStandardContextMenu(const QPoint &position)
2279{
2280 Q_D(QPlainTextEdit);
2281 return d->control->createStandardContextMenu(position, this);
2282}
2283#endif // QT_NO_CONTEXTMENU
2284
2285/*!
2286 returns a QTextCursor at position \a pos (in viewport coordinates).
2287*/
2288QTextCursor QPlainTextEdit::cursorForPosition(const QPoint &pos) const
2289{
2290 Q_D(const QPlainTextEdit);
2291 return d->control->cursorForPosition(d->mapToContents(pos));
2292}
2293
2294/*!
2295 returns a rectangle (in viewport coordinates) that includes the
2296 \a cursor.
2297 */
2298QRect QPlainTextEdit::cursorRect(const QTextCursor &cursor) const
2299{
2300 Q_D(const QPlainTextEdit);
2301 if (cursor.isNull())
2302 return QRect();
2303
2304 QRect r = d->control->cursorRect(cursor).toRect();
2305 r.translate(-d->horizontalOffset(),-(int)d->verticalOffset());
2306 return r;
2307}
2308
2309/*!
2310 returns a rectangle (in viewport coordinates) that includes the
2311 cursor of the text edit.
2312 */
2313QRect QPlainTextEdit::cursorRect() const
2314{
2315 Q_D(const QPlainTextEdit);
2316 QRect r = d->control->cursorRect().toRect();
2317 r.translate(-d->horizontalOffset(),-(int)d->verticalOffset());
2318 return r;
2319}
2320
2321
2322/*!
2323 \property QPlainTextEdit::overwriteMode
2324 \brief whether text entered by the user will overwrite existing text
2325
2326 As with many text editors, the plain text editor widget can be configured
2327 to insert or overwrite existing text with new text entered by the user.
2328
2329 If this property is \c true, existing text is overwritten, character-for-character
2330 by new text; otherwise, text is inserted at the cursor position, displacing
2331 existing text.
2332
2333 By default, this property is \c false (new text does not overwrite existing text).
2334*/
2335
2336bool QPlainTextEdit::overwriteMode() const
2337{
2338 Q_D(const QPlainTextEdit);
2339 return d->control->overwriteMode();
2340}
2341
2342void QPlainTextEdit::setOverwriteMode(bool overwrite)
2343{
2344 Q_D(QPlainTextEdit);
2345 d->control->setOverwriteMode(overwrite);
2346}
2347
2348/*!
2349 \property QPlainTextEdit::tabStopDistance
2350 \brief the tab stop distance in pixels
2351 \since 5.10
2352
2353 By default, this property contains a value of 80 pixels.
2354
2355 Do not set a value less than the \l {QFontMetrics::}{horizontalAdvance()}
2356 of the QChar::VisualTabCharacter character, otherwise the tab-character
2357 will be drawn incompletely.
2358
2359 \sa QTextOption::ShowTabsAndSpaces, QTextDocument::defaultTextOption
2360*/
2361
2362qreal QPlainTextEdit::tabStopDistance() const
2363{
2364 Q_D(const QPlainTextEdit);
2365 return d->control->document()->defaultTextOption().tabStopDistance();
2366}
2367
2368void QPlainTextEdit::setTabStopDistance(qreal distance)
2369{
2370 Q_D(QPlainTextEdit);
2371 QTextOption opt = d->control->document()->defaultTextOption();
2372 if (opt.tabStopDistance() == distance || distance < 0)
2373 return;
2374 opt.setTabStopDistance(distance);
2375 d->control->document()->setDefaultTextOption(opt);
2376}
2377
2378
2379/*!
2380 \property QPlainTextEdit::cursorWidth
2381
2382 This property specifies the width of the cursor in pixels. The default value is 1.
2383*/
2384int QPlainTextEdit::cursorWidth() const
2385{
2386 Q_D(const QPlainTextEdit);
2387 return d->control->cursorWidth();
2388}
2389
2390void QPlainTextEdit::setCursorWidth(int width)
2391{
2392 Q_D(QPlainTextEdit);
2393 d->control->setCursorWidth(width);
2394}
2395
2396
2397
2398/*!
2399 This function allows temporarily marking certain regions in the document
2400 with a given color, specified as \a selections. This can be useful for
2401 example in a programming editor to mark a whole line of text with a given
2402 background color to indicate the existence of a breakpoint.
2403
2404 \sa QTextEdit::ExtraSelection, extraSelections()
2405*/
2406void QPlainTextEdit::setExtraSelections(const QList<QTextEdit::ExtraSelection> &selections)
2407{
2408 Q_D(QPlainTextEdit);
2409 d->control->setExtraSelections(selections);
2410}
2411
2412/*!
2413 Returns previously set extra selections.
2414
2415 \sa setExtraSelections()
2416*/
2417QList<QTextEdit::ExtraSelection> QPlainTextEdit::extraSelections() const
2418{
2419 Q_D(const QPlainTextEdit);
2420 return d->control->extraSelections();
2421}
2422
2423/*!
2424 This function returns a new MIME data object to represent the contents
2425 of the text edit's current selection. It is called when the selection needs
2426 to be encapsulated into a new QMimeData object; for example, when a drag
2427 and drop operation is started, or when data is copied to the clipboard.
2428
2429 If you reimplement this function, note that the ownership of the returned
2430 QMimeData object is passed to the caller. The selection can be retrieved
2431 by using the textCursor() function.
2432*/
2433QMimeData *QPlainTextEdit::createMimeDataFromSelection() const
2434{
2435 Q_D(const QPlainTextEdit);
2436 return d->control->QWidgetTextControl::createMimeDataFromSelection();
2437}
2438
2439/*!
2440 This function returns \c true if the contents of the MIME data object, specified
2441 by \a source, can be decoded and inserted into the document. It is called
2442 for example when during a drag operation the mouse enters this widget and it
2443 is necessary to determine whether it is possible to accept the drag.
2444 */
2445bool QPlainTextEdit::canInsertFromMimeData(const QMimeData *source) const
2446{
2447 Q_D(const QPlainTextEdit);
2448 return d->control->QWidgetTextControl::canInsertFromMimeData(source);
2449}
2450
2451/*!
2452 This function inserts the contents of the MIME data object, specified
2453 by \a source, into the text edit at the current cursor position. It is
2454 called whenever text is inserted as the result of a clipboard paste
2455 operation, or when the text edit accepts data from a drag and drop
2456 operation.
2457*/
2458void QPlainTextEdit::insertFromMimeData(const QMimeData *source)
2459{
2460 Q_D(QPlainTextEdit);
2461 d->control->QWidgetTextControl::insertFromMimeData(source);
2462}
2463
2464/*!
2465 \property QPlainTextEdit::readOnly
2466 \brief whether the text edit is read-only
2467
2468 In a read-only text edit the user can only navigate through the
2469 text and select text; modifying the text is not possible.
2470
2471 This property's default is false.
2472*/
2473
2474bool QPlainTextEdit::isReadOnly() const
2475{
2476 Q_D(const QPlainTextEdit);
2477 return !d->control || !(d->control->textInteractionFlags() & Qt::TextEditable);
2478}
2479
2480void QPlainTextEdit::setReadOnly(bool ro)
2481{
2482 Q_D(QPlainTextEdit);
2483 Qt::TextInteractionFlags flags = Qt::NoTextInteraction;
2484 if (ro) {
2485 flags = Qt::TextSelectableByMouse;
2486 } else {
2487 flags = Qt::TextEditorInteraction;
2488 }
2489 d->control->setTextInteractionFlags(flags);
2490 setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
2491 QEvent event(QEvent::ReadOnlyChange);
2492 QCoreApplication::sendEvent(this, &event);
2493}
2494
2495/*!
2496 \property QPlainTextEdit::textInteractionFlags
2497
2498 Specifies how the label should interact with user input if it displays text.
2499
2500 If the flags contain either Qt::LinksAccessibleByKeyboard or Qt::TextSelectableByKeyboard
2501 then the focus policy is also automatically set to Qt::ClickFocus.
2502
2503 The default value depends on whether the QPlainTextEdit is read-only
2504 or editable.
2505*/
2506
2507void QPlainTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags)
2508{
2509 Q_D(QPlainTextEdit);
2510 d->control->setTextInteractionFlags(flags);
2511}
2512
2513Qt::TextInteractionFlags QPlainTextEdit::textInteractionFlags() const
2514{
2515 Q_D(const QPlainTextEdit);
2516 return d->control->textInteractionFlags();
2517}
2518
2519/*!
2520 Merges the properties specified in \a modifier into the current character
2521 format by calling QTextCursor::mergeCharFormat on the editor's cursor.
2522 If the editor has a selection then the properties of \a modifier are
2523 directly applied to the selection.
2524
2525 \sa QTextCursor::mergeCharFormat()
2526 */
2527void QPlainTextEdit::mergeCurrentCharFormat(const QTextCharFormat &modifier)
2528{
2529 Q_D(QPlainTextEdit);
2530 d->control->mergeCurrentCharFormat(modifier);
2531}
2532
2533/*!
2534 Sets the char format that is be used when inserting new text to \a
2535 format by calling QTextCursor::setCharFormat() on the editor's
2536 cursor. If the editor has a selection then the char format is
2537 directly applied to the selection.
2538 */
2539void QPlainTextEdit::setCurrentCharFormat(const QTextCharFormat &format)
2540{
2541 Q_D(QPlainTextEdit);
2542 d->control->setCurrentCharFormat(format);
2543}
2544
2545/*!
2546 Returns the char format that is used when inserting new text.
2547 */
2548QTextCharFormat QPlainTextEdit::currentCharFormat() const
2549{
2550 Q_D(const QPlainTextEdit);
2551 return d->control->currentCharFormat();
2552}
2553
2554
2555
2556/*!
2557 Convenience slot that inserts \a text at the current
2558 cursor position.
2559
2560 It is equivalent to
2561
2562 \snippet code/src_gui_widgets_qplaintextedit.cpp 1
2563 */
2564void QPlainTextEdit::insertPlainText(const QString &text)
2565{
2566 Q_D(QPlainTextEdit);
2567 d->control->insertPlainText(text);
2568}
2569
2570
2571/*!
2572 Moves the cursor by performing the given \a operation.
2573
2574 If \a mode is QTextCursor::KeepAnchor, the cursor selects the text it moves over.
2575 This is the same effect that the user achieves when they hold down the Shift key
2576 and move the cursor with the cursor keys.
2577
2578 \sa QTextCursor::movePosition()
2579*/
2580void QPlainTextEdit::moveCursor(QTextCursor::MoveOperation operation, QTextCursor::MoveMode mode)
2581{
2582 Q_D(QPlainTextEdit);
2583 d->control->moveCursor(operation, mode);
2584}
2585
2586/*!
2587 Returns whether text can be pasted from the clipboard into the textedit.
2588*/
2589bool QPlainTextEdit::canPaste() const
2590{
2591 Q_D(const QPlainTextEdit);
2592 return d->control->canPaste();
2593}
2594
2595/*!
2596 Convenience function to print the text edit's document to the given \a printer. This
2597 is equivalent to calling the print method on the document directly except that this
2598 function also supports QPrinter::Selection as print range.
2599
2600 \sa QTextDocument::print()
2601*/
2602#ifndef QT_NO_PRINTER
2603void QPlainTextEdit::print(QPagedPaintDevice *printer) const
2604{
2605 Q_D(const QPlainTextEdit);
2606 d->control->print(printer);
2607}
2608#endif
2609
2610/*! \property QPlainTextEdit::tabChangesFocus
2611 \brief whether \uicontrol Tab changes focus or is accepted as input
2612
2613 In some occasions text edits should not allow the user to input
2614 tabulators or change indentation using the \uicontrol Tab key, as this breaks
2615 the focus chain. The default is false.
2616
2617*/
2618
2619bool QPlainTextEdit::tabChangesFocus() const
2620{
2621 Q_D(const QPlainTextEdit);
2622 return d->tabChangesFocus;
2623}
2624
2625void QPlainTextEdit::setTabChangesFocus(bool b)
2626{
2627 Q_D(QPlainTextEdit);
2628 d->tabChangesFocus = b;
2629}
2630
2631/*!
2632 \property QPlainTextEdit::documentTitle
2633 \brief the title of the document parsed from the text.
2634
2635 By default, this property contains an empty string.
2636*/
2637
2638/*!
2639 \property QPlainTextEdit::lineWrapMode
2640 \brief the line wrap mode
2641
2642 The default mode is WidgetWidth which causes words to be
2643 wrapped at the right edge of the text edit. Wrapping occurs at
2644 whitespace, keeping whole words intact. If you want wrapping to
2645 occur within words use setWordWrapMode().
2646*/
2647
2648QPlainTextEdit::LineWrapMode QPlainTextEdit::lineWrapMode() const
2649{
2650 Q_D(const QPlainTextEdit);
2651 return d->lineWrap;
2652}
2653
2654void QPlainTextEdit::setLineWrapMode(LineWrapMode wrap)
2655{
2656 Q_D(QPlainTextEdit);
2657 if (d->lineWrap == wrap)
2658 return;
2659 d->lineWrap = wrap;
2660 d->updateDefaultTextOption();
2661 d->relayoutDocument();
2662 d->adjustScrollbars();
2663 ensureCursorVisible();
2664}
2665
2666/*!
2667 \property QPlainTextEdit::wordWrapMode
2668 \brief the mode QPlainTextEdit will use when wrapping text by words
2669
2670 By default, this property is set to QTextOption::WrapAtWordBoundaryOrAnywhere.
2671
2672 \sa QTextOption::WrapMode
2673*/
2674
2675QTextOption::WrapMode QPlainTextEdit::wordWrapMode() const
2676{
2677 Q_D(const QPlainTextEdit);
2678 return d->wordWrap;
2679}
2680
2681void QPlainTextEdit::setWordWrapMode(QTextOption::WrapMode mode)
2682{
2683 Q_D(QPlainTextEdit);
2684 if (mode == d->wordWrap)
2685 return;
2686 d->wordWrap = mode;
2687 d->updateDefaultTextOption();
2688}
2689
2690/*!
2691 \property QPlainTextEdit::backgroundVisible
2692 \brief whether the palette background is visible outside the document area
2693
2694 If set to true, the plain text edit paints the palette background
2695 on the viewport area not covered by the text document. Otherwise,
2696 if set to false, it won't. The feature makes it possible for
2697 the user to visually distinguish between the area of the document,
2698 painted with the base color of the palette, and the empty
2699 area not covered by any document.
2700
2701 The default is false.
2702*/
2703
2704bool QPlainTextEdit::backgroundVisible() const
2705{
2706 Q_D(const QPlainTextEdit);
2707 return d->backgroundVisible;
2708}
2709
2710void QPlainTextEdit::setBackgroundVisible(bool visible)
2711{
2712 Q_D(QPlainTextEdit);
2713 if (visible == d->backgroundVisible)
2714 return;
2715 d->backgroundVisible = visible;
2716 d->updateViewport();
2717}
2718
2719/*!
2720 \property QPlainTextEdit::centerOnScroll
2721 \brief whether the cursor should be centered on screen
2722
2723 If set to true, the plain text edit scrolls the document
2724 vertically to make the cursor visible at the center of the
2725 viewport. This also allows the text edit to scroll below the end
2726 of the document. Otherwise, if set to false, the plain text edit
2727 scrolls the smallest amount possible to ensure the cursor is
2728 visible. The same algorithm is applied to any new line appended
2729 through appendPlainText().
2730
2731 The default is false.
2732
2733 \sa centerCursor(), ensureCursorVisible()
2734*/
2735
2736bool QPlainTextEdit::centerOnScroll() const
2737{
2738 Q_D(const QPlainTextEdit);
2739 return d->centerOnScroll;
2740}
2741
2742void QPlainTextEdit::setCenterOnScroll(bool enabled)
2743{
2744 Q_D(QPlainTextEdit);
2745 if (enabled == d->centerOnScroll)
2746 return;
2747 d->centerOnScroll = enabled;
2748 d->adjustScrollbars();
2749}
2750
2751
2752
2753/*!
2754 Finds the next occurrence of the string, \a exp, using the given
2755 \a options. Returns \c true if \a exp was found and changes the
2756 cursor to select the match; otherwise returns \c false.
2757*/
2758bool QPlainTextEdit::find(const QString &exp, QTextDocument::FindFlags options)
2759{
2760 Q_D(QPlainTextEdit);
2761 return d->control->find(exp, options);
2762}
2763
2764/*!
2765 \fn bool QPlainTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2766
2767 \since 5.13
2768 \overload
2769
2770 Finds the next occurrence, matching the regular expression, \a exp, using the given
2771 \a options.
2772
2773 Returns \c true if a match was found and changes the cursor to select the match;
2774 otherwise returns \c false.
2775
2776 \warning For historical reasons, the case sensitivity option set on
2777 \a exp is ignored. Instead, the \a options are used to determine
2778 if the search is case sensitive or not.
2779*/
2780#if QT_CONFIG(regularexpression)
2781bool QPlainTextEdit::find(const QRegularExpression &exp, QTextDocument::FindFlags options)
2782{
2783 Q_D(QPlainTextEdit);
2784 return d->control->find(exp, options);
2785}
2786#endif
2787
2788/*!
2789 \fn void QPlainTextEdit::copyAvailable(bool yes)
2790
2791 This signal is emitted when text is selected or de-selected in the
2792 text edit.
2793
2794 When text is selected this signal will be emitted with \a yes set
2795 to true. If no text has been selected or if the selected text is
2796 de-selected this signal is emitted with \a yes set to false.
2797
2798 If \a yes is true then copy() can be used to copy the selection to
2799 the clipboard. If \a yes is false then copy() does nothing.
2800
2801 \sa selectionChanged()
2802*/
2803
2804
2805/*!
2806 \fn void QPlainTextEdit::selectionChanged()
2807
2808 This signal is emitted whenever the selection changes.
2809
2810 \sa copyAvailable()
2811*/
2812
2813/*!
2814 \fn void QPlainTextEdit::cursorPositionChanged()
2815
2816 This signal is emitted whenever the position of the
2817 cursor changed.
2818*/
2819
2820
2821
2822/*!
2823 \fn void QPlainTextEdit::updateRequest(const QRect &rect, int dy)
2824
2825 This signal is emitted when the text document needs an update of
2826 the specified \a rect. If the text is scrolled, \a rect will cover
2827 the entire viewport area. If the text is scrolled vertically, \a
2828 dy carries the amount of pixels the viewport was scrolled.
2829
2830 The purpose of the signal is to support extra widgets in plain
2831 text edit subclasses that e.g. show line numbers, breakpoints, or
2832 other extra information.
2833*/
2834
2835/*! \fn void QPlainTextEdit::blockCountChanged(int newBlockCount);
2836
2837 This signal is emitted whenever the block count changes. The new
2838 block count is passed in \a newBlockCount.
2839*/
2840
2841/*! \fn void QPlainTextEdit::modificationChanged(bool changed);
2842
2843 This signal is emitted whenever the content of the document
2844 changes in a way that affects the modification state. If \a
2845 changed is true, the document has been modified; otherwise it is
2846 false.
2847
2848 For example, calling setModified(false) on a document and then
2849 inserting text causes the signal to get emitted. If you undo that
2850 operation, causing the document to return to its original
2851 unmodified state, the signal will get emitted again.
2852*/
2853
2854
2855
2856
2857void QPlainTextEditPrivate::append(const QString &text, Qt::TextFormat format)
2858{
2859 Q_Q(QPlainTextEdit);
2860
2861 QTextDocument *document = control->document();
2862 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document->documentLayout());
2863 Q_ASSERT(documentLayout);
2864
2865 int maximumBlockCount = document->maximumBlockCount();
2866 if (maximumBlockCount)
2867 document->setMaximumBlockCount(0);
2868
2869 const bool atBottom = q->isVisible()
2870 && (control->blockBoundingRect(document->lastBlock()).bottom() - verticalOffset()
2871 <= viewport->rect().bottom());
2872
2873 if (!q->isVisible())
2874 showCursorOnInitialShow = true;
2875
2876 bool documentSizeChangedBlocked = documentLayout->priv()->blockDocumentSizeChanged;
2877 documentLayout->priv()->blockDocumentSizeChanged = true;
2878
2879 switch (format) {
2880 case Qt::RichText:
2881 control->appendHtml(text);
2882 break;
2883 case Qt::PlainText:
2884 control->appendPlainText(text);
2885 break;
2886 default:
2887 control->append(text);
2888 break;
2889 }
2890
2891 if (maximumBlockCount > 0) {
2892 if (document->blockCount() > maximumBlockCount) {
2893 bool blockUpdate = false;
2894 if (control->topBlock) {
2896 blockUpdate = true;
2897 emit q->updateRequest(viewport->rect(), 0);
2898 }
2899
2900 bool updatesBlocked = documentLayout->priv()->blockUpdate;
2901 documentLayout->priv()->blockUpdate = blockUpdate;
2902 QTextCursor cursor(document);
2903 cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);
2904 cursor.removeSelectedText();
2905 documentLayout->priv()->blockUpdate = updatesBlocked;
2906 }
2907 document->setMaximumBlockCount(maximumBlockCount);
2908 }
2909
2910 documentLayout->priv()->blockDocumentSizeChanged = documentSizeChangedBlocked;
2912
2913
2914 if (atBottom) {
2915 const bool needScroll = !centerOnScroll
2916 || control->blockBoundingRect(document->lastBlock()).bottom() - verticalOffset()
2917 > viewport->rect().bottom();
2918 if (needScroll)
2919 vbar->setValue(vbar->maximum());
2920 }
2921}
2922
2923
2924/*!
2925 Appends a new paragraph with \a text to the end of the text edit.
2926
2927 \sa appendHtml()
2928*/
2929
2930void QPlainTextEdit::appendPlainText(const QString &text)
2931{
2932 Q_D(QPlainTextEdit);
2933 d->append(text, Qt::PlainText);
2934}
2935
2936/*!
2937 Appends a new paragraph with \a html to the end of the text edit.
2938
2939 appendPlainText()
2940*/
2941
2942void QPlainTextEdit::appendHtml(const QString &html)
2943{
2944 Q_D(QPlainTextEdit);
2945 d->append(html, Qt::RichText);
2946}
2947
2949{
2950 Q_Q(QPlainTextEdit);
2951 QRect visible = viewport->rect();
2952 QRect cr = q->cursorRect();
2953 if (cr.top() < visible.top() || cr.bottom() > visible.bottom()) {
2954 ensureVisible(control->textCursor().position(), center);
2955 }
2956
2957 const bool rtl = q->isRightToLeft();
2958 if (cr.left() < visible.left() || cr.right() > visible.right()) {
2959 int x = cr.center().x() + horizontalOffset() - visible.width()/2;
2960 hbar->setValue(rtl ? hbar->maximum() - x : x);
2961 }
2962}
2963
2964/*!
2965 Ensures that the cursor is visible by scrolling the text edit if
2966 necessary.
2967
2968 \sa centerCursor(), centerOnScroll
2969*/
2970void QPlainTextEdit::ensureCursorVisible()
2971{
2972 Q_D(QPlainTextEdit);
2973 d->ensureCursorVisible(d->centerOnScroll);
2974}
2975
2976
2977/*! Scrolls the document in order to center the cursor vertically.
2978
2979\sa ensureCursorVisible(), centerOnScroll
2980 */
2981void QPlainTextEdit::centerCursor()
2982{
2983 Q_D(QPlainTextEdit);
2984 d->ensureVisible(textCursor().position(), true, true);
2985}
2986
2987/*!
2988 Returns the first visible block.
2989
2990 \sa blockBoundingRect()
2991 */
2992QTextBlock QPlainTextEdit::firstVisibleBlock() const
2993{
2994 Q_D(const QPlainTextEdit);
2995 return d->control->firstVisibleBlock();
2996}
2997
2998/*! Returns the content's origin in viewport coordinates.
2999
3000 The origin of the content of a plain text edit is always the top
3001 left corner of the first visible text block. The content offset
3002 is different from (0,0) when the text has been scrolled
3003 horizontally, or when the first visible block has been scrolled
3004 partially off the screen, i.e. the visible text does not start
3005 with the first line of the first visible block, or when the first
3006 visible block is the very first block and the editor displays a
3007 margin.
3008
3009 \sa firstVisibleBlock(), horizontalScrollBar(), verticalScrollBar()
3010 */
3011QPointF QPlainTextEdit::contentOffset() const
3012{
3013 Q_D(const QPlainTextEdit);
3014 return QPointF(-d->horizontalOffset(), -d->verticalOffset());
3015}
3016
3017
3018/*! Returns the bounding rectangle of the text \a block in content
3019 coordinates. Translate the rectangle with the contentOffset() to get
3020 visual coordinates on the viewport.
3021
3022 \sa firstVisibleBlock(), blockBoundingRect()
3023 */
3024QRectF QPlainTextEdit::blockBoundingGeometry(const QTextBlock &block) const
3025{
3026 Q_D(const QPlainTextEdit);
3027 return d->control->blockBoundingRect(block);
3028}
3029
3030/*!
3031 Returns the bounding rectangle of the text \a block in the block's own coordinates.
3032
3033 \sa blockBoundingGeometry()
3034 */
3035QRectF QPlainTextEdit::blockBoundingRect(const QTextBlock &block) const
3036{
3037 QPlainTextDocumentLayout *documentLayout = qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout());
3038 Q_ASSERT(documentLayout);
3039 return documentLayout->blockBoundingRect(block);
3040}
3041
3042/*!
3043 \property QPlainTextEdit::blockCount
3044 \brief the number of text blocks in the document.
3045
3046 By default, in an empty document, this property contains a value of 1.
3047*/
3048int QPlainTextEdit::blockCount() const
3049{
3050 return document()->blockCount();
3051}
3052
3053/*! Returns the paint context for the viewport(), useful only when
3054 reimplementing paintEvent().
3055 */
3056QAbstractTextDocumentLayout::PaintContext QPlainTextEdit::getPaintContext() const
3057{
3058 Q_D(const QPlainTextEdit);
3059 return d->control->getPaintContext(d->viewport);
3060}
3061
3062/*!
3063 \property QPlainTextEdit::maximumBlockCount
3064 \brief the limit for blocks in the document.
3065
3066 Specifies the maximum number of blocks the document may have. If there are
3067 more blocks in the document that specified with this property blocks are removed
3068 from the beginning of the document.
3069
3070 A negative or zero value specifies that the document may contain an unlimited
3071 amount of blocks.
3072
3073 The default value is 0.
3074
3075 Note that setting this property will apply the limit immediately to the document
3076 contents. Setting this property also disables the undo redo history.
3077
3078*/
3079
3080
3081/*!
3082 \fn void QPlainTextEdit::textChanged()
3083
3084 This signal is emitted whenever the document's content changes; for
3085 example, when text is inserted or deleted, or when formatting is applied.
3086*/
3087
3088/*!
3089 \fn void QPlainTextEdit::undoAvailable(bool available)
3090
3091 This signal is emitted whenever undo operations become available
3092 (\a available is true) or unavailable (\a available is false).
3093*/
3094
3095/*!
3096 \fn void QPlainTextEdit::redoAvailable(bool available)
3097
3098 This signal is emitted whenever redo operations become available
3099 (\a available is true) or unavailable (\a available is false).
3100*/
3101
3102QT_END_NAMESPACE
3103
3104#include "moc_qplaintextedit.cpp"
3105#include "moc_qplaintextedit_p.cpp"
friend class QPainter
QRect viewport() const
Returns the viewport rectangle.
void layoutBlock(const QTextBlock &block)
qreal blockWidth(const QTextBlock &block)
QPlainTextEditPrivate * mainViewPrivate
QPlainTextEdit * textEdit
void insertFromMimeData(const QMimeData *source) override
bool canInsertFromMimeData(const QMimeData *source) const override
QTextBlock firstVisibleBlock() const
QMimeData * createMimeDataFromSelection() const override
void pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode, bool moveCursor=true)
QPlainTextEditControl * control
void ensureVisible(int position, bool center, bool forceCenter=false)
qreal verticalOffset(int topBlock, int topLine) const
void setTopLine(int visualTopLine, int dx=0)
void verticalScrollbarActionTriggered(int action)
void ensureCursorVisible(bool center=false)
void setTopBlock(int newTopBlock, int newTopLine, int dx=0)
\inmodule QtCore\reentrant
Definition qpoint.h:232
Combined button and popup list for selecting options.
static QT_BEGIN_NAMESPACE bool shouldEnableInputMethod(QPlainTextEdit *control)
static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, const QRectF &gradientRect=QRectF())