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
qquicktext.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:critical reason:data-parser
4
5#include "qquicktext_p.h"
7
8#include <private/qqmldebugserviceinterfaces_p.h>
9#include <private/qqmldebugconnector_p.h>
10
11#include <QtQuick/private/qsgcontext_p.h>
12#include <private/qqmlglobal_p.h>
13#include <private/qsgadaptationlayer_p.h>
16
17#include <QtQuick/private/qsgtexture_p.h>
18
19#include <QtQml/qqmlinfo.h>
20#include <QtGui/qevent.h>
21#include <QtGui/qabstracttextdocumentlayout.h>
22#include <QtGui/qpainter.h>
23#include <QtGui/qtextdocument.h>
24#include <QtGui/qtextobject.h>
25#include <QtGui/qtextcursor.h>
26#include <QtGui/qguiapplication.h>
27#include <QtGui/qinputmethod.h>
28
29#include <private/qtextengine_p.h>
30#include <private/qquickstyledtext_p.h>
31#include <QtQuick/private/qquickpixmap_p.h>
32
33#include <qmath.h>
34#include <limits.h>
35
37
38Q_STATIC_LOGGING_CATEGORY(lcText, "qt.quick.text")
39
40using namespace Qt::StringLiterals;
41
42const QChar QQuickTextPrivate::elideChar = QChar(0x2026);
43
44#if !defined(QQUICKTEXT_LARGETEXT_THRESHOLD)
45 #define QQUICKTEXT_LARGETEXT_THRESHOLD 10000
46#endif
47// if QString::size() > largeTextSizeThreshold, we render more often, but only visible lines
48const int QQuickTextPrivate::largeTextSizeThreshold = QQUICKTEXT_LARGETEXT_THRESHOLD;
49
50QQuickTextPrivate::QQuickTextPrivate()
51 : fontInfo(font), lineWidth(0)
52 , color(0xFF000000), linkColor(0xFF0000FF), styleColor(0xFF000000)
53 , lineCount(1), multilengthEos(-1)
54 , elideMode(QQuickText::ElideNone), hAlign(QQuickText::AlignLeft), vAlign(QQuickText::AlignTop)
55 , wrapMode(QQuickText::NoWrap)
56 , style(QQuickText::Normal)
57 , renderType(QQuickTextUtil::textRenderType<QQuickText>())
58 , updateType(UpdatePaintNode)
59 , maximumLineCountValid(false), updateOnComponentComplete(true)
60 , widthExceeded(false), heightExceeded(false), internalWidthUpdate(false)
61 , requireImplicitSize(false), implicitWidthValid(false), implicitHeightValid(false)
62 , truncated(false), hAlignImplicit(true), rightToLeftText(false)
63 , layoutTextElided(false), textHasChanged(true), needToUpdateLayout(false), formatModifiesFontSize(false)
64 , polishSize(false)
65 , updateSizeRecursionGuard(false)
66 , containsUnscalableGlyphs(false)
67 , textFormatWarningDisplayed(false)
68 , effectiveTextFormat(QQuickText::AutoText)
69{
70 implicitAntialiasing = true;
71}
72
73QQuickTextPrivate::ExtraData::ExtraData()
74 : padding(0)
75 , topPadding(0)
76 , leftPadding(0)
77 , rightPadding(0)
78 , bottomPadding(0)
79 , explicitTopPadding(false)
80 , explicitLeftPadding(false)
81 , explicitRightPadding(false)
82 , explicitBottomPadding(false)
83 , lineHeight(1.0)
84 , doc(nullptr)
85 , minimumPixelSize(12)
86 , minimumPointSize(12)
87 , maximumLineCount(INT_MAX)
88 , renderTypeQuality(QQuickText::DefaultRenderTypeQuality)
89 , lineHeightValid(false)
90 , lineHeightMode(QQuickText::ProportionalHeight)
91 , fontSizeMode(QQuickText::FixedSize)
92{
93}
94
95void QQuickTextPrivate::init()
96{
97 Q_Q(QQuickText);
98 q->setAcceptedMouseButtons(Qt::LeftButton);
99 q->setFlag(QQuickItem::ItemHasContents);
100 q->setFlag(QQuickItem::ItemObservesViewport); // default until size is known
101}
102
103QQuickTextPrivate::~QQuickTextPrivate()
104{
105 if (extra.isAllocated()) {
106 qDeleteAll(extra->imgTags);
107 extra->imgTags.clear();
108 }
109}
110
111qreal QQuickTextPrivate::getImplicitWidth() const
112{
113 if (!requireImplicitSize) {
114 // We don't calculate implicitWidth unless it is required.
115 // We need to force a size update now to ensure implicitWidth is calculated
116 QQuickTextPrivate *me = const_cast<QQuickTextPrivate*>(this);
117 me->requireImplicitSize = true;
118 me->updateSize();
119 }
120 return implicitWidth;
121}
122
123qreal QQuickTextPrivate::getImplicitHeight() const
124{
125 if (!requireImplicitSize) {
126 QQuickTextPrivate *me = const_cast<QQuickTextPrivate*>(this);
127 me->requireImplicitSize = true;
128 me->updateSize();
129 }
130 return implicitHeight;
131}
132
133qreal QQuickTextPrivate::availableWidth() const
134{
135 Q_Q(const QQuickText);
136 return q->width() - q->leftPadding() - q->rightPadding();
137}
138
139qreal QQuickTextPrivate::availableHeight() const
140{
141 Q_Q(const QQuickText);
142 return q->height() - q->topPadding() - q->bottomPadding();
143}
144
145void QQuickTextPrivate::setTopPadding(qreal value, bool reset)
146{
147 Q_Q(QQuickText);
148 qreal oldPadding = q->topPadding();
149 if (!reset || extra.isAllocated()) {
150 extra.value().topPadding = value;
151 extra.value().explicitTopPadding = !reset;
152 }
153 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
154 updateSize();
155 emit q->topPaddingChanged();
156 }
157}
158
159void QQuickTextPrivate::setLeftPadding(qreal value, bool reset)
160{
161 Q_Q(QQuickText);
162 qreal oldPadding = q->leftPadding();
163 if (!reset || extra.isAllocated()) {
164 extra.value().leftPadding = value;
165 extra.value().explicitLeftPadding = !reset;
166 }
167 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
168 updateSize();
169 emit q->leftPaddingChanged();
170 }
171}
172
173void QQuickTextPrivate::setRightPadding(qreal value, bool reset)
174{
175 Q_Q(QQuickText);
176 qreal oldPadding = q->rightPadding();
177 if (!reset || extra.isAllocated()) {
178 extra.value().rightPadding = value;
179 extra.value().explicitRightPadding = !reset;
180 }
181 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
182 updateSize();
183 emit q->rightPaddingChanged();
184 }
185}
186
187void QQuickTextPrivate::setBottomPadding(qreal value, bool reset)
188{
189 Q_Q(QQuickText);
190 qreal oldPadding = q->bottomPadding();
191 if (!reset || extra.isAllocated()) {
192 extra.value().bottomPadding = value;
193 extra.value().explicitBottomPadding = !reset;
194 }
195 if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
196 updateSize();
197 emit q->bottomPaddingChanged();
198 }
199}
200
201void QQuickTextPrivate::decideEffectiveTextFormat(const QString &n)
202{
203 Q_Q(QQuickText);
204 effectiveTextFormat = q->textFormat();
205 if (effectiveTextFormat == QQuickText::AutoText) {
206 if (Qt::mightBeRichText(n))
207 effectiveTextFormat = QQuickText::StyledText;
208 else
209 effectiveTextFormat = QQuickText::PlainText;
210 }
211}
212
213/*!
214 \qmlproperty bool QtQuick::Text::antialiasing
215
216 Used to decide if the Text should use antialiasing or not. Only Text
217 with renderType of Text.NativeRendering can disable antialiasing.
218
219 The default is \c true.
220*/
221
222void QQuickText::q_updateLayout()
223{
224 Q_D(QQuickText);
225 d->updateLayout();
226}
227
228void QQuickTextPrivate::updateLayout()
229{
230 Q_Q(QQuickText);
231 if (!q->isComponentComplete()) {
232 updateOnComponentComplete = true;
233 return;
234 }
235 updateOnComponentComplete = false;
236 layoutTextElided = false;
237
238 needToUpdateLayout = false;
239
240 // Setup instance of QTextLayout for all cases other than richtext
241 if (!hasRichTextFormat()) {
242 if (textHasChanged) {
243 if (effectiveTextFormat == QQuickText::StyledText && !text.isEmpty()) {
244 layout.setFont(font);
245 // needs temporary bool because formatModifiesFontSize is in a bit-field
246 bool fontSizeModified = false;
247 QList<QQuickStyledTextImgTag*> someImgTags = extra.isAllocated() ? extra->imgTags : QList<QQuickStyledTextImgTag*>();
248 QQuickStyledText::parse(text, layout, someImgTags, q->baseUrl(), qmlContext(q), !maximumLineCountValid, &fontSizeModified);
249 if (someImgTags.size() || extra.isAllocated())
250 extra.value().imgTags = someImgTags;
251 formatModifiesFontSize = fontSizeModified;
252 multilengthEos = -1;
253 } else {
254 QString tmp = text;
255 multilengthEos = tmp.indexOf(QLatin1Char('\x9c'));
256 if (multilengthEos != -1)
257 tmp = tmp.mid(0, multilengthEos);
258 tmp.replace(QLatin1Char('\n'), QChar::LineSeparator);
259 layout.setText(tmp);
260 }
261 // Detect direction from the layout text (already stripped of
262 // HTML markup for StyledText, identical to source for plain).
263 rightToLeftText = layout.text().isRightToLeft();
264 determineHorizontalAlignment();
265 textHasChanged = false;
266 }
267 } else if (extra.isAllocated() && extra->lineHeightValid) {
268 ensureDoc();
269 QTextBlockFormat::LineHeightTypes type;
270 type = lineHeightMode() == QQuickText::FixedHeight ? QTextBlockFormat::FixedHeight : QTextBlockFormat::ProportionalHeight;
271 QTextBlockFormat blockFormat;
272 blockFormat.setLineHeight((lineHeightMode() == QQuickText::FixedHeight ? lineHeight() : lineHeight() * 100), type);
273 for (QTextBlock it = extra->doc->begin(); it != extra->doc->end(); it = it.next()) {
274 QTextCursor cursor(it);
275 cursor.mergeBlockFormat(blockFormat);
276 }
277 }
278
279 updateSize();
280
281 if (needToUpdateLayout) {
282 needToUpdateLayout = false;
283 textHasChanged = true;
284 updateLayout();
285 }
286
287 q->polish();
288}
289
290void QQuickTextPrivate::scheduleUpdatePaintNode()
291{
292 updateType = UpdatePaintNode;
293 dirty(QQuickItemPrivate::Content);
294}
295
296/*! \internal
297 QTextDocument::loadResource() calls this to load inline images etc.
298 But if it's a local file, don't do it: let QTextDocument::loadResource()
299 load it in the default way. QQuickPixmap is for QtQuick-specific uses.
300*/
301QVariant QQuickText::loadResource(int type, const QUrl &source)
302{
303 Q_D(QQuickText);
304 const QUrl url = d->extra->doc->baseUrl().resolved(source);
305 if (url.isLocalFile()) {
306 // qmlWarning if the file doesn't exist (because QTextDocument::loadResource() can't do that)
307 const QFileInfo fi(QQmlFile::urlToLocalFileOrQrc(url));
308 if (!fi.exists())
309 qmlWarning(this) << "Cannot open: " << url.toString();
310 // let QTextDocument::loadResource() handle local file loading
311 return {};
312 }
313
314 // If the image is in resources, load it here, because QTextDocument::loadResource() doesn't do that
315 if (!url.scheme().compare("qrc"_L1, Qt::CaseInsensitive)) {
316 // qmlWarning if the file doesn't exist
317 QFile f(QQmlFile::urlToLocalFileOrQrc(url));
318 if (f.open(QFile::ReadOnly)) {
319 QByteArray buf = f.readAll();
320 f.close();
321 QImage image;
322 image.loadFromData(buf);
323 if (!image.isNull())
324 return image;
325 }
326 // if we get here, loading failed
327 qmlWarning(this) << "Cannot read resource: " << f.fileName();
328 return {};
329 }
330
331 // see if we already started a load job
332 for (auto it = d->extra->pixmapsInProgress.cbegin(); it != d->extra->pixmapsInProgress.cend();) {
333 auto *job = *it;
334 if (job->url() == url) {
335 if (job->isError()) {
336 qmlWarning(this) << job->error();
337 delete *it;
338 d->extra->pixmapsInProgress.erase(it);
339 return QImage();
340 }
341 qCDebug(lcText) << "already downloading" << url;
342 // existing job: return a null variant if it's not done yet
343 return job->isReady() ? job->image() : QVariant();
344 }
345 ++it;
346 }
347 qCDebug(lcText) << "loading" << source << "resolved" << url
348 << "type" << static_cast<QTextDocument::ResourceType>(type);
349 QQmlContext *context = qmlContext(this);
350 Q_ASSERT(context);
351 // don't cache it in QQuickPixmapCache, because it's cached in QTextDocumentPrivate::cachedResources
352 QQuickPixmap *p = new QQuickPixmap(context->engine(), url, QQuickPixmap::Options{});
353 p->connectFinished(this, SLOT(resourceRequestFinished()));
354 d->extra->pixmapsInProgress.append(p);
355 // the new job is probably not done; return a null variant if the caller should poll again
356 return p->isReady() ? p->image() : QVariant();
357}
358
359/*! \internal
360 Handle completion of a download that QQuickText::loadResource() started.
361*/
362void QQuickText::resourceRequestFinished()
363{
364 Q_D(QQuickText);
365 bool allDone = true;
366 for (auto it = d->extra->pixmapsInProgress.begin(); it != d->extra->pixmapsInProgress.end();) {
367 auto *job = *it;
368 if (job->isError()) {
369 // get QTextDocument::loadResource() to call QQuickText::loadResource() again, to return the placeholder
370 qCDebug(lcText) << "failed to load" << job->url();
371 d->extra->doc->resource(QTextDocument::ImageResource, job->url());
372 } else if (job->isReady()) {
373 // get QTextDocument::loadResource() to call QQuickText::loadResource() again, and cache the result
374 auto res = d->extra->doc->resource(QTextDocument::ImageResource, job->url());
375 // If QTextDocument::resource() returned a valid variant, it's been cached too. Either way, the job is done.
376 qCDebug(lcText) << (res.isValid() ? "done downloading" : "failed to load") << job->url();
377 delete *it;
378 it = d->extra->pixmapsInProgress.erase(it);
379 } else {
380 allDone = false;
381 ++it;
382 }
383 }
384 if (allDone) {
385 Q_ASSERT(d->extra->pixmapsInProgress.isEmpty());
386 d->updateLayout();
387 }
388}
389
390/*! \internal
391 Handle completion of StyledText image downloads (there's no QTextDocument instance in that case).
392*/
393void QQuickText::imageDownloadFinished()
394{
395 Q_D(QQuickText);
396 if (!d->extra.isAllocated())
397 return;
398
399 if (std::any_of(d->extra->imgTags.cbegin(), d->extra->imgTags.cend(),
400 [] (auto *image) { return image->pix && image->pix->isLoading(); })) {
401 // return if we still have any active download
402 return;
403 }
404
405 // when all the remote images have been downloaded,
406 // if one of the sizes was not specified at parsing time
407 // we use the implicit size from pixmapcache and re-layout.
408
409 bool needToUpdateLayout = false;
410 for (QQuickStyledTextImgTag *img : std::as_const(d->extra->visibleImgTags)) {
411 if (!img->size.isValid()) {
412 img->size = img->pix->implicitSize();
413 needToUpdateLayout = true;
414 }
415 }
416
417 if (needToUpdateLayout) {
418 d->textHasChanged = true;
419 d->updateLayout();
420 } else {
421 d->scheduleUpdatePaintNode();
422 }
423}
424
425void QQuickTextPrivate::updateBaseline(qreal baseline, qreal dy)
426{
427 Q_Q(QQuickText);
428
429 qreal yoff = 0;
430
431 if (q->heightValid()) {
432 if (vAlign == QQuickText::AlignBottom)
433 yoff = dy;
434 else if (vAlign == QQuickText::AlignVCenter)
435 yoff = dy/2;
436 }
437
438 q->setBaselineOffset(baseline + yoff + q->topPadding());
439}
440
441void QQuickTextPrivate::signalSizeChange(const QSizeF &previousSize)
442{
443 Q_Q(QQuickText);
444 const QSizeF contentSize(q->contentWidth(), q->contentHeight());
445
446 if (contentSize != previousSize) {
447 emit q->contentSizeChanged();
448 if (contentSize.width() != previousSize.width())
449 emit q->contentWidthChanged(contentSize.width());
450 if (contentSize.height() != previousSize.height())
451 emit q->contentHeightChanged(contentSize.height());
452 }
453}
454
455void QQuickTextPrivate::updateSize()
456{
457 Q_Q(QQuickText);
458
459 if (!q->isComponentComplete()) {
460 updateOnComponentComplete = true;
461 return;
462 }
463
464 if (!requireImplicitSize) {
465 implicitWidthChanged();
466 implicitHeightChanged();
467 // if the implicitWidth is used, then updateSize() has already been called (recursively)
468 if (requireImplicitSize)
469 return;
470 }
471
472 qreal hPadding = q->leftPadding() + q->rightPadding();
473 qreal vPadding = q->topPadding() + q->bottomPadding();
474
475 const QSizeF previousSize(q->contentWidth(), q->contentHeight());
476
477 if (text.isEmpty() && !isLineLaidOutConnected() && fontSizeMode() == QQuickText::FixedSize) {
478 // How much more expensive is it to just do a full layout on an empty string here?
479 // There may be subtle differences in the height and baseline calculations between
480 // QTextLayout and QFontMetrics and the number of variables that can affect the size
481 // and position of a line is increasing.
482 QFontMetricsF fm(font);
483 qreal fontHeight = qCeil(fm.height()); // QScriptLine and therefore QTextLine rounds up
484 if (!hasRichTextFormat()) { // line height, so we will as well.
485 fontHeight = lineHeightMode() == QQuickText::FixedHeight
486 ? lineHeight()
487 : fontHeight * lineHeight();
488 }
489 updateBaseline(fm.ascent(), q->height() - fontHeight - vPadding);
490 q->setImplicitSize(hPadding, fontHeight + qMax(lineHeightOffset(), 0) + vPadding);
491 layedOutTextRect = QRectF(0, 0, 0, fontHeight);
492 advance = QSizeF();
493 signalSizeChange(previousSize);
494 lineCount = 1;
495 emit q->lineCountChanged();
496 if (truncated) {
497 truncated = false;
498 emit q->truncatedChanged();
499 }
500 scheduleUpdatePaintNode();
501 return;
502 }
503
504 QSizeF size(0, 0);
505
506 //setup instance of QTextLayout for all cases other than richtext
507 if (!hasRichTextFormat()) {
508 qreal baseline = 0;
509 QRectF textRect = setupTextLayout(&baseline);
510
511 if (internalWidthUpdate) // probably the result of a binding loop, but by letting it
512 return; // get this far we'll get a warning to that effect if it is.
513
514 layedOutTextRect = textRect;
515 size = textRect.size();
516 updateBaseline(baseline, q->height() - size.height() - vPadding);
517 } else {
518 widthExceeded = true; // always relayout rich text on width changes..
519 heightExceeded = false; // rich text layout isn't affected by height changes.
520 ensureDoc();
521 extra->doc->setDefaultFont(font);
522 QQuickText::HAlignment horizontalAlignment = q->effectiveHAlign();
523 if (rightToLeftText) {
524 if (horizontalAlignment == QQuickText::AlignLeft)
525 horizontalAlignment = QQuickText::AlignRight;
526 else if (horizontalAlignment == QQuickText::AlignRight)
527 horizontalAlignment = QQuickText::AlignLeft;
528 }
529 QTextOption option;
530 option.setAlignment((Qt::Alignment)int(horizontalAlignment | vAlign));
531 option.setWrapMode(QTextOption::WrapMode(wrapMode));
532 option.setUseDesignMetrics(renderType != QQuickText::NativeRendering);
533 extra->doc->setDefaultTextOption(option);
534 qreal naturalWidth = 0;
535 if (requireImplicitSize) {
536 extra->doc->setTextWidth(-1);
537 naturalWidth = extra->doc->idealWidth();
538 const bool wasInLayout = internalWidthUpdate;
539 internalWidthUpdate = true;
540 q->setImplicitWidth(naturalWidth + hPadding);
541 internalWidthUpdate = wasInLayout;
542 }
543 if (internalWidthUpdate)
544 return;
545
546 extra->doc->setPageSize(QSizeF(q->width(), -1));
547 if (q->widthValid() && (wrapMode != QQuickText::NoWrap || extra->doc->idealWidth() < availableWidth()))
548 extra->doc->setTextWidth(availableWidth());
549 else
550 extra->doc->setTextWidth(extra->doc->idealWidth()); // ### Text does not align if width is not set (QTextDoc bug)
551
552 QSizeF dsize = extra->doc->size();
553 layedOutTextRect = QRectF(QPointF(0,0), dsize);
554 size = QSizeF(extra->doc->idealWidth(),dsize.height());
555
556
557 qreal baseline = QFontMetricsF(font).ascent();
558 QTextBlock firstBlock = extra->doc->firstBlock();
559 if (firstBlock.isValid() && firstBlock.layout() != nullptr && firstBlock.lineCount() > 0)
560 baseline = firstBlock.layout()->lineAt(0).ascent();
561
562 updateBaseline(baseline, q->height() - size.height() - vPadding);
563
564 //### need to confirm cost of always setting these for richText
565 internalWidthUpdate = true;
566 qreal oldWidth = q->width();
567 qreal iWidth = -1;
568 if (!q->widthValid())
569 iWidth = size.width();
570 if (iWidth > -1)
571 q->setImplicitSize(iWidth + hPadding, size.height() + qMax(lineHeightOffset(), 0) + vPadding);
572 internalWidthUpdate = false;
573
574 // If the implicit width update caused a recursive change of the width,
575 // we will have skipped integral parts of the layout due to the
576 // internalWidthUpdate recursion guard. To make sure everything is up
577 // to date, we need to run a second pass over the layout when updateSize()
578 // is done.
579 if (!qFuzzyCompare(q->width(), oldWidth) && !updateSizeRecursionGuard) {
580 updateSizeRecursionGuard = true;
581 updateSize();
582 updateSizeRecursionGuard = false;
583 } else {
584 if (iWidth == -1)
585 q->setImplicitHeight(size.height() + lineHeightOffset() + vPadding);
586
587 QTextBlock firstBlock = extra->doc->firstBlock();
588 while (firstBlock.layout()->lineCount() == 0)
589 firstBlock = firstBlock.next();
590
591 QTextBlock lastBlock = extra->doc->lastBlock();
592 while (lastBlock.layout()->lineCount() == 0)
593 lastBlock = lastBlock.previous();
594
595 if (firstBlock.lineCount() > 0 && lastBlock.lineCount() > 0) {
596 QTextLine firstLine = firstBlock.layout()->lineAt(0);
597 QTextLine lastLine = lastBlock.layout()->lineAt(lastBlock.layout()->lineCount() - 1);
598 advance = QSizeF(lastLine.horizontalAdvance(),
599 (lastLine.y() + lastBlock.layout()->position().y() + lastLine.ascent()) - (firstLine.y() + firstBlock.layout()->position().y() + firstLine.ascent()));
600 } else {
601 advance = QSizeF();
602 }
603 }
604 }
605
606 signalSizeChange(previousSize);
607 scheduleUpdatePaintNode();
608}
609
610QQuickTextLine::QQuickTextLine()
611 : QObject(), m_line(nullptr), m_height(0), m_lineOffset(0)
612{
613}
614
615void QQuickTextLine::setLine(QTextLine *line)
616{
617 m_line = line;
618}
619
620void QQuickTextLine::setLineOffset(int offset)
621{
622 m_lineOffset = offset;
623}
624
625void QQuickTextLine::setFullLayoutTextLength(int length)
626{
627 m_fullLayoutTextLength = length;
628}
629
630int QQuickTextLine::number() const
631{
632 if (m_line)
633 return m_line->lineNumber() + m_lineOffset;
634 return 0;
635}
636
637qreal QQuickTextLine::implicitWidth() const
638{
639 if (m_line)
640 return m_line->naturalTextWidth();
641 return 0;
642}
643
644bool QQuickTextLine::isLast() const
645{
646 if (m_line && (m_line->textStart() + m_line->textLength()) == m_fullLayoutTextLength) {
647 // Ensure that isLast will change if the user reduced the width of the line
648 // so that the text no longer fits.
649 return m_line->width() >= m_line->naturalTextWidth();
650 }
651
652 return false;
653}
654
655qreal QQuickTextLine::width() const
656{
657 if (m_line)
658 return m_line->width();
659 return 0;
660}
661
662void QQuickTextLine::setWidth(qreal width)
663{
664 if (m_line)
665 m_line->setLineWidth(width);
666}
667
668qreal QQuickTextLine::height() const
669{
670 if (m_height)
671 return m_height;
672 if (m_line)
673 return m_line->height();
674 return 0;
675}
676
677void QQuickTextLine::setHeight(qreal height)
678{
679 if (m_line)
680 m_line->setPosition(QPointF(m_line->x(), m_line->y() - m_line->height() + height));
681 m_height = height;
682}
683
684qreal QQuickTextLine::x() const
685{
686 if (m_line)
687 return m_line->x();
688 return 0;
689}
690
691void QQuickTextLine::setX(qreal x)
692{
693 if (m_line)
694 m_line->setPosition(QPointF(x, m_line->y()));
695}
696
697qreal QQuickTextLine::y() const
698{
699 if (m_line)
700 return m_line->y();
701 return 0;
702}
703
704void QQuickTextLine::setY(qreal y)
705{
706 if (m_line)
707 m_line->setPosition(QPointF(m_line->x(), y));
708}
709
710bool QQuickTextPrivate::isLineLaidOutConnected()
711{
712 Q_Q(QQuickText);
713 IS_SIGNAL_CONNECTED(q, QQuickText, lineLaidOut, (QQuickTextLine *));
714}
715
716void QQuickTextPrivate::setupCustomLineGeometry(QTextLine &line, qreal &height, int fullLayoutTextLength, int lineOffset)
717{
718 Q_Q(QQuickText);
719
720 if (!textLine)
721 textLine.reset(new QQuickTextLine);
722 textLine->setFullLayoutTextLength(fullLayoutTextLength);
723 textLine->setLine(&line);
724 textLine->setY(height);
725 textLine->setHeight(0);
726 textLine->setLineOffset(lineOffset);
727
728 // use the text item's width by default if it has one and wrap is on or text must be aligned
729 if (q->widthValid() && (q->wrapMode() != QQuickText::NoWrap ||
730 q->effectiveHAlign() != QQuickText::AlignLeft))
731 textLine->setWidth(availableWidth());
732 else
733 textLine->setWidth(qreal(INT_MAX));
734 if (lineHeight() != 1.0)
735 textLine->setHeight((lineHeightMode() == QQuickText::FixedHeight) ? lineHeight() : line.height() * lineHeight());
736
737 emit q->lineLaidOut(textLine.get());
738
739 height += textLine->height();
740}
741
742// Position an inline image using cursorToX at pos and pos+1 to get both
743// edges of the inline object, then take the left edge. This handles
744// both LTR and RTL text directions correctly. The HMargin is added to
745// the X coordinate so the image is inset from the object boundary
746// (the object width already includes 2*HMargin).
747static void positionInlineImage(QQuickStyledTextImgTag *image, int textPos, const QTextLine &line)
748{
749 if (!image->size.isValid())
750 return; // Size unknown yet (remote image still loading)
751
752 const qreal x0 = line.cursorToX(textPos);
753 const qreal x1 = line.cursorToX(textPos + 1);
754 image->pos.setX(qMin(x0, x1) + QQuickStyledTextImgTag::HMargin);
755
756 qreal imgY;
757 switch (image->align) {
758 case QQuickStyledTextImgTag::Top:
759 imgY = 0;
760 break;
761 case QQuickStyledTextImgTag::Middle:
762 imgY = (line.height() - image->size.height()) / 2.0;
763 break;
764 default: // Bottom
765 imgY = line.height() - image->size.height();
766 break;
767 }
768 image->pos.setY(line.y() + imgY);
769}
770
771void QQuickTextPrivate::elideFormats(
772 const int start, const int length, int offset, QList<QTextLayout::FormatRange> *elidedFormats)
773{
774 const int end = start + length;
775 const QList<QTextLayout::FormatRange> formats = layout.formats();
776 for (int i = 0; i < formats.size(); ++i) {
777 QTextLayout::FormatRange format = formats.at(i);
778 const int formatLength = qMin(format.start + format.length, end) - qMax(format.start, start);
779 if (formatLength > 0) {
780 format.start = qMax(offset, format.start - start + offset);
781 format.length = formatLength;
782 elidedFormats->append(format);
783 }
784 }
785}
786
787QString QQuickTextPrivate::elidedText(qreal lineWidth, const QTextLine &line) const
788{
789 return layout.engine()->elidedText(
790 Qt::TextElideMode(elideMode),
791 QFixed::fromReal(lineWidth),
792 0,
793 line.textStart(),
794 line.textLength());
795}
796
797void QQuickTextPrivate::clearFormats()
798{
799 layout.clearFormats();
800 if (elideLayout)
801 elideLayout->clearFormats();
802}
803
804/*!
805 Lays out the QQuickTextPrivate::layout QTextLayout in the constraints of the QQuickText.
806
807 Returns the size of the final text. This can be used to position the text vertically (the text is
808 already absolutely positioned horizontally).
809*/
810
811QRectF QQuickTextPrivate::setupTextLayout(qreal *const baseline)
812{
813 Q_Q(QQuickText);
814
815 bool singlelineElide = elideMode != QQuickText::ElideNone && q->widthValid();
816 bool multilineElide = elideMode == QQuickText::ElideRight
817 && q->widthValid()
818 && (q->heightValid() || maximumLineCountValid);
819
820 if ((!requireImplicitSize || (implicitWidthValid && implicitHeightValid))
821 && ((singlelineElide && availableWidth() <= 0.)
822 || (multilineElide && q->heightValid() && availableHeight() <= 0.))) {
823 // we are elided and we have a zero width or height
824 widthExceeded = q->widthValid() && availableWidth() <= 0.;
825 heightExceeded = q->heightValid() && availableHeight() <= 0.;
826
827 if (!truncated) {
828 truncated = true;
829 emit q->truncatedChanged();
830 }
831 if (lineCount) {
832 lineCount = 0;
833 q->setFlag(QQuickItem::ItemObservesViewport, false);
834 emit q->lineCountChanged();
835 }
836
837 if (qFuzzyIsNull(q->width())) {
838 layout.setText(QString());
839 textHasChanged = true;
840 }
841
842 QFontMetricsF fm(font);
843 qreal height = (lineHeightMode() == QQuickText::FixedHeight) ? lineHeight() : qCeil(fm.height()) * lineHeight();
844 *baseline = fm.ascent();
845 return QRectF(0, 0, 0, height);
846 }
847
848 bool shouldUseDesignMetrics = renderType != QQuickText::NativeRendering;
849 layout.setCacheEnabled(true);
850 QTextOption textOption = layout.textOption();
851 if (textOption.alignment() != q->effectiveHAlign()
852 || textOption.wrapMode() != QTextOption::WrapMode(wrapMode)
853 || textOption.useDesignMetrics() != shouldUseDesignMetrics) {
854 textOption.setAlignment(Qt::Alignment(q->effectiveHAlign()));
855 textOption.setWrapMode(QTextOption::WrapMode(wrapMode));
856 textOption.setUseDesignMetrics(shouldUseDesignMetrics);
857 layout.setTextOption(textOption);
858 }
859 if (layout.font() != font)
860 layout.setFont(font);
861
862 lineWidth = (q->widthValid() || implicitWidthValid) && q->width() > 0
863 ? q->width()
864 : FLT_MAX;
865 qreal maxHeight = q->heightValid() ? availableHeight() : FLT_MAX;
866
867 const bool customLayout = isLineLaidOutConnected();
868 const bool wasTruncated = truncated;
869
870 bool canWrap = wrapMode != QQuickText::NoWrap && q->widthValid();
871
872 bool horizontalFit = fontSizeMode() & QQuickText::HorizontalFit && q->widthValid();
873 bool verticalFit = fontSizeMode() & QQuickText::VerticalFit
874 && (q->heightValid() || (maximumLineCountValid && canWrap));
875
876 const bool pixelSize = font.pixelSize() != -1;
877 QString layoutText = layout.text();
878
879 const qreal minimumSize = pixelSize
880 ? static_cast<qreal>(minimumPixelSize())
881 : minimumPointSize();
882 qreal largeFont = pixelSize ? font.pixelSize() : font.pointSizeF();
883 qreal smallFont = fontSizeMode() != QQuickText::FixedSize
884 ? qMin<qreal>(minimumSize, largeFont)
885 : largeFont;
886 qreal scaledFontSize = largeFont;
887 const qreal sizeFittingThreshold(0.01);
888
889 bool widthChanged = false;
890 widthExceeded = availableWidth() <= 0 && (singlelineElide || canWrap || horizontalFit);
891 heightExceeded = availableHeight() <= 0 && (multilineElide || verticalFit);
892
893 QRectF br;
894
895 QFont scaledFont = font;
896
897 int visibleCount = 0;
898 bool elide;
899 qreal height = 0;
900 QString elideText;
901 bool once = true;
902 int elideStart = 0;
903 int elideEnd = 0;
904 bool noBreakLastLine = multilineElide && (wrapMode == QQuickText::Wrap || wrapMode == QQuickText::WordWrap);
905
906 int eos = multilengthEos;
907
908 // Repeated layouts with reduced font sizes or abbreviated strings may be required if the text
909 // doesn't fit within the item dimensions, or a binding to implicitWidth/Height changes
910 // the item dimensions.
911 for (;;) {
912 if (!once) {
913 if (pixelSize)
914 scaledFont.setPixelSize(scaledFontSize);
915 else
916 scaledFont.setPointSizeF(scaledFontSize);
917 if (layout.font() != scaledFont)
918 layout.setFont(scaledFont);
919 }
920
921 layout.beginLayout();
922
923 bool wrapped = false;
924 bool truncateHeight = false;
925 truncated = false;
926 elide = false;
927 int unwrappedLineCount = 1;
928 bool uncountedLineBreak = false;
929 const int maxLineCount = maximumLineCount();
930 height = 0;
931 qreal naturalHeight = 0;
932 qreal previousHeight = 0;
933 br = QRectF();
934
935 QRectF unelidedRect;
936 QTextLine line;
937 for (visibleCount = 1; ; ++visibleCount) {
938 line = layout.createLine();
939
940 if (noBreakLastLine && visibleCount == maxLineCount)
941 layout.engine()->option.setWrapMode(QTextOption::WrapAnywhere);
942 if (customLayout) {
943 setupCustomLineGeometry(line, naturalHeight, layoutText.size());
944 } else {
945 setLineGeometry(line, lineWidth, naturalHeight);
946 }
947 if (noBreakLastLine && visibleCount == maxLineCount)
948 layout.engine()->option.setWrapMode(QTextOption::WrapMode(wrapMode));
949
950 unelidedRect = br.united(line.naturalTextRect());
951
952 // Elide the previous line if the accumulated height of the text exceeds the height
953 // of the element.
954 if (multilineElide && naturalHeight > maxHeight && visibleCount > 1) {
955 elide = true;
956 heightExceeded = true;
957 uncountedLineBreak = layoutText.at(line.textStart() + line.textLength() - 1)
958 == QChar::LineSeparator;
959 if (eos != -1) // There's an abbreviated string available, skip the rest as it's
960 break; // all going to be discarded.
961
962 truncated = true;
963 truncateHeight = true;
964
965 visibleCount -= 1;
966
967 const QTextLine previousLine = layout.lineAt(visibleCount - 1);
968 elideText = elidedText(line.width(), previousLine);
969 elideStart = previousLine.textStart();
970 elideEnd = line.textStart() + line.textLength();
971
972 height = previousHeight;
973 break;
974 }
975
976 const bool isLastLine = line.textStart() + line.textLength() >= layoutText.size();
977 if (isLastLine) {
978 if (singlelineElide && visibleCount == 1 && line.naturalTextWidth() > line.width()) {
979 // Elide a single previousLine of text if its width exceeds the element width.
980 elide = true;
981 widthExceeded = true;
982 if (eos != -1) // There's an abbreviated string available.
983 break;
984
985 truncated = true;
986 elideText = layout.engine()->elidedText(
987 Qt::TextElideMode(elideMode),
988 QFixed::fromReal(line.width()),
989 0,
990 line.textStart(),
991 line.textLength());
992 elideStart = line.textStart();
993 elideEnd = elideStart + line.textLength();
994 } else {
995 br = unelidedRect;
996 height = naturalHeight;
997 }
998 break;
999 } else {
1000 const bool wrappedLine = layoutText.at(line.textStart() + line.textLength() - 1) != QChar::LineSeparator;
1001 wrapped |= wrappedLine;
1002
1003 if (!wrappedLine)
1004 ++unwrappedLineCount;
1005
1006 // Stop if the maximum number of lines has been reached
1007 if (visibleCount == maxLineCount) {
1008 truncated = true;
1009 heightExceeded |= wrapped;
1010
1011 if (multilineElide) {
1012 elide = true;
1013 if (eos != -1) // There's an abbreviated string available
1014 break;
1015
1016 elideText = elidedText(line.width(), line);
1017 elideStart = line.textStart();
1018 elideEnd = elideStart + line.textLength();
1019 } else {
1020 br = unelidedRect;
1021 height = naturalHeight;
1022 }
1023 break;
1024 }
1025 }
1026 br = unelidedRect;
1027 previousHeight = height;
1028 height = naturalHeight;
1029 }
1030 widthExceeded |= wrapped;
1031
1032 // Save the implicit size of the text on the first layout only.
1033 if (once) {
1034 once = false;
1035
1036 // If implicit sizes are required, lay out any additional lines up to the maximum
1037 // line count, including the remainder of a paragraph wrapped on the last allowed line.
1038 const int paragraphCount = unwrappedLineCount + (uncountedLineBreak ? 1 : 0);
1039 if ((requireImplicitSize) && line.isValid() && paragraphCount <= maxLineCount) {
1040 // Layout the remainder of the wrapped lines up to maxLineCount to get the implicit
1041 // height.
1042 for (int lineCount = layout.lineCount(); lineCount < maxLineCount; ++lineCount) {
1043 line = layout.createLine();
1044 if (!line.isValid())
1045 break;
1046 if (layoutText.at(line.textStart() - 1) == QChar::LineSeparator)
1047 ++unwrappedLineCount;
1048 setLineGeometry(line, lineWidth, naturalHeight);
1049 }
1050
1051 // Create the remainder of the unwrapped lines up to maxLineCount to get the
1052 // implicit width.
1053 const int eol = line.isValid()
1054 ? line.textStart() + line.textLength()
1055 : layoutText.size();
1056 if (eol < layoutText.size() && layoutText.at(eol) != QChar::LineSeparator)
1057 line = layout.createLine();
1058 for (; line.isValid() && unwrappedLineCount < maxLineCount; ++unwrappedLineCount)
1059 line = layout.createLine();
1060 }
1061
1062 layout.endLayout();
1063
1064 const qreal naturalWidth = layout.maximumWidth();
1065
1066 bool wasInLayout = internalWidthUpdate;
1067 internalWidthUpdate = true;
1068 q->setImplicitSize(naturalWidth + q->leftPadding() + q->rightPadding(), naturalHeight + qMax(lineHeightOffset(), 0) + q->topPadding() + q->bottomPadding());
1069 internalWidthUpdate = wasInLayout;
1070
1071 // Update any variables that are dependent on the validity of the width or height.
1072 singlelineElide = elideMode != QQuickText::ElideNone && q->widthValid();
1073 multilineElide = elideMode == QQuickText::ElideRight
1074 && q->widthValid()
1075 && (q->heightValid() || maximumLineCountValid);
1076 canWrap = wrapMode != QQuickText::NoWrap && q->widthValid();
1077
1078 horizontalFit = fontSizeMode() & QQuickText::HorizontalFit && q->widthValid();
1079 verticalFit = fontSizeMode() & QQuickText::VerticalFit
1080 && (q->heightValid() || (maximumLineCountValid && canWrap));
1081
1082 const qreal oldWidth = lineWidth;
1083 const qreal oldHeight = maxHeight;
1084
1085 const qreal availWidth = availableWidth();
1086 const qreal availHeight = availableHeight();
1087
1088 lineWidth = q->widthValid() && q->width() > 0 ? availWidth : naturalWidth;
1089 maxHeight = q->heightValid() ? availHeight : FLT_MAX;
1090
1091 // If the width of the item has changed and it's possible the result of wrapping,
1092 // eliding, scaling has changed, or the text is not left aligned do another layout.
1093 if ((!qFuzzyCompare(lineWidth, oldWidth) || (widthExceeded && lineWidth > oldWidth))
1094 && (singlelineElide || multilineElide || canWrap || horizontalFit
1095 || q->effectiveHAlign() != QQuickText::AlignLeft)) {
1096 widthChanged = true;
1097 widthExceeded = lineWidth >= qMin(oldWidth, naturalWidth);
1098 heightExceeded = false;
1099 continue;
1100 }
1101
1102 // If the height of the item has changed and it's possible the result of eliding,
1103 // line count truncation or scaling has changed, do another layout.
1104 if ((maxHeight < qMin(oldHeight, naturalHeight) || (heightExceeded && maxHeight > oldHeight))
1105 && (multilineElide || (canWrap && maximumLineCountValid))) {
1106 widthExceeded = false;
1107 heightExceeded = false;
1108 continue;
1109 }
1110
1111 // If the horizontal alignment is not left and the width was not valid we need to relayout
1112 // now that we know the maximum line width.
1113 if (!q->widthValid() && !implicitWidthValid && unwrappedLineCount > 1 && q->effectiveHAlign() != QQuickText::AlignLeft) {
1114 widthExceeded = false;
1115 heightExceeded = false;
1116 continue;
1117 }
1118 } else if (widthChanged) {
1119 widthChanged = false;
1120 if (line.isValid()) {
1121 for (int lineCount = layout.lineCount(); lineCount < maxLineCount; ++lineCount) {
1122 line = layout.createLine();
1123 if (!line.isValid())
1124 break;
1125 setLineGeometry(line, lineWidth, naturalHeight);
1126 }
1127 }
1128 layout.endLayout();
1129
1130 bool wasInLayout = internalWidthUpdate;
1131 internalWidthUpdate = true;
1132 q->setImplicitHeight(naturalHeight + qMax(lineHeightOffset(), 0) + q->topPadding() + q->bottomPadding());
1133 internalWidthUpdate = wasInLayout;
1134
1135 multilineElide = elideMode == QQuickText::ElideRight
1136 && q->widthValid()
1137 && (q->heightValid() || maximumLineCountValid);
1138 verticalFit = fontSizeMode() & QQuickText::VerticalFit
1139 && (q->heightValid() || (maximumLineCountValid && canWrap));
1140
1141 const qreal oldHeight = maxHeight;
1142 maxHeight = q->heightValid() ? availableHeight() : FLT_MAX;
1143 // If the height of the item has changed and it's possible the result of eliding,
1144 // line count truncation or scaling has changed, do another layout.
1145 if ((maxHeight < qMin(oldHeight, naturalHeight) || (heightExceeded && maxHeight > oldHeight))
1146 && (multilineElide || (canWrap && maximumLineCountValid))) {
1147 widthExceeded = false;
1148 heightExceeded = false;
1149 continue;
1150 }
1151 } else {
1152 layout.endLayout();
1153 }
1154
1155 // If the next needs to be elided and there's an abbreviated string available
1156 // go back and do another layout with the abbreviated string.
1157 if (eos != -1 && elide) {
1158 int start = eos + 1;
1159 eos = text.indexOf(QLatin1Char('\x9c'), start);
1160 layoutText = text.mid(start, eos != -1 ? eos - start : -1);
1161 layoutText.replace(QLatin1Char('\n'), QChar::LineSeparator);
1162 layout.setText(layoutText);
1163 textHasChanged = true;
1164 continue;
1165 }
1166
1167 br.moveTop(0);
1168
1169 // Find the advance of the text layout
1170 if (layout.lineCount() > 0) {
1171 QTextLine firstLine = layout.lineAt(0);
1172 QTextLine lastLine = layout.lineAt(layout.lineCount() - 1);
1173 advance = QSizeF(lastLine.horizontalAdvance(),
1174 lastLine.y() - firstLine.y());
1175 } else {
1176 advance = QSizeF();
1177 }
1178
1179 if (!horizontalFit && !verticalFit)
1180 break;
1181
1182 // Can't find a better fit
1183 if (qFuzzyCompare(smallFont, largeFont))
1184 break;
1185
1186 // Try and find a font size that better fits the dimensions of the element.
1187 if (horizontalFit) {
1188 if (unelidedRect.width() > lineWidth || (!verticalFit && wrapped)) {
1189 widthExceeded = true;
1190 largeFont = scaledFontSize;
1191
1192 scaledFontSize = (smallFont + largeFont) / 2;
1193
1194 continue;
1195 } else if (!verticalFit) {
1196 smallFont = scaledFontSize;
1197
1198 // Check to see if the current scaledFontSize is acceptable
1199 if ((largeFont - smallFont) < sizeFittingThreshold)
1200 break;
1201
1202 scaledFontSize = (smallFont + largeFont) / 2;
1203 }
1204 }
1205
1206 if (verticalFit) {
1207 if (truncateHeight || unelidedRect.height() > maxHeight) {
1208 heightExceeded = true;
1209 largeFont = scaledFontSize;
1210
1211 scaledFontSize = (smallFont + largeFont) / 2;
1212
1213 } else {
1214 smallFont = scaledFontSize;
1215
1216 // Check to see if the current scaledFontSize is acceptable
1217 if ((largeFont - smallFont) < sizeFittingThreshold)
1218 break;
1219
1220 scaledFontSize = (smallFont + largeFont) / 2;
1221 }
1222 }
1223 }
1224
1225 implicitWidthValid = true;
1226 implicitHeightValid = true;
1227
1228 QFontInfo scaledFontInfo(scaledFont);
1229 if (fontInfo.weight() != scaledFontInfo.weight()
1230 || fontInfo.pixelSize() != scaledFontInfo.pixelSize()
1231 || fontInfo.italic() != scaledFontInfo.italic()
1232 || !qFuzzyCompare(fontInfo.pointSizeF(), scaledFontInfo.pointSizeF())
1233 || fontInfo.family() != scaledFontInfo.family()
1234 || fontInfo.styleName() != scaledFontInfo.styleName()) {
1235 fontInfo = scaledFontInfo;
1236 emit q->fontInfoChanged();
1237 }
1238
1239 if (eos != multilengthEos)
1240 truncated = true;
1241
1242 assignedFont = QFontInfo(font).family();
1243
1244 if (elide) {
1245 if (!elideLayout) {
1246 elideLayout.reset(new QTextLayout);
1247 elideLayout->setCacheEnabled(true);
1248 }
1249 QTextEngine *engine = layout.engine();
1250 if (engine && engine->hasFormats()) {
1251 QList<QTextLayout::FormatRange> formats;
1252 switch (elideMode) {
1253 case QQuickText::ElideRight:
1254 elideFormats(elideStart, elideText.size() - 1, 0, &formats);
1255 break;
1256 case QQuickText::ElideLeft:
1257 elideFormats(elideEnd - elideText.size() + 1, elideText.size() - 1, 1, &formats);
1258 break;
1259 case QQuickText::ElideMiddle: {
1260 const int index = elideText.indexOf(elideChar);
1261 if (index != -1) {
1262 elideFormats(elideStart, index, 0, &formats);
1263 elideFormats(
1264 elideEnd - elideText.size() + index + 1,
1265 elideText.size() - index - 1,
1266 index + 1,
1267 &formats);
1268 }
1269 break;
1270 }
1271 default:
1272 break;
1273 }
1274 elideLayout->setFormats(formats);
1275 }
1276
1277 elideLayout->setFont(layout.font());
1278 elideLayout->setTextOption(layout.textOption());
1279 elideLayout->setText(elideText);
1280 elideLayout->beginLayout();
1281
1282 QTextLine elidedLine = elideLayout->createLine();
1283 elidedLine.setPosition(QPointF(0, height));
1284 if (customLayout) {
1285 setupCustomLineGeometry(elidedLine, height, elideText.size(), visibleCount - 1);
1286 } else {
1287 setLineGeometry(elidedLine, lineWidth, height);
1288 }
1289 elideLayout->endLayout();
1290
1291 br = br.united(elidedLine.naturalTextRect());
1292
1293 if (visibleCount == 1)
1294 layout.clearLayout();
1295 } else {
1296 elideLayout.reset();
1297 }
1298
1299 // Position inline images on all visible lines.
1300 // When eliding, the last visible line comes from the elide layout.
1301 if (extra.isAllocated()) {
1302 extra->visibleImgTags.clear();
1303 const int mainLineCount = elide ? visibleCount - 1 : visibleCount;
1304 for (int i = 0; i < mainLineCount; ++i)
1305 positionInlineImages(layout.lineAt(i), layout.formats());
1306 if (elideLayout)
1307 positionInlineImages(elideLayout->lineAt(0), elideLayout->formats());
1308 }
1309
1310 QTextLine firstLine = visibleCount == 1 && elideLayout
1311 ? elideLayout->lineAt(0)
1312 : layout.lineAt(0);
1313 if (firstLine.isValid())
1314 *baseline = firstLine.y() + firstLine.ascent();
1315
1316 if (!customLayout)
1317 br.setHeight(height);
1318
1319 //Update the number of visible lines
1320 if (lineCount != visibleCount) {
1321 lineCount = visibleCount;
1322 emit q->lineCountChanged();
1323 }
1324
1325 if (truncated != wasTruncated)
1326 emit q->truncatedChanged();
1327
1328 return br;
1329}
1330
1331void QQuickTextPrivate::positionInlineImages(const QTextLine &line, const QList<QTextLayout::FormatRange> &formats)
1332{
1333 Q_Q(QQuickText);
1334 if (!extra.isAllocated())
1335 return;
1336
1337 const int lineStart = line.textStart();
1338 const int lineEnd = lineStart + line.textLength();
1339
1340 for (const auto &range : formats) {
1341 if (!range.format.isImageFormat())
1342 continue;
1343 if (range.start < lineStart || range.start >= lineEnd)
1344 continue;
1345
1346 const int imgIndex = range.format.objectIndex();
1347 if (imgIndex < 0 || imgIndex >= extra->imgTags.size())
1348 continue;
1349
1350 QQuickStyledTextImgTag *image = extra->imgTags.at(imgIndex);
1351
1352 if (!image->pix) {
1353 const QQmlContext *context = qmlContext(q);
1354 const QUrl url = context->resolvedUrl(q->baseUrl()).resolved(image->url);
1355 image->pix.reset(new QQuickPixmap(context->engine(), url, QRect(), image->size * effectiveDevicePixelRatio()));
1356
1357 if (image->pix->isLoading()) {
1358 image->pix->connectFinished(q, SLOT(imageDownloadFinished()));
1359 } else if (image->pix->isReady()) {
1360 if (!image->size.isValid()) {
1361 image->size = image->pix->implicitSize();
1362 // if the size of the image was not explicitly set, we need to
1363 // call updateLayout() once again.
1364 needToUpdateLayout = true;
1365 }
1366 } else if (image->pix->isError()) {
1367 qmlWarning(q) << image->pix->error();
1368 }
1369 }
1370
1371 positionInlineImage(image, range.start, line);
1372 extra->visibleImgTags << image;
1373 }
1374}
1375
1376void QQuickTextPrivate::setLineGeometry(QTextLine &line, qreal lineWidth, qreal &height)
1377{
1378 line.setLineWidth(lineWidth);
1379 line.setPosition(QPointF(line.position().x(), height));
1380 height += (lineHeightMode() == QQuickText::FixedHeight) ? lineHeight()
1381 : line.height() * lineHeight();
1382}
1383
1384/*!
1385 Returns the y offset when aligning text with a non-1.0 lineHeight
1386*/
1387int QQuickTextPrivate::lineHeightOffset() const
1388{
1389 QFontMetricsF fm(font);
1390 qreal fontHeight = qCeil(fm.height()); // QScriptLine and therefore QTextLine rounds up
1391 return lineHeightMode() == QQuickText::FixedHeight ? fontHeight - lineHeight()
1392 : (1.0 - lineHeight()) * fontHeight;
1393}
1394
1395/*!
1396 Ensures the QQuickTextPrivate::doc variable is set to a valid text document
1397*/
1398void QQuickTextPrivate::ensureDoc()
1399{
1400 if (!extra.isAllocated() || !extra->doc) {
1401 Q_Q(QQuickText);
1402 extra.value().doc = new QTextDocument(q);
1403 auto *doc = extra->doc;
1404 extra->imageHandler = new QQuickTextImageHandler(doc);
1405 doc->documentLayout()->registerHandler(QTextFormat::ImageObject, extra->imageHandler);
1406 doc->setPageSize(QSizeF(0, 0));
1407 doc->setDocumentMargin(0);
1408 const QQmlContext *context = qmlContext(q);
1409 doc->setBaseUrl(context ? context->resolvedUrl(q->baseUrl()) : q->baseUrl());
1410 }
1411}
1412
1413void QQuickTextPrivate::updateDocumentText()
1414{
1415 ensureDoc();
1416#if QT_CONFIG(textmarkdownreader)
1417 if (effectiveTextFormat == QQuickText::MarkdownText)
1418 extra->doc->setMarkdown(text);
1419 else
1420#endif
1421#if QT_CONFIG(texthtmlparser)
1422 extra->doc->setHtml(text);
1423#else
1424 extra->doc->setPlainText(text);
1425#endif
1426 rightToLeftText = extra->doc->toPlainText().isRightToLeft();
1427 determineHorizontalAlignment();
1428}
1429
1430/*!
1431 \qmltype Text
1432 \nativetype QQuickText
1433 \inqmlmodule QtQuick
1434 \ingroup qtquick-visual
1435 \inherits Item
1436 \brief Specifies how to add formatted text to a scene.
1437
1438 Text items can display both plain and rich text. For example, you can define
1439 red text with a specific font and size like this:
1440
1441 \qml
1442 Text {
1443 text: "Hello World!"
1444 font.family: "Helvetica"
1445 font.pointSize: 24
1446 color: "red"
1447 }
1448 \endqml
1449
1450 Use HTML-style markup or Markdown to define rich text:
1451
1452 \if defined(onlinedocs)
1453 \tab {build-qt-app}{tab-html}{HTML-style}{checked}
1454 \tab {build-qt-app}{tab-md}{Markdown}{}
1455 \tabcontent {tab-html}
1456 \else
1457 \section1 Using HTML-style
1458 \endif
1459 \qml
1460 Text {
1461 text: "<b>Hello</b> <i>World!</i>"
1462 }
1463 \endqml
1464 \if defined(onlinedocs)
1465 \endtabcontent
1466 \tabcontent {tab-md}
1467 \else
1468 \section1 Using Markdown
1469 \endif
1470 \qml
1471 Text {
1472 text: "**Hello** *World!*"
1473 }
1474 \endqml
1475 \if defined(onlinedocs)
1476 \endtabcontent
1477 \endif
1478
1479 \image declarative-text.png {Markdown styling to show Hello in bold
1480 and World in italics}
1481
1482 If height and width are not explicitly set, Text will try to determine how
1483 much room is needed and set it accordingly. Unless \l wrapMode is set, it
1484 will always prefer width to height (all text will be placed on a single
1485 line).
1486
1487 To fit a single line of plain text to a set width, you can use the \l elide
1488 property.
1489
1490 \note The \l{Supported HTML Subset} is limited. It is not intended to be compliant with the
1491 HTML standard but is provided as a convenience for applying styles to text labels. Also, if the
1492 text contains HTML \c img tags that load remote images, the text will be reloaded.
1493
1494 Text provides read-only text. For editable text, see \l TextEdit.
1495
1496 \warning By default, Text will detect the \l textFormat based on the contents in \l{text}.
1497 If it determined to be either \c Text.StyledText or \c Text.MarkdownText, the Text component
1498 will support rich text features such as changing colors, font styles and inline images. This
1499 functionality includes loading images remotely over the network. Thus, when displaying
1500 user-controlled, untrusted content, the \l textFormat should either be explicitly set to
1501 \c Text.PlainText, or the contents should be stripped of unwanted tags.
1502
1503 \sa {Qt Quick Examples - Text#Fonts}{Fonts example}
1504*/
1505QQuickText::QQuickText(QQuickItem *parent)
1506: QQuickImplicitSizeItem(*(new QQuickTextPrivate), parent)
1507{
1508 Q_D(QQuickText);
1509 d->init();
1510}
1511
1512QQuickText::QQuickText(QQuickTextPrivate &dd, QQuickItem *parent)
1513: QQuickImplicitSizeItem(dd, parent)
1514{
1515 Q_D(QQuickText);
1516 d->init();
1517}
1518
1519QQuickText::~QQuickText()
1520{
1521 Q_D(QQuickText);
1522 if (d->extra.isAllocated()) {
1523 qDeleteAll(d->extra->pixmapsInProgress);
1524 d->extra->pixmapsInProgress.clear();
1525 }
1526}
1527
1528/*!
1529 \qmlproperty bool QtQuick::Text::clip
1530 This property holds whether the text is clipped.
1531
1532 Note that if the text does not fit in the bounding rectangle, it will be abruptly chopped.
1533
1534 If you want to display potentially long text in a limited space, you probably want to use \c elide instead.
1535*/
1536
1537/*!
1538 \qmlsignal QtQuick::Text::lineLaidOut(object line)
1539
1540 This signal is emitted for each line of text that is laid out during the layout
1541 process in plain text or styled text mode. It is not emitted in rich text mode.
1542 The specified \a line object provides more details about the line that
1543 is currently being laid out.
1544
1545 This gives the opportunity to position and resize a line as it is being laid out.
1546 It can for example be used to create columns or lay out text around objects.
1547
1548 The properties of the specified \a line object are:
1549
1550 \table
1551 \header
1552 \li Property name
1553 \li Description
1554 \row
1555 \li number (read-only)
1556 \li Line number, starts with zero.
1557 \row
1558 \li x
1559 \li Specifies the line's x position inside the \c Text element.
1560 \row
1561 \li y
1562 \li Specifies the line's y position inside the \c Text element.
1563 \row
1564 \li width
1565 \li Specifies the width of the line.
1566 \row
1567 \li height
1568 \li Specifies the height of the line.
1569 \row
1570 \li implicitWidth (read-only)
1571 \li The width that the line would naturally occupy based on its contents,
1572 not taking into account any modifications made to \e width.
1573 \row
1574 \li isLast (read-only)
1575 \li Whether the line is the last. This property can change if you
1576 set the \e width property to a different value.
1577 \endtable
1578
1579 For example, this will move the first 5 lines of a Text item by 100 pixels to the right:
1580 \code
1581 onLineLaidOut: (line)=> {
1582 if (line.number < 5) {
1583 line.x = line.x + 100
1584 line.width = line.width - 100
1585 }
1586 }
1587 \endcode
1588
1589 The following example will allow you to position an item at the end of the last line:
1590 \code
1591 onLineLaidOut: (line)=> {
1592 if (line.isLast) {
1593 lastLineMarker.x = line.x + line.implicitWidth
1594 lastLineMarker.y = line.y + (line.height - lastLineMarker.height) / 2
1595 }
1596 }
1597 \endcode
1598*/
1599
1600/*!
1601 \qmlsignal QtQuick::Text::linkActivated(string link)
1602
1603 This signal is emitted when the user clicks on a link embedded in the text.
1604 The link must be in rich text or HTML format and the
1605 \a link string provides access to the particular link.
1606
1607 \snippet qml/text/onLinkActivated.qml 0
1608
1609 The example code will display the text
1610 "See the \l{http://qt-project.org}{Qt Project website}."
1611
1612 Clicking on the highlighted link will output
1613 \tt{http://qt-project.org link activated} to the console.
1614*/
1615
1616/*!
1617 \qmlproperty string QtQuick::Text::font.family
1618
1619 Sets the family name of the font.
1620
1621 \include qmltypereference.qdoc qml-font-family
1622*/
1623
1624/*!
1625 \qmlproperty string QtQuick::Text::font.styleName
1626 \since 5.6
1627
1628 Sets the style name of the font.
1629
1630 \include qmltypereference.qdoc qml-font-style-name
1631*/
1632
1633/*!
1634 \qmlproperty bool QtQuick::Text::font.bold
1635
1636 Sets whether the font weight is bold.
1637*/
1638
1639/*!
1640 \qmlproperty int QtQuick::Text::font.weight
1641
1642 \include qmltypereference.qdoc qml-font-weight
1643*/
1644
1645/*!
1646 \qmlproperty bool QtQuick::Text::font.italic
1647
1648 Sets whether the font has an italic style.
1649*/
1650
1651/*!
1652 \qmlproperty bool QtQuick::Text::font.underline
1653
1654 Sets whether the text is underlined.
1655*/
1656
1657/*!
1658 \qmlproperty bool QtQuick::Text::font.strikeout
1659
1660 Sets whether the font has a strikeout style.
1661*/
1662
1663/*!
1664 \qmlproperty real QtQuick::Text::font.pointSize
1665
1666 Sets the font size in points. The point size must be greater than zero.
1667*/
1668
1669/*!
1670 \qmlproperty int QtQuick::Text::font.pixelSize
1671
1672 Sets the font size in pixels.
1673
1674 Using this function makes the font device dependent.
1675 Use \c pointSize to set the size of the font in a device independent manner.
1676*/
1677
1678/*!
1679 \qmlproperty real QtQuick::Text::font.letterSpacing
1680
1681 Sets the letter spacing for the font.
1682
1683 \include qmltypereference.qdoc qml-font-letter-spacing
1684*/
1685
1686/*!
1687 \qmlproperty real QtQuick::Text::font.wordSpacing
1688
1689 Sets the word spacing for the font.
1690
1691 \include qmltypereference.qdoc qml-font-word-spacing
1692*/
1693
1694/*!
1695 \qmlproperty enumeration QtQuick::Text::font.capitalization
1696
1697 Sets the capitalization for the text.
1698
1699 \include qmltypereference.qdoc qml-font-capitalization
1700*/
1701
1702/*!
1703 \qmlproperty enumeration QtQuick::Text::font.hintingPreference
1704 \since 5.8
1705
1706 Sets the preferred hinting on the text.
1707
1708 \include qmltypereference.qdoc qml-font-hinting-preference
1709*/
1710
1711/*!
1712 \qmlproperty bool QtQuick::Text::font.kerning
1713 \since 5.10
1714
1715 \include qmltypereference.qdoc qml-font-kerning
1716*/
1717
1718/*!
1719 \qmlproperty bool QtQuick::Text::font.preferShaping
1720 \since 5.10
1721
1722 \include qmltypereference.qdoc qml-font-prefer-shaping
1723*/
1724
1725/*!
1726 \qmlproperty object QtQuick::Text::font.variableAxes
1727 \since 6.7
1728
1729 \include qmltypereference.qdoc qml-font-variable-axes
1730*/
1731
1732
1733/*!
1734 \qmlproperty object QtQuick::Text::font.features
1735 \since 6.6
1736
1737 \include qmltypereference.qdoc qml-font-features
1738*/
1739
1740/*!
1741 \qmlproperty bool QtQuick::Text::font.contextFontMerging
1742 \since 6.8
1743
1744 \include qmltypereference.qdoc qml-font-context-font-merging
1745*/
1746
1747/*!
1748 \qmlproperty bool QtQuick::Text::font.preferTypoLineMetrics
1749 \since 6.8
1750
1751 \include qmltypereference.qdoc qml-font-prefer-typo-line-metrics
1752*/
1753
1754
1755QFont QQuickText::font() const
1756{
1757 Q_D(const QQuickText);
1758 return d->sourceFont;
1759}
1760
1761void QQuickText::setFont(const QFont &font)
1762{
1763 Q_D(QQuickText);
1764 if (d->sourceFont == font)
1765 return;
1766
1767 d->sourceFont = font;
1768 QFont oldFont = d->font;
1769 d->font = font;
1770
1771 if (!antialiasing())
1772 d->font.setStyleStrategy(QFont::NoAntialias);
1773
1774 if (d->font.pointSizeF() != -1) {
1775 // 0.5pt resolution
1776 qreal size = qRound(d->font.pointSizeF()*2.0);
1777 d->font.setPointSizeF(size/2.0);
1778 }
1779
1780 if (oldFont != d->font) {
1781 // if the format changes the size of the text
1782 // with headings or <font> tag, we need to re-parse
1783 if (d->formatModifiesFontSize)
1784 d->textHasChanged = true;
1785 d->implicitWidthValid = false;
1786 d->implicitHeightValid = false;
1787 d->updateLayout();
1788 }
1789
1790 emit fontChanged(d->sourceFont);
1791}
1792
1793void QQuickText::itemChange(ItemChange change, const ItemChangeData &value)
1794{
1795 Q_D(QQuickText);
1796 Q_UNUSED(value);
1797 switch (change) {
1798 case ItemAntialiasingHasChanged:
1799 if (!antialiasing())
1800 d->font.setStyleStrategy(QFont::NoAntialias);
1801 else
1802 d->font.setStyleStrategy(QFont::PreferAntialias);
1803 d->implicitWidthValid = false;
1804 d->implicitHeightValid = false;
1805 d->updateLayout();
1806 break;
1807
1808 case ItemDevicePixelRatioHasChanged:
1809 {
1810 bool needUpdateLayout = false;
1811 if (d->containsUnscalableGlyphs) {
1812 // Native rendering optimizes for a given pixel grid, so its results must not be scaled.
1813 // Text layout code respects the current device pixel ratio automatically, we only need
1814 // to rerun layout after the ratio changed.
1815 // Changes of implicit size should be minimal; they are hard to avoid.
1816 d->implicitWidthValid = false;
1817 d->implicitHeightValid = false;
1818 needUpdateLayout = true;
1819 }
1820
1821 if (d->extra.isAllocated()) {
1822 // check if we have scalable inline images with explicit size set, which should be reloaded
1823 for (QQuickStyledTextImgTag *image : std::as_const(d->extra->visibleImgTags)) {
1824 if (image->size.isValid() && QQuickPixmap::isScalableImageFormat(image->url)) {
1825 image->pix.reset();
1826 needUpdateLayout = true;
1827 }
1828 }
1829 }
1830
1831 if (needUpdateLayout)
1832 d->updateLayout();
1833 }
1834 break;
1835
1836 default:
1837 break;
1838 }
1839 QQuickItem::itemChange(change, value);
1840}
1841
1842/*!
1843 \qmlproperty string QtQuick::Text::text
1844
1845 The text to display. Text supports both plain and rich text strings.
1846
1847 The item will try to automatically determine whether the text should
1848 be treated as styled text. This determination is made using Qt::mightBeRichText().
1849 However, detection of Markdown is not automatic.
1850
1851 \sa textFormat
1852*/
1853QString QQuickText::text() const
1854{
1855 Q_D(const QQuickText);
1856 return d->text;
1857}
1858
1859void QQuickText::setText(const QString &n)
1860{
1861 Q_D(QQuickText);
1862 if (d->text == n)
1863 return;
1864
1865 d->decideEffectiveTextFormat(n);
1866 Q_ASSERT(d->effectiveTextFormat != AutoText);
1867
1868 d->text = n;
1869 if (isComponentComplete()) {
1870 if (d->hasRichTextFormat())
1871 d->updateDocumentText();
1872 else
1873 d->clearFormats();
1874 }
1875 d->textHasChanged = true;
1876 d->implicitWidthValid = false;
1877 d->implicitHeightValid = false;
1878
1879 if (d->extra.isAllocated()) {
1880 qDeleteAll(d->extra->imgTags);
1881 d->extra->imgTags.clear();
1882 }
1883 setFlag(QQuickItem::ItemObservesViewport, n.size() > QQuickTextPrivate::largeTextSizeThreshold);
1884 d->updateLayout();
1885 setAcceptHoverEvents(d->effectiveTextFormat != PlainText);
1886 emit textChanged(d->text);
1887}
1888
1889/*!
1890 \qmlproperty color QtQuick::Text::color
1891
1892 The text color.
1893
1894 An example of green text defined using hexadecimal notation:
1895 \qml
1896 Text {
1897 color: "#00FF00"
1898 text: "green text"
1899 }
1900 \endqml
1901
1902 An example of steel blue text defined using an SVG color name:
1903 \qml
1904 Text {
1905 color: "steelblue"
1906 text: "blue text"
1907 }
1908 \endqml
1909*/
1910QColor QQuickText::color() const
1911{
1912 Q_D(const QQuickText);
1913 return QColor::fromRgba(d->color);
1914}
1915
1916void QQuickText::setColor(const QColor &color)
1917{
1918 Q_D(QQuickText);
1919 QRgb rgb = color.rgba();
1920 if (d->color == rgb)
1921 return;
1922
1923 d->color = rgb;
1924 if (isComponentComplete())
1925 d->scheduleUpdatePaintNode();
1926 emit colorChanged();
1927}
1928
1929/*!
1930 \qmlproperty color QtQuick::Text::linkColor
1931
1932 The color of links in the text.
1933
1934 This property works with the StyledText \l textFormat, but not with RichText.
1935 Link color in RichText can be specified by including CSS style tags in the
1936 text.
1937*/
1938
1939QColor QQuickText::linkColor() const
1940{
1941 Q_D(const QQuickText);
1942 return QColor::fromRgba(d->linkColor);
1943}
1944
1945void QQuickText::setLinkColor(const QColor &color)
1946{
1947 Q_D(QQuickText);
1948 QRgb rgb = color.rgba();
1949 if (d->linkColor == rgb)
1950 return;
1951
1952 d->linkColor = rgb;
1953 if (isComponentComplete())
1954 d->scheduleUpdatePaintNode();
1955 emit linkColorChanged();
1956}
1957
1958/*!
1959 \qmlproperty enumeration QtQuick::Text::style
1960
1961 Set an additional text style.
1962
1963 Supported text styles are:
1964
1965 \value Text.Normal - the default
1966 \value Text.Outline
1967 \value Text.Raised
1968 \value Text.Sunken
1969
1970 \qml
1971 Row {
1972 Text { font.pointSize: 24; text: "Normal" }
1973 Text { font.pointSize: 24; text: "Raised"; style: Text.Raised; styleColor: "#AAAAAA" }
1974 Text { font.pointSize: 24; text: "Outline";style: Text.Outline; styleColor: "red" }
1975 Text { font.pointSize: 24; text: "Sunken"; style: Text.Sunken; styleColor: "#AAAAAA" }
1976 }
1977 \endqml
1978
1979 \image declarative-textstyle.png {Four text styles: Normal, Raised,
1980 Outline with red border, and Sunken}
1981*/
1982QQuickText::TextStyle QQuickText::style() const
1983{
1984 Q_D(const QQuickText);
1985 return d->style;
1986}
1987
1988void QQuickText::setStyle(QQuickText::TextStyle style)
1989{
1990 Q_D(QQuickText);
1991 if (d->style == style)
1992 return;
1993
1994 d->style = style;
1995 if (isComponentComplete())
1996 d->scheduleUpdatePaintNode();
1997 emit styleChanged(d->style);
1998}
1999
2000/*!
2001 \qmlproperty color QtQuick::Text::styleColor
2002
2003 Defines the secondary color used by text styles.
2004
2005 \c styleColor is used as the outline color for outlined text, and as the
2006 shadow color for raised or sunken text. If no style has been set, it is not
2007 used at all.
2008
2009 \qml
2010 Text { font.pointSize: 18; text: "hello"; style: Text.Raised; styleColor: "gray" }
2011 \endqml
2012
2013 \sa style
2014 */
2015QColor QQuickText::styleColor() const
2016{
2017 Q_D(const QQuickText);
2018 return QColor::fromRgba(d->styleColor);
2019}
2020
2021void QQuickText::setStyleColor(const QColor &color)
2022{
2023 Q_D(QQuickText);
2024 QRgb rgb = color.rgba();
2025 if (d->styleColor == rgb)
2026 return;
2027
2028 d->styleColor = rgb;
2029 if (isComponentComplete())
2030 d->scheduleUpdatePaintNode();
2031 emit styleColorChanged();
2032}
2033
2034/*!
2035 \qmlproperty enumeration QtQuick::Text::horizontalAlignment
2036 \qmlproperty enumeration QtQuick::Text::verticalAlignment
2037 \qmlproperty enumeration QtQuick::Text::effectiveHorizontalAlignment
2038
2039 Sets the horizontal and vertical alignment of the text within the Text items
2040 width and height. By default, the text is vertically aligned to the top. Horizontal
2041 alignment follows the natural alignment of the text, for example text that is read
2042 from left to right will be aligned to the left.
2043
2044 The valid values for \c horizontalAlignment are \c Text.AlignLeft, \c Text.AlignRight, \c Text.AlignHCenter and
2045 \c Text.AlignJustify. The valid values for \c verticalAlignment are \c Text.AlignTop, \c Text.AlignBottom
2046 and \c Text.AlignVCenter.
2047
2048 Note that for a single line of text, the size of the text is the area of the text. In this common case,
2049 all alignments are equivalent. If you want the text to be, say, centered in its parent, then you will
2050 need to either modify the Item::anchors, or set horizontalAlignment to Text.AlignHCenter and bind the width to
2051 that of the parent.
2052
2053 When using the attached property LayoutMirroring::enabled to mirror application
2054 layouts, the horizontal alignment of text will also be mirrored. However, the property
2055 \c horizontalAlignment will remain unchanged. To query the effective horizontal alignment
2056 of Text, use the read-only property \c effectiveHorizontalAlignment.
2057*/
2058QQuickText::HAlignment QQuickText::hAlign() const
2059{
2060 Q_D(const QQuickText);
2061 return d->hAlign;
2062}
2063
2064void QQuickText::setHAlign(HAlignment align)
2065{
2066 Q_D(QQuickText);
2067 bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
2068 d->hAlignImplicit = false;
2069 if (d->setHAlign(align, forceAlign) && isComponentComplete())
2070 d->updateLayout();
2071}
2072
2073void QQuickText::resetHAlign()
2074{
2075 Q_D(QQuickText);
2076 d->hAlignImplicit = true;
2077 if (isComponentComplete() && d->determineHorizontalAlignment())
2078 d->updateLayout();
2079}
2080
2081QQuickText::HAlignment QQuickText::effectiveHAlign() const
2082{
2083 Q_D(const QQuickText);
2084 QQuickText::HAlignment effectiveAlignment = d->hAlign;
2085 if (!d->hAlignImplicit && d->effectiveLayoutMirror) {
2086 switch (d->hAlign) {
2087 case QQuickText::AlignLeft:
2088 effectiveAlignment = QQuickText::AlignRight;
2089 break;
2090 case QQuickText::AlignRight:
2091 effectiveAlignment = QQuickText::AlignLeft;
2092 break;
2093 default:
2094 break;
2095 }
2096 }
2097 return effectiveAlignment;
2098}
2099
2100bool QQuickTextPrivate::setHAlign(QQuickText::HAlignment alignment, bool forceAlign)
2101{
2102 Q_Q(QQuickText);
2103 if (hAlign != alignment || forceAlign) {
2104 QQuickText::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
2105 hAlign = alignment;
2106
2107 emit q->horizontalAlignmentChanged(hAlign);
2108 if (oldEffectiveHAlign != q->effectiveHAlign())
2109 emit q->effectiveHorizontalAlignmentChanged();
2110 return true;
2111 }
2112 return false;
2113}
2114
2115bool QQuickTextPrivate::determineHorizontalAlignment()
2116{
2117 if (hAlignImplicit) {
2118#if QT_CONFIG(im)
2119 bool alignToRight = text.isEmpty() ? QGuiApplication::inputMethod()->inputDirection() == Qt::RightToLeft : rightToLeftText;
2120#else
2121 bool alignToRight = rightToLeftText;
2122#endif
2123 return setHAlign(alignToRight ? QQuickText::AlignRight : QQuickText::AlignLeft);
2124 }
2125 return false;
2126}
2127
2128void QQuickTextPrivate::mirrorChange()
2129{
2130 Q_Q(QQuickText);
2131 if (q->isComponentComplete()) {
2132 if (!hAlignImplicit && (hAlign == QQuickText::AlignRight || hAlign == QQuickText::AlignLeft)) {
2133 updateLayout();
2134 emit q->effectiveHorizontalAlignmentChanged();
2135 }
2136 }
2137}
2138
2139QQuickText::VAlignment QQuickText::vAlign() const
2140{
2141 Q_D(const QQuickText);
2142 return d->vAlign;
2143}
2144
2145void QQuickText::setVAlign(VAlignment align)
2146{
2147 Q_D(QQuickText);
2148 if (d->vAlign == align)
2149 return;
2150
2151 d->vAlign = align;
2152
2153 if (isComponentComplete())
2154 d->updateLayout();
2155
2156 emit verticalAlignmentChanged(align);
2157}
2158
2159/*!
2160 \qmlproperty enumeration QtQuick::Text::wrapMode
2161
2162 Set this property to wrap the text to the Text item's width. The text will only
2163 wrap if an explicit width has been set. wrapMode can be one of:
2164
2165 \value Text.NoWrap
2166 (default) no wrapping will be performed. If the text contains
2167 insufficient newlines, then \l contentWidth will exceed a set width.
2168 \value Text.WordWrap
2169 wrapping is done on word boundaries only. If a word is too long,
2170 \l contentWidth will exceed a set width.
2171 \value Text.WrapAnywhere
2172 wrapping is done at any point on a line, even if it occurs in the middle of a word.
2173 \value Text.Wrap
2174 if possible, wrapping occurs at a word boundary; otherwise it will occur
2175 at the appropriate point on the line, even in the middle of a word.
2176*/
2177QQuickText::WrapMode QQuickText::wrapMode() const
2178{
2179 Q_D(const QQuickText);
2180 return d->wrapMode;
2181}
2182
2183void QQuickText::setWrapMode(WrapMode mode)
2184{
2185 Q_D(QQuickText);
2186 if (mode == d->wrapMode)
2187 return;
2188
2189 d->wrapMode = mode;
2190 d->updateLayout();
2191
2192 emit wrapModeChanged();
2193}
2194
2195/*!
2196 \qmlproperty int QtQuick::Text::lineCount
2197
2198 Returns the number of lines visible in the text item.
2199
2200 This property is not supported for rich text.
2201
2202 \sa maximumLineCount
2203*/
2204int QQuickText::lineCount() const
2205{
2206 Q_D(const QQuickText);
2207 return d->lineCount;
2208}
2209
2210/*!
2211 \qmlproperty bool QtQuick::Text::truncated
2212
2213 Returns true if the text has been truncated due to \l maximumLineCount
2214 or \l elide.
2215
2216 This property is not supported for rich text.
2217
2218 \sa maximumLineCount, elide
2219*/
2220bool QQuickText::truncated() const
2221{
2222 Q_D(const QQuickText);
2223 return d->truncated;
2224}
2225
2226/*!
2227 \qmlproperty int QtQuick::Text::maximumLineCount
2228
2229 Set this property to limit the number of lines that the text item will show.
2230 If elide is set to Text.ElideRight, the text will be elided appropriately.
2231 By default, this is the value of the largest possible integer.
2232
2233 This property is not supported for rich text.
2234
2235 \sa lineCount, elide
2236*/
2237int QQuickText::maximumLineCount() const
2238{
2239 Q_D(const QQuickText);
2240 return d->maximumLineCount();
2241}
2242
2243void QQuickText::setMaximumLineCount(int lines)
2244{
2245 Q_D(QQuickText);
2246
2247 d->maximumLineCountValid = lines==INT_MAX ? false : true;
2248 if (d->maximumLineCount() != lines) {
2249 d->extra.value().maximumLineCount = lines;
2250 d->implicitHeightValid = false;
2251 d->updateLayout();
2252 emit maximumLineCountChanged();
2253 }
2254}
2255
2256void QQuickText::resetMaximumLineCount()
2257{
2258 Q_D(QQuickText);
2259 setMaximumLineCount(INT_MAX);
2260 if (d->truncated != false) {
2261 d->truncated = false;
2262 emit truncatedChanged();
2263 }
2264}
2265
2266/*!
2267 \qmlproperty enumeration QtQuick::Text::textFormat
2268
2269 The way the \l text property should be displayed.
2270
2271 Supported text formats are:
2272
2273 \value Text.AutoText (default) detected via the Qt::mightBeRichText() heuristic
2274 \value Text.PlainText all styling tags are treated as plain text
2275 \value Text.StyledText optimized basic rich text as in HTML 3.2
2276 \value Text.RichText \l {Supported HTML Subset} {a subset of HTML 4}
2277 \value Text.MarkdownText \l {https://commonmark.org/help/}{CommonMark} plus the
2278 \l {https://guides.github.com/features/mastering-markdown/}{GitHub}
2279 extensions for tables and task lists (since 5.14)
2280
2281 If the text format is \c Text.AutoText, the Text item
2282 will automatically determine whether the text should be treated as
2283 styled text. This determination is made using Qt::mightBeRichText(),
2284 which can detect the presence of an HTML tag on the first line of text,
2285 but cannot distinguish Markdown from plain text.
2286
2287 \c Text.StyledText is an optimized format supporting some basic text
2288 styling markup, in the style of HTML 3.2:
2289
2290 \code
2291 <b></b> - bold
2292 <del></del> - strike out (removed content)
2293 <s></s> - strike out (no longer accurate or no longer relevant content)
2294 <strong></strong> - bold
2295 <i></i> - italic
2296 <br> - new line
2297 <p> - paragraph
2298 <u> - underlined text
2299 <font color="color_name" size="1-7"></font>
2300 <h1> to <h6> - headers
2301 <a href=""> - anchor
2302 <img src="" align="top,middle,bottom" width="" height=""> - inline images
2303 <ol type="">, <ul type=""> and <li> - ordered and unordered lists
2304 <pre></pre> - preformatted
2305 All entities
2306 \endcode
2307
2308 \c Text.StyledText parser is strict, requiring tags to be correctly nested.
2309
2310 \table
2311 \row
2312 \li
2313 \snippet qml/text/textFormats.qml 0
2314 \li \image declarative-textformat.png {Multiple text format display
2315 examples: AutoText, HTML, plain, and Markdown}
2316 \endtable
2317
2318 \c Text.RichText supports a larger subset of HTML 4, as described on the
2319 \l {Supported HTML Subset} page. You should prefer using \c Text.PlainText,
2320 \c Text.StyledText or \c Text.MarkdownText instead, as they offer better performance.
2321
2322 \note With \c Text.MarkdownText, and with the supported subset of HTML,
2323 some decorative elements are not rendered as they would be in a web browser:
2324 \list
2325 \li code blocks use the \l {QFontDatabase::FixedFont}{default monospace font} but without a surrounding highlight box
2326 \li block quotes are indented, but there is no vertical line alongside the quote
2327 \endlist
2328
2329 \warning When the text format is any other format than \c{Text.PlainText}, it will support
2330 rich text features such as changing colors, font styles and inline images. This includes
2331 loading images remotely over the network. Thus, when displaying user-controlled, untrusted
2332 content, the \l textFormat should either be explicitly set to \c Text.PlainText, or the contents
2333 should be stripped of unwanted tags.
2334*/
2335QQuickText::TextFormat QQuickText::textFormat() const
2336{
2337 Q_D(const QQuickText);
2338 return d->format.value_or(QQuickText::AutoText);
2339}
2340
2341void QQuickText::setTextFormat(TextFormat format)
2342{
2343 Q_D(QQuickText);
2344 if (d->format.has_value() && format == d->format)
2345 return;
2346
2347 const QQuickText::TextFormat oldFormat = textFormat();
2348 d->format = format;
2349
2350 const bool wasRich = d->hasRichTextFormat();
2351 d->decideEffectiveTextFormat(d->text);
2352 Q_ASSERT(d->effectiveTextFormat != AutoText);
2353
2354 if (isComponentComplete()) {
2355 if (!wasRich && d->hasRichTextFormat()) {
2356 d->updateDocumentText();
2357 } else {
2358 d->clearFormats();
2359 d->textHasChanged = true;
2360 }
2361 }
2362 d->updateLayout();
2363 setAcceptHoverEvents(d->effectiveTextFormat != PlainText);
2364 setAcceptedMouseButtons(d->effectiveTextFormat != PlainText ? Qt::LeftButton : Qt::NoButton);
2365
2366 // We may be changing the format from an implicit AutoText to an explicit one, which means
2367 // we have to check whether we actually changed something before emitting.
2368 if (oldFormat != format)
2369 emit textFormatChanged(format);
2370}
2371
2372/*!
2373 \qmlproperty enumeration QtQuick::Text::elide
2374
2375 Set this property to elide parts of the text fit to the Text item's width.
2376 The text will only elide if an explicit width has been set.
2377
2378 This property works with \c Text.PlainText and \c Text.StyledText formats,
2379 but cannot be used with \c Text.RichText or \c Text.MarkdownText formats.
2380
2381 Eliding can be:
2382
2383 \value Text.ElideNone - the default
2384 \value Text.ElideLeft
2385 \value Text.ElideMiddle
2386 \value Text.ElideRight
2387
2388 If this property is set to Text.ElideRight, it can be used with \l {wrapMode}{wrapped}
2389 text. The text will only elide if \c maximumLineCount, or \c height has been set.
2390 If both \c maximumLineCount and \c height are set, \c maximumLineCount will
2391 apply unless the lines do not fit in the height allowed.
2392
2393 If the text is a multi-length string, and the mode is not \c Text.ElideNone,
2394 the first string that fits will be used, otherwise the last will be elided.
2395
2396 Multi-length strings are ordered from longest to shortest, separated by the
2397 Unicode "String Terminator" character \c U009C (write this in QML with \c{"\u009C"} or \c{"\x9C"}).
2398*/
2399QQuickText::TextElideMode QQuickText::elideMode() const
2400{
2401 Q_D(const QQuickText);
2402 return d->elideMode;
2403}
2404
2405void QQuickText::setElideMode(QQuickText::TextElideMode mode)
2406{
2407 Q_D(QQuickText);
2408 if (mode == d->elideMode)
2409 return;
2410
2411 d->elideMode = mode;
2412 d->updateLayout();
2413
2414 emit elideModeChanged(mode);
2415}
2416
2417/*!
2418 \qmlproperty url QtQuick::Text::baseUrl
2419
2420 This property specifies a base URL that is used to resolve relative URLs
2421 within the text.
2422
2423 Urls are resolved to be within the same directory as the target of the base
2424 URL meaning any portion of the path after the last '/' will be ignored.
2425
2426 \table
2427 \header \li Base URL \li Relative URL \li Resolved URL
2428 \row \li http://qt-project.org/ \li images/logo.png \li http://qt-project.org/images/logo.png
2429 \row \li http://qt-project.org/index.html \li images/logo.png \li http://qt-project.org/images/logo.png
2430 \row \li http://qt-project.org/content \li images/logo.png \li http://qt-project.org/content/images/logo.png
2431 \row \li http://qt-project.org/content/ \li images/logo.png \li http://qt-project.org/content/images/logo.png
2432 \row \li http://qt-project.org/content/index.html \li images/logo.png \li http://qt-project.org/content/images/logo.png
2433 \row \li http://qt-project.org/content/index.html \li ../images/logo.png \li http://qt-project.org/images/logo.png
2434 \row \li http://qt-project.org/content/index.html \li /images/logo.png \li http://qt-project.org/images/logo.png
2435 \endtable
2436
2437 The default value is the url of the QML file instantiating the Text item.
2438*/
2439
2440QUrl QQuickText::baseUrl() const
2441{
2442 Q_D(const QQuickText);
2443 if (!d->extra.isAllocated() || d->extra->baseUrl.isEmpty()) {
2444 if (QQmlContext *context = qmlContext(this))
2445 return context->baseUrl();
2446 else
2447 return QUrl();
2448 } else {
2449 return d->extra->baseUrl;
2450 }
2451}
2452
2453void QQuickText::setBaseUrl(const QUrl &url)
2454{
2455 Q_D(QQuickText);
2456 if (baseUrl() != url) {
2457 d->extra.value().baseUrl = url;
2458
2459 if (d->hasRichTextFormat()) {
2460 d->ensureDoc();
2461 d->extra->doc->setBaseUrl(url);
2462 } else if (d->effectiveTextFormat == StyledText) {
2463 d->textHasChanged = true;
2464 if (d->extra.isAllocated()) {
2465 qDeleteAll(d->extra->imgTags);
2466 d->extra->imgTags.clear();
2467 }
2468 d->updateLayout();
2469 }
2470 emit baseUrlChanged();
2471 }
2472}
2473
2474void QQuickText::resetBaseUrl()
2475{
2476 if (QQmlContext *context = qmlContext(this))
2477 setBaseUrl(context->baseUrl());
2478 else
2479 setBaseUrl(QUrl());
2480}
2481
2482/*!
2483 Returns the extents of the text after layout.
2484 If the \l style() is not \c Text.Normal, a margin is added to ensure
2485 that the rendering effect will fit within this rectangle.
2486
2487 \sa contentWidth(), contentHeight(), clipRect()
2488*/
2489QRectF QQuickText::boundingRect() const
2490{
2491 Q_D(const QQuickText);
2492
2493 QRectF rect = d->layedOutTextRect;
2494 rect.moveLeft(QQuickTextUtil::alignedX(rect.width(), width(), effectiveHAlign()));
2495 rect.moveTop(QQuickTextUtil::alignedY(rect.height() + d->lineHeightOffset(), height(), d->vAlign));
2496
2497 if (d->style != Normal)
2498 rect.adjust(-1, 0, 1, 2);
2499 // Could include font max left/right bearings to either side of rectangle.
2500
2501 return rect;
2502}
2503
2504/*!
2505 Returns a rectangular area slightly larger than what is currently visible
2506 in \l viewportItem(); otherwise, the rectangle \c (0, 0, width, height).
2507 The text will be clipped to fit if \l clip is \c true.
2508
2509 \note If the \l style is not \c Text.Normal, the clip rectangle is adjusted
2510 to be slightly larger, to limit clipping of the outline effect at the edges.
2511 But it still looks better to set \l clip to \c false in that case.
2512
2513 \sa contentWidth(), contentHeight(), boundingRect()
2514*/
2515QRectF QQuickText::clipRect() const
2516{
2517 Q_D(const QQuickText);
2518
2519 QRectF rect = QQuickImplicitSizeItem::clipRect();
2520 if (d->style != Normal)
2521 rect.adjust(-1, 0, 1, 2);
2522 return rect;
2523}
2524
2525/*! \internal */
2526void QQuickText::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
2527{
2528 Q_D(QQuickText);
2529 if (d->text.isEmpty()) {
2530 QQuickItem::geometryChange(newGeometry, oldGeometry);
2531 return;
2532 }
2533
2534 bool widthChanged = newGeometry.width() != oldGeometry.width();
2535 bool heightChanged = newGeometry.height() != oldGeometry.height();
2536 bool wrapped = d->wrapMode != QQuickText::NoWrap;
2537 bool elide = d->elideMode != QQuickText::ElideNone;
2538 bool scaleFont = d->fontSizeMode() != QQuickText::FixedSize && (widthValid() || heightValid());
2539 bool verticalScale = (d->fontSizeMode() & QQuickText::VerticalFit) && heightValid();
2540
2541 bool widthMaximum = newGeometry.width() >= oldGeometry.width() && !d->widthExceeded;
2542 bool heightMaximum = newGeometry.height() >= oldGeometry.height() && !d->heightExceeded;
2543
2544 bool verticalPositionChanged = heightChanged && d->vAlign != AlignTop;
2545
2546 if ((!widthChanged && !heightChanged) || d->internalWidthUpdate)
2547 goto geomChangeDone;
2548
2549 if ((effectiveHAlign() != QQuickText::AlignLeft && widthChanged) || verticalPositionChanged) {
2550 // If the width has changed and we're not left aligned do an update so the text is
2551 // repositioned even if a full layout isn't required. And the same for vertical.
2552 d->scheduleUpdatePaintNode();
2553 }
2554
2555 if (!wrapped && !elide && !scaleFont && !verticalPositionChanged)
2556 goto geomChangeDone; // left aligned unwrapped text without eliding never needs relayout
2557
2558 if (elide // eliding and dimensions were and remain invalid;
2559 && ((widthValid() && oldGeometry.width() <= 0 && newGeometry.width() <= 0)
2560 || (heightValid() && oldGeometry.height() <= 0 && newGeometry.height() <= 0))) {
2561 goto geomChangeDone;
2562 }
2563
2564 if (widthMaximum && heightMaximum && !d->isLineLaidOutConnected() && !verticalPositionChanged && !elide) // Size is sufficient and growing.
2565 goto geomChangeDone;
2566
2567 if (!(widthChanged || widthMaximum) && !d->isLineLaidOutConnected()) { // only height has changed
2568 if (!verticalPositionChanged) {
2569 if (newGeometry.height() > oldGeometry.height()) {
2570 if (!d->heightExceeded && !qFuzzyIsNull(oldGeometry.height())) {
2571 // Height is adequate and growing, and it wasn't 0 previously.
2572 goto geomChangeDone;
2573 }
2574 if (d->lineCount == d->maximumLineCount()) // Reached maximum line and height is growing.
2575 goto geomChangeDone;
2576 } else if (newGeometry.height() < oldGeometry.height()) {
2577 if (d->lineCount < 2 && !verticalScale && newGeometry.height() > 0) // A single line won't be truncated until the text is 0 height.
2578 goto geomChangeDone;
2579
2580 if (!verticalScale // no scaling, no eliding, and either unwrapped, or no maximum line count.
2581 && d->elideMode != QQuickText::ElideRight
2582 && !(d->maximumLineCountValid && d->widthExceeded)) {
2583 goto geomChangeDone;
2584 }
2585 }
2586 }
2587 } else if (!heightChanged && widthMaximum && !elide) {
2588 if (oldGeometry.width() > 0) {
2589 // no change to height, width is adequate and wasn't 0 before
2590 // (old width could also be negative if it was 0 and the margins
2591 // were set)
2592 goto geomChangeDone;
2593 }
2594 }
2595
2596 if (d->updateOnComponentComplete || d->textHasChanged) {
2597 // We need to re-elide
2598 d->updateLayout();
2599 } else {
2600 // We just need to re-layout
2601 d->updateSize();
2602 }
2603
2604geomChangeDone:
2605 QQuickItem::geometryChange(newGeometry, oldGeometry);
2606}
2607
2608void QQuickText::triggerPreprocess()
2609{
2610 Q_D(QQuickText);
2611 if (d->updateType == QQuickTextPrivate::UpdateNone)
2612 d->updateType = QQuickTextPrivate::UpdatePreprocess;
2613 update();
2614}
2615
2616QSGNode *QQuickText::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
2617{
2618 Q_UNUSED(data);
2619 Q_D(QQuickText);
2620
2621 if (d->text.isEmpty()) {
2622 d->containsUnscalableGlyphs = false;
2623 delete oldNode;
2624 return nullptr;
2625 }
2626
2627 if (d->updateType != QQuickTextPrivate::UpdatePaintNode && oldNode != nullptr) {
2628 // Update done in preprocess() in the nodes
2629 d->updateType = QQuickTextPrivate::UpdateNone;
2630 return oldNode;
2631 }
2632
2633 d->updateType = QQuickTextPrivate::UpdateNone;
2634
2635 const qreal dy = QQuickTextUtil::alignedY(d->layedOutTextRect.height() + d->lineHeightOffset(), d->availableHeight(), d->vAlign) + topPadding();
2636
2637 QSGInternalTextNode *node = nullptr;
2638 if (!oldNode)
2639 node = d->sceneGraphContext()->createInternalTextNode(d->sceneGraphRenderContext());
2640 else
2641 node = static_cast<QSGInternalTextNode *>(oldNode);
2642
2643 node->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest);
2644
2645 node->setTextStyle(QSGTextNode::TextStyle(d->style));
2646 node->setRenderType(QSGTextNode::RenderType(d->renderType));
2647 node->setRenderTypeQuality(d->renderTypeQuality());
2648
2649 QSGInternalTextNode::RecycleBin recycleBin;
2650 node->recycle(&recycleBin);
2651 node->setMatrix(QMatrix4x4());
2652
2653 node->setColor(QColor::fromRgba(d->color));
2654 node->setStyleColor(QColor::fromRgba(d->styleColor));
2655 node->setLinkColor(QColor::fromRgba(d->linkColor));
2656
2657 node->setDevicePixelRatio(d->effectiveDevicePixelRatio());
2658
2659 if (d->hasRichTextFormat()) {
2660 node->setViewport(clipRect());
2661 const qreal dx = QQuickTextUtil::alignedX(d->layedOutTextRect.width(), d->availableWidth(), effectiveHAlign()) + leftPadding();
2662 d->ensureDoc();
2663 node->addTextDocument(QPointF(dx, dy), d->extra->doc, &recycleBin);
2664 } else if (d->layedOutTextRect.width() > 0) {
2665 if (flags().testFlag(ItemObservesViewport))
2666 node->setViewport(clipRect());
2667 else
2668 node->setViewport(QRectF{});
2669 const qreal dx = QQuickTextUtil::alignedX(d->lineWidth, d->availableWidth(), effectiveHAlign()) + leftPadding();
2670 int unelidedLineCount = d->lineCount;
2671 if (d->elideLayout)
2672 unelidedLineCount -= 1;
2673 if (unelidedLineCount > 0)
2674 node->addTextLayout(QPointF(dx, dy), &d->layout, &recycleBin, -1, -1,0, unelidedLineCount);
2675
2676 if (d->elideLayout)
2677 node->addTextLayout(QPointF(dx, dy), d->elideLayout.get(), &recycleBin);
2678
2679 if (d->extra.isAllocated()) {
2680 for (QQuickStyledTextImgTag *img : std::as_const(d->extra->visibleImgTags)) {
2681 if (img->pix && img->pix->isReady()) {
2682 node->addImage(QRectF(img->pos.x() + dx,
2683 img->pos.y() + dy,
2684 img->size.width(),
2685 img->size.height()),
2686 img->pix->image(),
2687 &recycleBin);
2688 }
2689 }
2690 }
2691 }
2692
2693 d->containsUnscalableGlyphs = node->containsUnscalableGlyphs();
2694
2695 // The font caches have now been initialized on the render thread, so they have to be
2696 // invalidated before we can use them from the main thread again.
2697 invalidateFontCaches();
2698
2699 node->discardUnusedNodes(&recycleBin);
2700
2701 return node;
2702}
2703
2704void QQuickText::updatePolish()
2705{
2706 Q_D(QQuickText);
2707 const bool clipNodeChanged =
2708 d->componentComplete && d->clipNode() && d->clipNode()->rect() != clipRect();
2709 if (clipNodeChanged)
2710 d->dirty(QQuickItemPrivate::Clip);
2711
2712 // If the fonts used for rendering are different from the ones used in the GUI thread,
2713 // it means we will get warnings and corrupted text. If this case is detected, we need
2714 // to update the text layout before creating the scenegraph nodes.
2715 if (!d->assignedFont.isEmpty() && QFontInfo(d->font).family() != d->assignedFont)
2716 d->polishSize = true;
2717
2718 if (d->polishSize) {
2719 d->updateSize();
2720 d->polishSize = false;
2721 }
2722
2723 if (!d->format && d->effectiveTextFormat == StyledText && !d->textFormatWarningDisplayed) {
2724 qCWarning(lcText)
2725 << "QQuickText: Rich text support has implicitly been enabled on a component with "
2726 "the default text format of AutoText. Unexpected rich text support may have "
2727 "security implications. Therefore, the default text format will change to PlainText "
2728 "in a future version of Qt. Please explicitly choose the appropriate text format in "
2729 "your components to avoid errors in a future upgrade. Affected component:" << this;
2730 d->textFormatWarningDisplayed = true;
2731 }
2732
2733 invalidateFontCaches();
2734}
2735
2736/*!
2737 \qmlproperty real QtQuick::Text::contentWidth
2738
2739 Returns the width of the text, including width past the width
2740 that is covered due to insufficient wrapping if WrapMode is set.
2741*/
2742qreal QQuickText::contentWidth() const
2743{
2744 Q_D(const QQuickText);
2745 return d->layedOutTextRect.width();
2746}
2747
2748/*!
2749 \qmlproperty real QtQuick::Text::contentHeight
2750
2751 Returns the height of the text, including height past the height
2752 that is covered due to there being more text than fits in the set height.
2753*/
2754qreal QQuickText::contentHeight() const
2755{
2756 Q_D(const QQuickText);
2757 return d->layedOutTextRect.height() + qMax(d->lineHeightOffset(), 0);
2758}
2759
2760/*!
2761 \qmlproperty real QtQuick::Text::lineHeight
2762
2763 Sets the line height for the text.
2764 The value can be in pixels or a multiplier depending on lineHeightMode.
2765
2766 The default value is a multiplier of 1.0.
2767 The line height must be a positive value.
2768*/
2769qreal QQuickText::lineHeight() const
2770{
2771 Q_D(const QQuickText);
2772 return d->lineHeight();
2773}
2774
2775void QQuickText::setLineHeight(qreal lineHeight)
2776{
2777 Q_D(QQuickText);
2778
2779 if ((d->lineHeight() == lineHeight) || (lineHeight < 0.0))
2780 return;
2781
2782 d->extra.value().lineHeightValid = true;
2783 d->extra.value().lineHeight = lineHeight;
2784 d->implicitHeightValid = false;
2785 d->updateLayout();
2786 emit lineHeightChanged(lineHeight);
2787}
2788
2789/*!
2790 \qmlproperty enumeration QtQuick::Text::lineHeightMode
2791
2792 This property determines how the line height is specified.
2793 The possible values are:
2794
2795 \value Text.ProportionalHeight (default) sets the spacing proportional to the line
2796 (as a multiplier). For example, set to 2 for double spacing.
2797 \value Text.FixedHeight sets the line height to a fixed line height (in pixels).
2798*/
2799QQuickText::LineHeightMode QQuickText::lineHeightMode() const
2800{
2801 Q_D(const QQuickText);
2802 return d->lineHeightMode();
2803}
2804
2805void QQuickText::setLineHeightMode(LineHeightMode mode)
2806{
2807 Q_D(QQuickText);
2808 if (mode == d->lineHeightMode())
2809 return;
2810
2811 d->implicitHeightValid = false;
2812 d->extra.value().lineHeightValid = true;
2813 d->extra.value().lineHeightMode = mode;
2814 d->updateLayout();
2815
2816 emit lineHeightModeChanged(mode);
2817}
2818
2819/*!
2820 \qmlproperty enumeration QtQuick::Text::fontSizeMode
2821
2822 This property specifies how the font size of the displayed text is determined.
2823 The possible values are:
2824
2825 \value Text.FixedSize
2826 (default) The size specified by \l font.pixelSize or \l font.pointSize is used.
2827 \value Text.HorizontalFit
2828 The largest size up to the size specified that fits within the width of the item
2829 without wrapping is used.
2830 \value Text.VerticalFit
2831 The largest size up to the size specified that fits the height of the item is used.
2832 \value Text.Fit
2833 The largest size up to the size specified that fits within the width and height
2834 of the item is used.
2835
2836 The font size of fitted text has a minimum bound specified by the
2837 minimumPointSize or minimumPixelSize property and maximum bound specified
2838 by either the \l font.pointSize or \l font.pixelSize properties.
2839
2840 \qml
2841 Text { text: "Hello"; fontSizeMode: Text.Fit; minimumPixelSize: 10; font.pixelSize: 72 }
2842 \endqml
2843
2844 If the text does not fit within the item bounds with the minimum font size
2845 the text will be elided as per the \l elide property.
2846
2847 If the \l textFormat property is set to \c Text.RichText, this will have no effect at all as the
2848 property will be ignored completely. If \l textFormat is set to \c Text.StyledText, then the
2849 property will be respected provided there is no font size tags inside the text. If there are
2850 font size tags, the property will still respect those. This can cause it to not fully comply with
2851 the fontSizeMode setting.
2852*/
2853
2854QQuickText::FontSizeMode QQuickText::fontSizeMode() const
2855{
2856 Q_D(const QQuickText);
2857 return d->fontSizeMode();
2858}
2859
2860void QQuickText::setFontSizeMode(FontSizeMode mode)
2861{
2862 Q_D(QQuickText);
2863 if (d->fontSizeMode() == mode)
2864 return;
2865
2866 d->polishSize = true;
2867 polish();
2868
2869 d->extra.value().fontSizeMode = mode;
2870 emit fontSizeModeChanged();
2871}
2872
2873/*!
2874 \qmlproperty int QtQuick::Text::minimumPixelSize
2875
2876 This property specifies the minimum font pixel size of text scaled by the
2877 fontSizeMode property.
2878
2879 If the fontSizeMode is Text.FixedSize or the \l font.pixelSize is -1 this
2880 property is ignored.
2881*/
2882
2883int QQuickText::minimumPixelSize() const
2884{
2885 Q_D(const QQuickText);
2886 return d->minimumPixelSize();
2887}
2888
2889void QQuickText::setMinimumPixelSize(int size)
2890{
2891 Q_D(QQuickText);
2892 if (d->minimumPixelSize() == size)
2893 return;
2894
2895 if (d->fontSizeMode() != FixedSize && (widthValid() || heightValid())) {
2896 d->polishSize = true;
2897 polish();
2898 }
2899 d->extra.value().minimumPixelSize = size;
2900 emit minimumPixelSizeChanged();
2901}
2902
2903/*!
2904 \qmlproperty int QtQuick::Text::minimumPointSize
2905
2906 This property specifies the minimum font point \l size of text scaled by
2907 the fontSizeMode property.
2908
2909 If the fontSizeMode is Text.FixedSize or the \l font.pointSize is -1 this
2910 property is ignored.
2911*/
2912
2913int QQuickText::minimumPointSize() const
2914{
2915 Q_D(const QQuickText);
2916 return d->minimumPointSize();
2917}
2918
2919void QQuickText::setMinimumPointSize(int size)
2920{
2921 Q_D(QQuickText);
2922 if (d->minimumPointSize() == size)
2923 return;
2924
2925 if (d->fontSizeMode() != FixedSize && (widthValid() || heightValid())) {
2926 d->polishSize = true;
2927 polish();
2928 }
2929 d->extra.value().minimumPointSize = size;
2930 emit minimumPointSizeChanged();
2931}
2932
2933/*!
2934 Returns the number of resources (images) that are being loaded asynchronously.
2935*/
2936int QQuickText::resourcesLoading() const
2937{
2938 Q_D(const QQuickText);
2939 if (d->hasRichTextFormat() && d->extra.isAllocated())
2940 return d->extra->pixmapsInProgress.size();
2941 return 0;
2942}
2943
2944/*! \internal */
2945void QQuickText::componentComplete()
2946{
2947 Q_D(QQuickText);
2948 if (d->updateOnComponentComplete) {
2949 if (d->hasRichTextFormat())
2950 d->updateDocumentText();
2951 }
2952 QQuickItem::componentComplete();
2953 if (d->updateOnComponentComplete)
2954 d->updateLayout();
2955}
2956
2957QString QQuickTextPrivate::anchorAt(const QTextLayout *layout, const QPointF &mousePos)
2958{
2959 for (int i = 0; i < layout->lineCount(); ++i) {
2960 QTextLine line = layout->lineAt(i);
2961 if (line.naturalTextRect().contains(mousePos)) {
2962 int charPos = line.xToCursor(mousePos.x(), QTextLine::CursorOnCharacter);
2963 const auto formats = layout->formats();
2964 for (const QTextLayout::FormatRange &formatRange : formats) {
2965 if (formatRange.format.isAnchor()
2966 && charPos >= formatRange.start
2967 && charPos < formatRange.start + formatRange.length) {
2968 return formatRange.format.anchorHref();
2969 }
2970 }
2971 break;
2972 }
2973 }
2974 return QString();
2975}
2976
2977QString QQuickTextPrivate::anchorAt(const QPointF &mousePos) const
2978{
2979 Q_Q(const QQuickText);
2980 QPointF translatedMousePos = mousePos;
2981 translatedMousePos.rx() -= q->leftPadding();
2982 translatedMousePos.ry() -= q->topPadding() + QQuickTextUtil::alignedY(layedOutTextRect.height() + lineHeightOffset(), availableHeight(), vAlign);
2983 if (effectiveTextFormat == QQuickText::StyledText) {
2984 translatedMousePos.rx() -= QQuickTextUtil::alignedX(lineWidth, availableWidth(), q->effectiveHAlign());
2985 QString link = anchorAt(&layout, translatedMousePos);
2986 if (link.isEmpty() && elideLayout)
2987 link = anchorAt(elideLayout.get(), translatedMousePos);
2988 return link;
2989 } else if (hasRichTextFormat() && extra.isAllocated() && extra->doc) {
2990 translatedMousePos.rx() -= QQuickTextUtil::alignedX(layedOutTextRect.width(), availableWidth(), q->effectiveHAlign());
2991 return extra->doc->documentLayout()->anchorAt(translatedMousePos);
2992 }
2993 return QString();
2994}
2995
2996QString QQuickTextPrivate::toolTipAt(const QTextLayout *layout, const QPointF &mousePos)
2997{
2998 for (int i = 0; i < layout->lineCount(); ++i) {
2999 const QTextLine line = layout->lineAt(i);
3000 if (line.naturalTextRect().contains(mousePos)) {
3001 const int charPos = line.xToCursor(mousePos.x(), QTextLine::CursorOnCharacter);
3002 const auto formats = layout->formats();
3003 for (const QTextLayout::FormatRange &formatRange : formats) {
3004 if (!formatRange.format.toolTip().isEmpty()
3005 && charPos >= formatRange.start
3006 && charPos < formatRange.start + formatRange.length) {
3007 return formatRange.format.toolTip();
3008 }
3009 }
3010 break;
3011 }
3012 }
3013 return QString();
3014}
3015
3016QString QQuickTextPrivate::toolTipAt(const QPointF &mousePos) const
3017{
3018 Q_Q(const QQuickText);
3019 QPointF translatedMousePos = mousePos;
3020 translatedMousePos.rx() -= q->leftPadding();
3021 translatedMousePos.ry() -= q->topPadding() +
3022 QQuickTextUtil::alignedY(layedOutTextRect.height() + lineHeightOffset(),
3023 availableHeight(), vAlign);
3024 if (effectiveTextFormat == QQuickText::StyledText) {
3025 translatedMousePos.rx() -=
3026 QQuickTextUtil::alignedX(lineWidth, availableWidth(), q->effectiveHAlign());
3027 QString toolTip = toolTipAt(&layout, translatedMousePos);
3028 if (toolTip.isEmpty() && elideLayout)
3029 toolTip = toolTipAt(elideLayout.get(), translatedMousePos);
3030 return toolTip;
3031 } else if (hasRichTextFormat() && extra.isAllocated() && extra->doc) {
3032 translatedMousePos.rx() -=
3033 QQuickTextUtil::alignedX(layedOutTextRect.width(), availableWidth(), q->effectiveHAlign());
3034 const QTextFormat fmt = extra->doc->documentLayout()->formatAt(translatedMousePos);
3035 return fmt.toCharFormat().toolTip();
3036 }
3037 return QString();
3038}
3039
3040bool QQuickTextPrivate::isLinkActivatedConnected()
3041{
3042 Q_Q(QQuickText);
3043 IS_SIGNAL_CONNECTED(q, QQuickText, linkActivated, (const QString &));
3044}
3045
3046/*! \internal */
3047void QQuickText::mousePressEvent(QMouseEvent *event)
3048{
3049 Q_D(QQuickText);
3050
3051 QString link;
3052 if (d->isLinkActivatedConnected())
3053 link = d->anchorAt(event->position());
3054
3055 if (link.isEmpty()) {
3056 event->setAccepted(false);
3057 } else {
3058 d->extra.value().activeLink = link;
3059 }
3060
3061 // ### may malfunction if two of the same links are clicked & dragged onto each other)
3062
3063 if (!event->isAccepted())
3064 QQuickItem::mousePressEvent(event);
3065}
3066
3067
3068/*! \internal */
3069void QQuickText::mouseReleaseEvent(QMouseEvent *event)
3070{
3071 Q_D(QQuickText);
3072
3073 // ### confirm the link, and send a signal out
3074
3075 QString link;
3076 if (d->isLinkActivatedConnected())
3077 link = d->anchorAt(event->position());
3078
3079 if (!link.isEmpty() && d->extra.isAllocated() && d->extra->activeLink == link)
3080 emit linkActivated(d->extra->activeLink);
3081 else
3082 event->setAccepted(false);
3083
3084 if (!event->isAccepted())
3085 QQuickItem::mouseReleaseEvent(event);
3086}
3087
3088bool QQuickTextPrivate::isLinkHoveredConnected()
3089{
3090 Q_Q(QQuickText);
3091 IS_SIGNAL_CONNECTED(q, QQuickText, linkHovered, (const QString &));
3092}
3093
3094bool QQuickTextPrivate::isHoveredToolTipChangedConnected()
3095{
3096 Q_Q(QQuickText);
3097 IS_SIGNAL_CONNECTED(q, QQuickText, hoveredToolTipChanged, ());
3098}
3099
3100static void getLinks_helper(const QTextLayout *layout, QList<QQuickTextPrivate::LinkDesc> *links)
3101{
3102 const auto formats = layout->formats();
3103 for (const QTextLayout::FormatRange &formatRange : formats) {
3104 if (formatRange.format.isAnchor()) {
3105 const int start = formatRange.start;
3106 const int len = formatRange.length;
3107 QTextLine line = layout->lineForTextPosition(start);
3108 QRectF r;
3109 r.setTop(line.y());
3110 r.setLeft(line.cursorToX(start, QTextLine::Leading));
3111 r.setHeight(line.height());
3112 r.setRight(line.cursorToX(start + len, QTextLine::Trailing));
3113 // ### anchorNames() is empty?! Not sure why this doesn't work
3114 // QString anchorName = formatRange.format.anchorNames().value(0); //### pick the first?
3115 // Therefore, we resort to QString::mid()
3116 QString anchorName = layout->text().mid(start, len);
3117 const QString anchorHref = formatRange.format.anchorHref();
3118 if (anchorName.isEmpty())
3119 anchorName = anchorHref;
3120 links->append( { anchorName, anchorHref, start, start + len, r.toRect()} );
3121 }
3122 }
3123}
3124
3125QList<QQuickTextPrivate::LinkDesc> QQuickTextPrivate::getLinks() const
3126{
3127 QList<QQuickTextPrivate::LinkDesc> links;
3128 getLinks_helper(&layout, &links);
3129 return links;
3130}
3131
3132
3133/*!
3134 \qmlsignal QtQuick::Text::linkHovered(string link)
3135 \since 5.2
3136
3137 This signal is emitted when the user hovers a link embedded in the
3138 text. The link must be in rich text or HTML format and the \a link
3139 string provides access to the particular link.
3140
3141 \sa hoveredLink, linkAt()
3142*/
3143
3144/*!
3145 \qmlproperty string QtQuick::Text::hoveredLink
3146 \since 5.2
3147
3148 This property contains the link string when the user hovers a link
3149 embedded in the text. The link must be in rich text or HTML format
3150 and the \a hoveredLink string provides access to the particular link.
3151
3152 \sa linkHovered, linkAt()
3153*/
3154
3155QString QQuickText::hoveredLink() const
3156{
3157 Q_D(const QQuickText);
3158 if (const_cast<QQuickTextPrivate *>(d)->isLinkHoveredConnected()) {
3159 if (d->extra.isAllocated())
3160 return d->extra->hoveredLink;
3161 } else {
3162#if QT_CONFIG(cursor)
3163 if (QQuickWindow *wnd = window()) {
3164 QPointF pos = QCursor::pos(wnd->screen()) - wnd->position() - mapToScene(QPointF(0, 0));
3165 return d->anchorAt(pos);
3166 }
3167#endif // cursor
3168 }
3169 return QString();
3170}
3171
3172/*!
3173 \qmlproperty string QtQuick::Text::hoveredToolTip
3174 \since 6.13
3175
3176 This property contains the tool tip string of the text fragment that the
3177 user is hovering, if any; otherwise it is empty. It changes as the mouse
3178 moves between fragments, and becomes empty when the mouse leaves text that
3179 carries a tool tip, or leaves the item. The tool tip must be provided by
3180 rich text or HTML, or by adding character formats to a \l QTextDocument
3181 programmatically.
3182
3183 A typical use is to drive a \l ToolTip:
3184 \snippet qml/text/hoveredToolTip.qml text
3185
3186 \sa hoveredLink
3187*/
3188
3189QString QQuickText::hoveredToolTip() const
3190{
3191 Q_D(const QQuickText);
3192 if (const_cast<QQuickTextPrivate *>(d)->isHoveredToolTipChangedConnected()) {
3193 if (d->extra.isAllocated())
3194 return d->extra->hoveredToolTip;
3195 } else {
3196#if QT_CONFIG(cursor)
3197 if (QQuickWindow *wnd = window()) {
3198 const QPointF pos = QCursor::pos(wnd->screen()) - wnd->position() - mapToScene(QPointF(0, 0));
3199 return d->toolTipAt(pos);
3200 }
3201#endif // cursor
3202 }
3203 return QString();
3204}
3205
3206void QQuickTextPrivate::processHoverEvent(QHoverEvent *event)
3207{
3208 Q_Q(QQuickText);
3209 qCDebug(lcHoverTrace) << q;
3210 QString link;
3211 if (isLinkHoveredConnected()) {
3212 if (event->type() != QEvent::HoverLeave)
3213 link = anchorAt(event->position());
3214
3215 if ((!extra.isAllocated() && !link.isEmpty()) || (extra.isAllocated() && extra->hoveredLink != link)) {
3216 extra.value().hoveredLink = link;
3217 emit q->linkHovered(extra->hoveredLink);
3218 }
3219 }
3220
3221 if (isHoveredToolTipChangedConnected()) {
3222 QString toolTip;
3223 if (event->type() != QEvent::HoverLeave)
3224 toolTip = toolTipAt(event->position());
3225
3226 if ( (!extra.isAllocated() && !toolTip.isEmpty())
3227 || (extra.isAllocated() && extra->hoveredToolTip != toolTip) ) {
3228 extra.value().hoveredToolTip = toolTip;
3229 emit q->hoveredToolTipChanged();
3230 qCDebug(lcHoverTrace) << q << event->type() << event->position() << "hoveredToolTip" << toolTip;
3231 }
3232 }
3233 event->ignore();
3234}
3235
3236void QQuickText::hoverEnterEvent(QHoverEvent *event)
3237{
3238 Q_D(QQuickText);
3239 d->processHoverEvent(event);
3240}
3241
3242void QQuickText::hoverMoveEvent(QHoverEvent *event)
3243{
3244 Q_D(QQuickText);
3245 d->processHoverEvent(event);
3246}
3247
3248void QQuickText::hoverLeaveEvent(QHoverEvent *event)
3249{
3250 Q_D(QQuickText);
3251 d->processHoverEvent(event);
3252}
3253
3254void QQuickText::invalidate()
3255{
3256 Q_D(QQuickText);
3257 d->textHasChanged = true;
3258 QMetaObject::invokeMethod(this,[&]{q_updateLayout();});
3259}
3260
3261bool QQuickTextPrivate::transformChanged(QQuickItem *transformedItem)
3262{
3263 // If there's a lot of text, we may need QQuickText::updatePaintNode() to call
3264 // QSGInternalTextNode::addTextLayout() again to populate a different range of lines
3265 if (flags & QQuickItem::ItemObservesViewport)
3266 scheduleUpdatePaintNode();
3267 return QQuickImplicitSizeItemPrivate::transformChanged(transformedItem);
3268}
3269
3270/*!
3271 \qmlproperty int QtQuick::Text::renderTypeQuality
3272 \since 6.0
3273
3274 Override the default rendering type quality for this component. This is a low-level
3275 customization which can be ignored in most cases. It currently only has an effect
3276 when \l renderType is \c Text.QtRendering.
3277
3278 The rasterization algorithm used by Text.QtRendering may give artifacts at
3279 large text sizes, such as sharp corners looking rounder than they should. If
3280 this is an issue for specific text items, increase the \c renderTypeQuality to
3281 improve rendering quality, at the expense of memory consumption.
3282
3283 The \c renderTypeQuality may be any integer over 0, or one of the following
3284 predefined values
3285
3286 \value Text.DefaultRenderTypeQuality -1 (default)
3287 \value Text.LowRenderTypeQuality 26
3288 \value Text.NormalRenderTypeQuality 52
3289 \value Text.HighRenderTypeQuality 104
3290 \value Text.VeryHighRenderTypeQuality 208
3291*/
3292int QQuickText::renderTypeQuality() const
3293{
3294 Q_D(const QQuickText);
3295 return d->renderTypeQuality();
3296}
3297
3298void QQuickText::setRenderTypeQuality(int renderTypeQuality)
3299{
3300 Q_D(QQuickText);
3301 if (renderTypeQuality == d->renderTypeQuality())
3302 return;
3303 d->extra.value().renderTypeQuality = renderTypeQuality;
3304
3305 if (isComponentComplete())
3306 d->scheduleUpdatePaintNode();
3307
3308 emit renderTypeQualityChanged();
3309}
3310
3311/*!
3312 \qmlproperty enumeration QtQuick::Text::renderType
3313
3314 Override the default rendering type for this component.
3315
3316 Supported render types are:
3317
3318 \value Text.QtRendering Text is rendered using a scalable distance field for each glyph.
3319 \value Text.NativeRendering Text is rendered using a platform-specific technique.
3320 \value Text.CurveRendering Text is rendered using a curve rasterizer running directly on the
3321 graphics hardware. (Introduced in Qt 6.7.0.)
3322
3323 Select \c Text.NativeRendering if you prefer text to look native on the target platform and do
3324 not require advanced features such as transformation of the text. Using such features in
3325 combination with the NativeRendering render type will lend poor and sometimes pixelated
3326 results.
3327
3328 Both \c Text.QtRendering and \c Text.CurveRendering are hardware-accelerated techniques.
3329 \c QtRendering is the faster of the two, but uses more memory and will exhibit rendering
3330 artifacts at large sizes. \c CurveRendering should be considered as an alternative in cases
3331 where \c QtRendering does not give good visual results or where reducing graphics memory
3332 consumption is a priority.
3333
3334 The default rendering type is determined by \l QQuickWindow::textRenderType().
3335*/
3336QQuickText::RenderType QQuickText::renderType() const
3337{
3338 Q_D(const QQuickText);
3339 return d->renderType;
3340}
3341
3342void QQuickText::setRenderType(QQuickText::RenderType renderType)
3343{
3344 Q_D(QQuickText);
3345 if (d->renderType == renderType)
3346 return;
3347
3348 d->renderType = renderType;
3349 emit renderTypeChanged();
3350
3351 if (isComponentComplete())
3352 d->updateLayout();
3353}
3354
3355#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
3356#if QT_DEPRECATED_SINCE(5, 15)
3357/*!
3358 \qmlmethod void QtQuick::Text::doLayout()
3359 \deprecated
3360
3361 Use \l forceLayout() instead.
3362*/
3363void QQuickText::doLayout()
3364{
3365 forceLayout();
3366}
3367
3368#endif
3369#endif
3370/*!
3371 \qmlmethod void QtQuick::Text::forceLayout()
3372 \since 5.9
3373
3374 Triggers a re-layout of the displayed text.
3375*/
3376void QQuickText::forceLayout()
3377{
3378 Q_D(QQuickText);
3379 d->updateSize();
3380}
3381
3382/*!
3383 \qmlmethod string QtQuick::Text::linkAt(real x, real y)
3384 \since 5.3
3385
3386 Returns the link string at point \a x, \a y in content coordinates,
3387 or an empty string if no link exists at that point.
3388
3389 \sa hoveredLink
3390*/
3391QString QQuickText::linkAt(qreal x, qreal y) const
3392{
3393 Q_D(const QQuickText);
3394 return d->anchorAt(QPointF(x, y));
3395}
3396
3397/*!
3398 * \internal
3399 *
3400 * Invalidates font caches owned by the text objects owned by the element
3401 * to work around the fact that text objects cannot be used from multiple threads.
3402 */
3403void QQuickText::invalidateFontCaches()
3404{
3405 Q_D(QQuickText);
3406
3407 if (d->hasRichTextFormat() && d->extra.isAllocated() && d->extra->doc != nullptr) {
3408 QTextBlock block;
3409 for (block = d->extra->doc->firstBlock(); block.isValid(); block = block.next()) {
3410 if (block.layout() != nullptr && block.layout()->engine() != nullptr)
3411 block.layout()->engine()->resetFontEngineCache();
3412 }
3413 } else {
3414 if (d->layout.engine() != nullptr)
3415 d->layout.engine()->resetFontEngineCache();
3416 }
3417}
3418
3419/*!
3420 \since 5.6
3421 \qmlproperty real QtQuick::Text::padding
3422 \qmlproperty real QtQuick::Text::topPadding
3423 \qmlproperty real QtQuick::Text::leftPadding
3424 \qmlproperty real QtQuick::Text::bottomPadding
3425 \qmlproperty real QtQuick::Text::rightPadding
3426
3427 These properties hold the padding around the content. This space is reserved
3428 in addition to the contentWidth and contentHeight.
3429*/
3430qreal QQuickText::padding() const
3431{
3432 Q_D(const QQuickText);
3433 return d->padding();
3434}
3435
3436void QQuickText::setPadding(qreal padding)
3437{
3438 Q_D(QQuickText);
3439 if (qFuzzyCompare(d->padding(), padding))
3440 return;
3441
3442 d->extra.value().padding = padding;
3443 d->updateSize();
3444 emit paddingChanged();
3445 if (!d->extra.isAllocated() || !d->extra->explicitTopPadding)
3446 emit topPaddingChanged();
3447 if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding)
3448 emit leftPaddingChanged();
3449 if (!d->extra.isAllocated() || !d->extra->explicitRightPadding)
3450 emit rightPaddingChanged();
3451 if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding)
3452 emit bottomPaddingChanged();
3453}
3454
3455void QQuickText::resetPadding()
3456{
3457 setPadding(0);
3458}
3459
3460qreal QQuickText::topPadding() const
3461{
3462 Q_D(const QQuickText);
3463 if (d->extra.isAllocated() && d->extra->explicitTopPadding)
3464 return d->extra->topPadding;
3465 return d->padding();
3466}
3467
3468void QQuickText::setTopPadding(qreal padding)
3469{
3470 Q_D(QQuickText);
3471 d->setTopPadding(padding);
3472}
3473
3474void QQuickText::resetTopPadding()
3475{
3476 Q_D(QQuickText);
3477 d->setTopPadding(0, true);
3478}
3479
3480qreal QQuickText::leftPadding() const
3481{
3482 Q_D(const QQuickText);
3483 if (d->extra.isAllocated() && d->extra->explicitLeftPadding)
3484 return d->extra->leftPadding;
3485 return d->padding();
3486}
3487
3488void QQuickText::setLeftPadding(qreal padding)
3489{
3490 Q_D(QQuickText);
3491 d->setLeftPadding(padding);
3492}
3493
3494void QQuickText::resetLeftPadding()
3495{
3496 Q_D(QQuickText);
3497 d->setLeftPadding(0, true);
3498}
3499
3500qreal QQuickText::rightPadding() const
3501{
3502 Q_D(const QQuickText);
3503 if (d->extra.isAllocated() && d->extra->explicitRightPadding)
3504 return d->extra->rightPadding;
3505 return d->padding();
3506}
3507
3508void QQuickText::setRightPadding(qreal padding)
3509{
3510 Q_D(QQuickText);
3511 d->setRightPadding(padding);
3512}
3513
3514void QQuickText::resetRightPadding()
3515{
3516 Q_D(QQuickText);
3517 d->setRightPadding(0, true);
3518}
3519
3520qreal QQuickText::bottomPadding() const
3521{
3522 Q_D(const QQuickText);
3523 if (d->extra.isAllocated() && d->extra->explicitBottomPadding)
3524 return d->extra->bottomPadding;
3525 return d->padding();
3526}
3527
3528void QQuickText::setBottomPadding(qreal padding)
3529{
3530 Q_D(QQuickText);
3531 d->setBottomPadding(padding);
3532}
3533
3534void QQuickText::resetBottomPadding()
3535{
3536 Q_D(QQuickText);
3537 d->setBottomPadding(0, true);
3538}
3539
3540/*!
3541 \qmlproperty string QtQuick::Text::fontInfo.family
3542 \since 5.9
3543
3544 The family name of the font that has been resolved for the current font
3545 and fontSizeMode.
3546*/
3547
3548/*!
3549 \qmlproperty string QtQuick::Text::fontInfo.styleName
3550 \since 5.9
3551
3552 The style name of the font info that has been resolved for the current font
3553 and fontSizeMode.
3554*/
3555
3556/*!
3557 \qmlproperty bool QtQuick::Text::fontInfo.bold
3558 \since 5.9
3559
3560 The bold state of the font info that has been resolved for the current font
3561 and fontSizeMode. This is true if the weight of the resolved font is bold or higher.
3562*/
3563
3564/*!
3565 \qmlproperty int QtQuick::Text::fontInfo.weight
3566 \since 5.9
3567
3568 The weight of the font info that has been resolved for the current font
3569 and fontSizeMode.
3570*/
3571
3572/*!
3573 \qmlproperty bool QtQuick::Text::fontInfo.italic
3574 \since 5.9
3575
3576 The italic state of the font info that has been resolved for the current font
3577 and fontSizeMode.
3578*/
3579
3580/*!
3581 \qmlproperty real QtQuick::Text::fontInfo.pointSize
3582 \since 5.9
3583
3584 The pointSize of the font info that has been resolved for the current font
3585 and fontSizeMode.
3586*/
3587
3588/*!
3589 \qmlproperty int QtQuick::Text::fontInfo.pixelSize
3590 \since 5.9
3591
3592 The pixel size of the font info that has been resolved for the current font
3593 and fontSizeMode.
3594*/
3595QJSValue QQuickText::fontInfo() const
3596{
3597 Q_D(const QQuickText);
3598
3599 QJSEngine *engine = qjsEngine(this);
3600 if (!engine) {
3601 qmlWarning(this) << "fontInfo: item has no JS engine";
3602 return QJSValue();
3603 }
3604
3605 QJSValue value = engine->newObject();
3606 value.setProperty(QStringLiteral("family"), d->fontInfo.family());
3607 value.setProperty(QStringLiteral("styleName"), d->fontInfo.styleName());
3608 value.setProperty(QStringLiteral("bold"), d->fontInfo.bold());
3609 value.setProperty(QStringLiteral("weight"), d->fontInfo.weight());
3610 value.setProperty(QStringLiteral("italic"), d->fontInfo.italic());
3611 value.setProperty(QStringLiteral("pointSize"), d->fontInfo.pointSizeF());
3612 value.setProperty(QStringLiteral("pixelSize"), d->fontInfo.pixelSize());
3613 return value;
3614}
3615
3616/*!
3617 \qmlproperty size QtQuick::Text::advance
3618 \since 5.10
3619
3620 The distance, in pixels, from the baseline origin of the first
3621 character of the text item, to the baseline origin of the first
3622 character in a text item occurring directly after this one
3623 in a text flow.
3624
3625 Note that the advance can be negative if the text flows from
3626 right to left.
3627*/
3628QSizeF QQuickText::advance() const
3629{
3630 Q_D(const QQuickText);
3631 return d->advance;
3632}
3633
3634QT_END_NAMESPACE
3635
3636#include "moc_qquicktext_p.cpp"
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
#define QQUICKTEXT_LARGETEXT_THRESHOLD
static void positionInlineImage(QQuickStyledTextImgTag *image, int textPos, const QTextLine &line)
static void getLinks_helper(const QTextLayout *layout, QList< QQuickTextPrivate::LinkDesc > *links)