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
qlabel.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qpainter.h"
6#include "qevent.h"
7#include "qpixmapcache.h"
8#include "qstyle.h"
9#include "qstyleoption.h"
10#include "qlabel_p.h"
11#include "private/qhexstring_p.h"
12#include <qmath.h>
13
14#if QT_CONFIG(style_stylesheet)
15#include "private/qstylesheetstyle_p.h"
16#endif
17#if QT_CONFIG(abstractbutton)
18#include "qabstractbutton.h"
19#endif
20#if QT_CONFIG(accessibility)
21#include <qaccessible.h>
22#endif
23
25
26Q_STATIC_LOGGING_CATEGORY(lcWidgetLabel, "qt.widgets.label")
27
28using namespace Qt::StringLiterals;
29
30QLabelPrivate::QLabelPrivate()
31 : QFramePrivate(),
32 valid_hints(false),
33 scaledcontents(false),
34 textLayoutDirty(false),
35 textDirty(false),
36 isTextLabel(false),
37 hasShortcut(false),
38 textFormatWarningDisplayed(false),
39#ifndef QT_NO_CURSOR
40 validCursor(false),
41 onAnchor(false),
42#endif
43 openExternalLinks(false)
44{
45}
46
47QLabelPrivate::~QLabelPrivate()
48{
49}
50
51/*!
52 \class QLabel
53 \brief The QLabel widget provides a text or image display.
54
55 \ingroup basicwidgets
56 \inmodule QtWidgets
57
58 \image fusion-label.png {Label}
59
60
61
62 QLabel is used for displaying text or an image. No user
63 interaction functionality is provided. The visual appearance of
64 the label can be configured in various ways, and it can be used
65 for specifying a focus mnemonic key for another widget.
66
67 A QLabel can contain any of the following content types:
68
69 \table
70 \header \li Content \li Setting
71 \row \li Plain text
72 \li Pass a QString to setText().
73 \row \li Rich text
74 \li Pass a QString that contains rich text to setText().
75 \row \li A pixmap
76 \li Pass a QPixmap to setPixmap().
77 \row \li A movie
78 \li Pass a QMovie to setMovie().
79 \row \li A number
80 \li Pass an \e int or a \e double to setNum(), which converts
81 the number to plain text.
82 \row \li Nothing
83 \li The same as an empty plain text. This is the default. Set
84 by clear().
85 \endtable
86
87 \warning When passing a QString to the constructor or calling setText(),
88 make sure to sanitize your input, as QLabel tries to guess whether it
89 displays the text as plain text or as rich text, a subset of HTML 4
90 markup. You may want to call
91 setTextFormat() explicitly, e.g. in case you expect the text to be in
92 plain format but cannot control the text source (for instance when
93 displaying data loaded from the Web).
94
95 When the content is changed using any of these functions, any
96 previous content is cleared.
97
98 By default, labels display \l{alignment}{left-aligned, vertically-centered}
99 text and images, where any tabs in the text to be displayed are
100 \l{Qt::TextExpandTabs}{automatically expanded}. However, the look
101 of a QLabel can be adjusted and fine-tuned in several ways.
102
103 The positioning of the content within the QLabel widget area can
104 be tuned with setAlignment() and setIndent(). Text content can
105 also wrap lines along word boundaries with setWordWrap(). For
106 example, this code sets up a sunken panel with a two-line text in
107 the bottom right corner (both lines being flush with the right
108 side of the label):
109
110 \snippet code/src_gui_widgets_qlabel.cpp 0
111
112 The properties and functions QLabel inherits from QFrame can also
113 be used to specify the widget frame to be used for any given label.
114
115 A QLabel is often used as a label for an interactive widget. For
116 this use QLabel provides a useful mechanism for adding an
117 mnemonic (see QKeySequence) that will set the keyboard focus to
118 the other widget (called the QLabel's "buddy"). For example:
119
120 \snippet code/src_gui_widgets_qlabel.cpp 1
121
122 In this example, keyboard focus is transferred to the label's
123 buddy (the QLineEdit) when the user presses Alt+P. If the buddy
124 was a button (inheriting from QAbstractButton), triggering the
125 mnemonic would emulate a button click.
126
127 \sa QLineEdit, QTextEdit, QPixmap, QMovie
128*/
129
130#ifndef QT_NO_PICTURE
131/*!
132 \fn QPicture QLabel::picture(Qt::ReturnByValueConstant) const
133 \deprecated Use the overload without argument instead.
134 \since 5.15
135
136 Returns the label's picture.
137
138 Previously, Qt provided a version of \c picture() which returned the picture
139 by-pointer. That version is now removed. This overload allowed to
140 explicitly differentiate between the by-pointer function and the by-value.
141*/
142
143/*!
144 \since 6.0
145
146 Returns the label's picture.
147*/
148QPicture QLabel::picture() const
149{
150 Q_D(const QLabel);
151 if (d->picture)
152 return *(d->picture);
153 return QPicture();
154}
155#endif // QT_NO_PICTURE
156
157
158/*!
159 Constructs an empty label.
160
161 The \a parent and widget flag \a f, arguments are passed
162 to the QFrame constructor.
163
164 \sa setAlignment(), setFrameStyle(), setIndent()
165*/
166QLabel::QLabel(QWidget *parent, Qt::WindowFlags f)
167 : QFrame(*new QLabelPrivate(), parent, f)
168{
169 Q_D(QLabel);
170 d->init();
171}
172
173/*!
174 Constructs a label that displays the text, \a text.
175
176 The \a parent and widget flag \a f, arguments are passed
177 to the QFrame constructor.
178
179 \sa setText(), setAlignment(), setFrameStyle(), setIndent()
180*/
181QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f)
182 : QLabel(parent, f)
183{
184 setText(text);
185}
186
187
188
189/*!
190 Destroys the label.
191*/
192
193QLabel::~QLabel()
194{
195 Q_D(QLabel);
196
197#ifndef QT_NO_SHORTCUT
198 if (d->buddy)
199 d->buddy->d_func()->labels.removeAll(this);
200#endif
201
202 d->clearContents();
203}
204
205void QLabelPrivate::init()
206{
207 Q_Q(QLabel);
208
209 q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred,
210 QSizePolicy::Label));
211 setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
212}
213
214
215/*!
216 \property QLabel::text
217 \brief the label's text.
218
219 If no text has been set this will return an empty string. Setting
220 the text clears any previous content.
221
222 The text will be interpreted either as plain text or as rich
223 text, depending on the text format setting; see setTextFormat().
224 The default setting is Qt::AutoText; i.e. QLabel will try to
225 auto-detect the format of the text set.
226 See \l {Supported HTML Subset} for the definition of rich text.
227
228 If a buddy has been set, the buddy mnemonic key is updated
229 from the new text.
230
231 Note that QLabel is well-suited to display small rich text
232 documents, such as small documents that get their document
233 specific settings (font, text color, link color) from the label's
234 palette and font properties. For large documents, use QTextEdit
235 in read-only mode instead. QTextEdit can also provide a scroll bar
236 when necessary.
237
238 \note This function enables mouse tracking if \a text contains rich
239 text.
240
241 \sa setTextFormat(), setBuddy(), alignment
242*/
243
244void QLabel::setText(const QString &text)
245{
246 Q_D(QLabel);
247 if (d->text == text)
248 return;
249
250 QWidgetTextControl *oldControl = d->control;
251 d->control = nullptr;
252
253 d->clearContents();
254 d->text = text;
255 d->isTextLabel = true;
256 d->textDirty = true;
257 d->effectiveTextFormat = d->textformat.value_or(Qt::AutoText);
258 if (d->effectiveTextFormat == Qt::AutoText) {
259 if (Qt::mightBeRichText(d->text))
260 d->effectiveTextFormat = Qt::RichText;
261 else
262 d->effectiveTextFormat = Qt::PlainText;
263 }
264
265 d->control = oldControl;
266
267 if (d->needTextControl()) {
268 d->ensureTextControl();
269 } else {
270 delete d->control;
271 d->control = nullptr;
272 }
273
274 if (d->effectiveTextFormat != Qt::PlainText) {
275 setMouseTracking(true);
276 } else {
277 // Note: mouse tracking not disabled intentionally
278 }
279
280#ifndef QT_NO_SHORTCUT
281 if (d->buddy)
282 d->updateShortcut();
283#endif
284
285 d->updateLabel();
286
287#if QT_CONFIG(accessibility)
288 if (accessibleName().isEmpty()) {
289 QAccessibleEvent event(this, QAccessible::NameChanged);
290 QAccessible::updateAccessibility(&event);
291 }
292#endif
293}
294
295QString QLabel::text() const
296{
297 Q_D(const QLabel);
298 return d->text;
299}
300
301/*!
302 Clears any label contents.
303*/
304
305void QLabel::clear()
306{
307 Q_D(QLabel);
308 d->clearContents();
309 d->updateLabel();
310}
311
312/*!
313 \property QLabel::pixmap
314 \brief the label's pixmap.
315
316 Setting the pixmap clears any previous content. The buddy
317 shortcut, if any, is disabled.
318*/
319void QLabel::setPixmap(const QPixmap &pixmap)
320{
321 Q_D(QLabel);
322 if (d->icon && d->icon->availableSizes().contains(pixmap.size()) &&
323 d->icon->pixmap(pixmap.size()).cacheKey() == pixmap.cacheKey())
324 return;
325 d->clearContents();
326 d->icon = QIcon(pixmap);
327 d->pixmapSize = pixmap.deviceIndependentSize().toSize();
328 d->updateLabel();
329}
330
331QPixmap QLabel::pixmap() const
332{
333 Q_D(const QLabel);
334 return d->icon ? d->icon->pixmap(d->pixmapSize) : QPixmap();
335}
336
337/*!
338 \fn QPixmap QLabel::pixmap(Qt::ReturnByValueConstant) const
339
340 \deprecated Use the overload without argument instead.
341 \since 5.15
342
343 Returns the label's pixmap.
344
345 Previously, Qt provided a version of \c pixmap() which returned the pixmap
346 by-pointer. That version has now been removed. This overload allowed to
347 explicitly differentiate between the by-pointer function and the by-value.
348
349 \code
350 QPixmap pixmapVal = label->pixmap(Qt::ReturnByValue);
351 \endcode
352*/
353
354#ifndef QT_NO_PICTURE
355/*!
356 Sets the label contents to \a picture. Any previous content is
357 cleared.
358
359 The buddy shortcut, if any, is disabled.
360
361 \sa picture(), setBuddy()
362*/
363
364void QLabel::setPicture(const QPicture &picture)
365{
366 Q_D(QLabel);
367 d->clearContents();
368 d->picture = picture;
369
370 d->updateLabel();
371}
372#endif // QT_NO_PICTURE
373
374/*!
375 Sets the label contents to plain text containing the textual
376 representation of integer \a num. Any previous content is cleared.
377 Does nothing if the integer's string representation is the same as
378 the current contents of the label.
379
380 The buddy shortcut, if any, is disabled.
381
382 \sa setText(), QString::setNum(), setBuddy()
383*/
384
385void QLabel::setNum(int num)
386{
387 setText(QString::number(num));
388}
389
390/*!
391 \overload
392
393 Sets the label contents to plain text containing the textual
394 representation of double \a num. Any previous content is cleared.
395 Does nothing if the double's string representation is the same as
396 the current contents of the label.
397
398 The buddy shortcut, if any, is disabled.
399
400 \sa setText(), QString::setNum(), setBuddy()
401*/
402
403void QLabel::setNum(double num)
404{
405 setText(QString::number(num));
406}
407
408/*!
409 \property QLabel::alignment
410 \brief the alignment of the label's contents.
411
412 By default, the contents of the label are left-aligned and vertically-centered.
413
414 \sa text
415*/
416
417void QLabel::setAlignment(Qt::Alignment alignment)
418{
419 Q_D(QLabel);
420 if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)))
421 return;
422 d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))
423 | (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
424
425 d->updateLabel();
426}
427
428
429Qt::Alignment QLabel::alignment() const
430{
431 Q_D(const QLabel);
432 return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
433}
434
435
436/*!
437 \property QLabel::wordWrap
438 \brief the label's word-wrapping policy.
439
440 If this property is \c true then label text is wrapped where
441 necessary at word-breaks; otherwise it is not wrapped at all.
442
443 By default, word wrap is disabled.
444
445 \sa text
446*/
447void QLabel::setWordWrap(bool on)
448{
449 Q_D(QLabel);
450 if (on)
451 d->align |= Qt::TextWordWrap;
452 else
453 d->align &= ~Qt::TextWordWrap;
454
455 d->updateLabel();
456}
457
458bool QLabel::wordWrap() const
459{
460 Q_D(const QLabel);
461 return d->align & Qt::TextWordWrap;
462}
463
464/*!
465 \property QLabel::indent
466 \brief the label's text indent in pixels.
467
468 If a label displays text, the indent applies to the left edge if
469 alignment() is Qt::AlignLeft, to the right edge if alignment() is
470 Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and
471 to the bottom edge if alignment() is Qt::AlignBottom.
472
473 If indent is negative, or if no indent has been set, the label
474 computes the effective indent as follows: If frameWidth() is 0,
475 the effective indent becomes 0. If frameWidth() is greater than 0,
476 the effective indent becomes half the width of the "x" character
477 of the widget's current font().
478
479 By default, the indent is -1, meaning that an effective indent is
480 calculating in the manner described above.
481
482 \sa alignment, margin, frameWidth(), font()
483*/
484
485void QLabel::setIndent(int indent)
486{
487 Q_D(QLabel);
488 d->indent = indent;
489 d->updateLabel();
490}
491
492int QLabel::indent() const
493{
494 Q_D(const QLabel);
495 return d->indent;
496}
497
498
499/*!
500 \property QLabel::margin
501 \brief the width of the margin.
502
503 The margin is the distance between the innermost pixel of the
504 frame and the outermost pixel of contents.
505
506 The default margin is 0.
507
508 \sa indent
509*/
510int QLabel::margin() const
511{
512 Q_D(const QLabel);
513 return d->margin;
514}
515
516void QLabel::setMargin(int margin)
517{
518 Q_D(QLabel);
519 if (d->margin == margin)
520 return;
521 d->margin = margin;
522 d->updateLabel();
523}
524
525/*!
526 \class QLabelPrivate
527 \inmodule QtWidgets
528 \internal
529*/
530
531/*!
532 Returns the size that will be used if the width of the label is \a
533 w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned
534*/
535QSize QLabelPrivate::sizeForWidth(int w) const
536{
537 Q_Q(const QLabel);
538 if (q->minimumWidth() > 0)
539 w = qMax(w, q->minimumWidth());
540 QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);
541
542 QRect br;
543
544 int hextra = 2 * margin;
545 int vextra = hextra;
546 QFontMetrics fm = q->fontMetrics();
547
548 if (icon && !icon->isNull()) {
549 br = QRect(QPoint(0, 0), pixmapSize);
550#ifndef QT_NO_PICTURE
551 } else if (picture && !picture->isNull()) {
552 br = picture->boundingRect();
553#endif
554#if QT_CONFIG(movie)
555 } else if (movie && !movie->currentPixmap().isNull()) {
556 br = movie->currentPixmap().rect();
557 br.setSize(movie->currentPixmap().deviceIndependentSize().toSize());
558#endif
559 } else if (isTextLabel) {
560 int align = QStyle::visualAlignment(textDirection(), QFlag(this->align));
561 // Add indentation
562 int m = indent;
563
564 if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
565 m = fm.horizontalAdvance(u'x') - margin*2;
566 if (m > 0) {
567 if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
568 hextra += m;
569 if ((align & Qt::AlignTop) || (align & Qt::AlignBottom))
570 vextra += m;
571 }
572
573 if (control) {
574 ensureTextLayouted();
575 const qreal oldTextWidth = control->textWidth();
576 // Calculate the length of document if w is the width
577 if (align & Qt::TextWordWrap) {
578 if (w >= 0) {
579 w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent
580 control->setTextWidth(w);
581 } else {
582 control->adjustSize();
583 }
584 } else {
585 control->setTextWidth(-1);
586 }
587
588 QSizeF controlSize = control->size();
589 br = QRect(QPoint(0, 0), QSize(qCeil(controlSize.width()), qCeil(controlSize.height())));
590
591 // restore state
592 control->setTextWidth(oldTextWidth);
593 } else {
594 // Turn off center alignment in order to avoid rounding errors for centering,
595 // since centering involves a division by 2. At the end, all we want is the size.
596 int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter);
597 if (hasShortcut) {
598 flags |= Qt::TextShowMnemonic;
599 QStyleOption opt;
600 opt.initFrom(q);
601 if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q))
602 flags |= Qt::TextHideMnemonic;
603 }
604
605 bool tryWidth = (w < 0) && (align & Qt::TextWordWrap);
606 if (tryWidth)
607 w = qMin(fm.averageCharWidth() * 80, q->maximumSize().width());
608 else if (w < 0)
609 w = 2000;
610 w -= (hextra + contentsMargin.width());
611 br = fm.boundingRect(0, 0, w ,2000, flags, text);
612 if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2)
613 br = fm.boundingRect(0, 0, w/2, 2000, flags, text);
614 if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4)
615 br = fm.boundingRect(0, 0, w/4, 2000, flags, text);
616 }
617 } else {
618 br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing()));
619 }
620
621 const QSize contentsSize(br.width() + hextra, br.height() + vextra);
622 return (contentsSize + contentsMargin).expandedTo(q->minimumSize());
623}
624
625
626/*!
627 \reimp
628*/
629
630int QLabel::heightForWidth(int w) const
631{
632 Q_D(const QLabel);
633 if (d->isTextLabel)
634 return d->sizeForWidth(w).height();
635 return QWidget::heightForWidth(w);
636}
637
638/*!
639 \property QLabel::openExternalLinks
640 \since 4.2
641
642 Specifies whether QLabel should automatically open links using
643 QDesktopServices::openUrl() instead of emitting the
644 linkActivated() signal.
645
646 \b{Note:} The textInteractionFlags set on the label need to include
647 either LinksAccessibleByMouse or LinksAccessibleByKeyboard.
648
649 The default value is false.
650
651 \sa textInteractionFlags()
652*/
653bool QLabel::openExternalLinks() const
654{
655 Q_D(const QLabel);
656 return d->openExternalLinks;
657}
658
659void QLabel::setOpenExternalLinks(bool open)
660{
661 Q_D(QLabel);
662 d->openExternalLinks = open;
663 if (d->control)
664 d->control->setOpenExternalLinks(open);
665}
666
667/*!
668 \property QLabel::textInteractionFlags
669 \since 4.2
670
671 Specifies how the label should interact with user input if it displays text.
672
673 If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also
674 automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set
675 then the focus policy is set to Qt::ClickFocus.
676
677 The default value is Qt::LinksAccessibleByMouse.
678*/
679void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags)
680{
681 Q_D(QLabel);
682 if (d->textInteractionFlags == flags)
683 return;
684 d->textInteractionFlags = flags;
685 if (flags & Qt::LinksAccessibleByKeyboard)
686 setFocusPolicy(Qt::StrongFocus);
687 else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse))
688 setFocusPolicy(Qt::ClickFocus);
689 else
690 setFocusPolicy(Qt::NoFocus);
691
692 if (d->needTextControl()) {
693 d->ensureTextControl();
694 } else {
695 delete d->control;
696 d->control = nullptr;
697 }
698
699 if (d->control)
700 d->control->setTextInteractionFlags(d->textInteractionFlags);
701}
702
703Qt::TextInteractionFlags QLabel::textInteractionFlags() const
704{
705 Q_D(const QLabel);
706 return d->textInteractionFlags;
707}
708
709/*!
710 Selects text from position \a start and for \a length characters.
711
712 \sa selectedText()
713
714 \b{Note:} The textInteractionFlags set on the label need to include
715 either TextSelectableByMouse or TextSelectableByKeyboard.
716
717 \since 4.7
718*/
719void QLabel::setSelection(int start, int length)
720{
721 Q_D(QLabel);
722 if (d->control) {
723 d->ensureTextPopulated();
724 QTextCursor cursor = d->control->textCursor();
725 cursor.setPosition(start);
726 cursor.setPosition(start + length, QTextCursor::KeepAnchor);
727 d->control->setTextCursor(cursor);
728 }
729}
730
731/*!
732 \property QLabel::hasSelectedText
733 \brief whether there is any text selected
734
735 hasSelectedText() returns \c true if some or all of the text has been
736 selected by the user; otherwise returns \c false.
737
738 By default, this property is \c false.
739
740 \sa selectedText()
741
742 \b{Note:} The textInteractionFlags set on the label need to include
743 either TextSelectableByMouse or TextSelectableByKeyboard.
744
745 \since 4.7
746*/
747bool QLabel::hasSelectedText() const
748{
749 Q_D(const QLabel);
750 if (d->control)
751 return d->control->textCursor().hasSelection();
752 return false;
753}
754
755/*!
756 \property QLabel::selectedText
757 \brief the selected text.
758
759 If there is no selected text this property's value is
760 an empty string.
761
762 By default, this property contains an empty string.
763
764 \sa hasSelectedText()
765
766 \b{Note:} The textInteractionFlags set on the label need to include
767 either TextSelectableByMouse or TextSelectableByKeyboard.
768
769 \since 4.7
770*/
771QString QLabel::selectedText() const
772{
773 Q_D(const QLabel);
774 if (d->control)
775 return d->control->textCursor().selectedText();
776 return QString();
777}
778
779/*!
780 selectionStart() returns the index of the first selected character in the
781 label or -1 if no text is selected.
782
783 \sa selectedText()
784
785 \b{Note:} The textInteractionFlags set on the label need to include
786 either TextSelectableByMouse or TextSelectableByKeyboard.
787
788 \since 4.7
789*/
790int QLabel::selectionStart() const
791{
792 Q_D(const QLabel);
793 if (d->control && d->control->textCursor().hasSelection())
794 return d->control->textCursor().selectionStart();
795 return -1;
796}
797
798/*!\reimp
799*/
800QSize QLabel::sizeHint() const
801{
802 Q_D(const QLabel);
803 if (!d->valid_hints)
804 (void) QLabel::minimumSizeHint();
805 return d->sh;
806}
807
808/*!
809 \reimp
810*/
811QSize QLabel::minimumSizeHint() const
812{
813 Q_D(const QLabel);
814 if (d->valid_hints) {
815 if (d->sizePolicy == sizePolicy())
816 return d->msh;
817 }
818
819 ensurePolished();
820 d->valid_hints = true;
821 d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size
822 QSize msh(-1, -1);
823
824 if (!d->isTextLabel) {
825 msh = d->sh;
826 } else {
827 msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line
828 msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size
829 if (d->sh.height() < msh.height())
830 msh.rheight() = d->sh.height();
831 }
832 d->msh = msh;
833 d->sizePolicy = sizePolicy();
834 return msh;
835}
836
837/*!\reimp
838*/
839void QLabel::mousePressEvent(QMouseEvent *ev)
840{
841 Q_D(QLabel);
842 d->sendControlEvent(ev);
843}
844
845/*!\reimp
846*/
847void QLabel::mouseMoveEvent(QMouseEvent *ev)
848{
849 Q_D(QLabel);
850 d->sendControlEvent(ev);
851}
852
853/*!\reimp
854*/
855void QLabel::mouseReleaseEvent(QMouseEvent *ev)
856{
857 Q_D(QLabel);
858 d->sendControlEvent(ev);
859}
860
861#ifndef QT_NO_CONTEXTMENU
862/*!\reimp
863*/
864void QLabel::contextMenuEvent(QContextMenuEvent *ev)
865{
866 Q_D(QLabel);
867 if (!d->isTextLabel) {
868 ev->ignore();
869 return;
870 }
871 QMenu *menu = d->createStandardContextMenu(ev->pos());
872 if (!menu) {
873 ev->ignore();
874 return;
875 }
876 ev->accept();
877 menu->setAttribute(Qt::WA_DeleteOnClose);
878 menu->popup(ev->globalPos());
879}
880#endif // QT_NO_CONTEXTMENU
881
882/*!
883 \reimp
884*/
885void QLabel::focusInEvent(QFocusEvent *ev)
886{
887 Q_D(QLabel);
888 if (d->isTextLabel) {
889 d->ensureTextControl();
890 d->sendControlEvent(ev);
891 }
892 QFrame::focusInEvent(ev);
893}
894
895/*!
896 \reimp
897*/
898void QLabel::focusOutEvent(QFocusEvent *ev)
899{
900 Q_D(QLabel);
901 if (d->control) {
902 d->sendControlEvent(ev);
903 QTextCursor cursor = d->control->textCursor();
904 Qt::FocusReason reason = ev->reason();
905 if (reason != Qt::ActiveWindowFocusReason
906 && reason != Qt::PopupFocusReason
907 && cursor.hasSelection()) {
908 cursor.clearSelection();
909 d->control->setTextCursor(cursor);
910 }
911 }
912
913 QFrame::focusOutEvent(ev);
914}
915
916/*!\reimp
917*/
918bool QLabel::focusNextPrevChild(bool next)
919{
920 Q_D(QLabel);
921 if (d->control && d->control->setFocusToNextOrPreviousAnchor(next))
922 return true;
923 return QFrame::focusNextPrevChild(next);
924}
925
926/*!\reimp
927*/
928void QLabel::keyPressEvent(QKeyEvent *ev)
929{
930 Q_D(QLabel);
931 d->sendControlEvent(ev);
932}
933
934/*!\reimp
935*/
936bool QLabel::event(QEvent *e)
937{
938 Q_D(QLabel);
939
940 switch (e->type()) {
941#ifndef QT_NO_SHORTCUT
942 case QEvent::Shortcut: {
943 QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
944 if (se->shortcutId() == d->shortcutId) {
945 QWidget *w = d->buddy;
946 if (!w)
947 return QFrame::event(e);
948 if (w->focusPolicy() != Qt::NoFocus)
949 w->setFocus(Qt::ShortcutFocusReason);
950#if QT_CONFIG(abstractbutton)
951 QAbstractButton *button = qobject_cast<QAbstractButton *>(w);
952 if (button && !se->isAmbiguous())
953 button->animateClick();
954 else
955#endif
956 window()->setAttribute(Qt::WA_KeyboardFocusChange);
957 return true;
958 }
959 break;
960 }
961#endif
962 case QEvent::Resize:
963 if (d->control)
964 d->textLayoutDirty = true;
965 break;
966 case QEvent::StyleChange:
967#ifdef Q_OS_MACOS
968 case QEvent::MacSizeChange:
969#endif
970 d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
971 d->updateLabel();
972 break;
973 case QEvent::Polish:
974 if (d->needTextControl())
975 d->ensureTextControl();
976 break;
977 case QEvent::Enter:
978 case QEvent::Leave:
979 d->sendControlEvent(e);
980 break;
981 default:
982 break;
983 }
984
985 return QFrame::event(e);
986}
987
988/*!\reimp
989*/
990void QLabel::paintEvent(QPaintEvent *)
991{
992 Q_D(QLabel);
993 QStyle *style = QWidget::style();
994 QPainter painter(this);
995 drawFrame(&painter);
996 QRect cr = contentsRect();
997 cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
998 int align = QStyle::visualAlignment(d->isTextLabel ? d->textDirection()
999 : layoutDirection(), QFlag(d->align));
1000
1001#if QT_CONFIG(movie)
1002 if (d->movie && !d->movie->currentPixmap().isNull()) {
1003 if (d->scaledcontents)
1004 style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
1005 else
1006 style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
1007 }
1008 else
1009#endif
1010 if (d->isTextLabel) {
1011 QRectF lr = d->layoutRect().toAlignedRect();
1012 QStyleOption opt;
1013 opt.initFrom(this);
1014#if QT_CONFIG(style_stylesheet)
1015 if (QStyleSheetStyle* cssStyle = qt_styleSheet(style))
1016 cssStyle->styleSheetPalette(this, &opt, &opt.palette);
1017#endif
1018 if (d->control) {
1019#ifndef QT_NO_SHORTCUT
1020 const bool underline = static_cast<bool>(style->styleHint(QStyle::SH_UnderlineShortcut,
1021 nullptr, this, nullptr));
1022 if (d->shortcutId != 0
1023 && underline != d->shortcutCursor.charFormat().fontUnderline()) {
1024 QTextCharFormat fmt;
1025 fmt.setFontUnderline(underline);
1026 d->shortcutCursor.mergeCharFormat(fmt);
1027 }
1028#endif
1029 d->ensureTextLayouted();
1030
1031 QAbstractTextDocumentLayout::PaintContext context;
1032 // Adjust the palette
1033 context.palette = opt.palette;
1034
1035 if (foregroundRole() != QPalette::Text && isEnabled())
1036 context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));
1037
1038 painter.save();
1039 painter.translate(lr.topLeft());
1040 painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
1041 d->control->setPalette(context.palette);
1042 d->control->drawContents(&painter, QRectF(), this);
1043 painter.restore();
1044 } else {
1045 int flags = align | (d->textDirection() == Qt::LeftToRight ? Qt::TextForceLeftToRight
1046 : Qt::TextForceRightToLeft);
1047 if (d->hasShortcut) {
1048 flags |= Qt::TextShowMnemonic;
1049 if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
1050 flags |= Qt::TextHideMnemonic;
1051 }
1052 style->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), d->text, foregroundRole());
1053 }
1054 } else
1055#ifndef QT_NO_PICTURE
1056 if (d->picture) {
1057 QRect br = d->picture->boundingRect();
1058 int rw = br.width();
1059 int rh = br.height();
1060 if (d->scaledcontents) {
1061 painter.save();
1062 painter.translate(cr.x(), cr.y());
1063 painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
1064 painter.drawPicture(-br.x(), -br.y(), *d->picture);
1065 painter.restore();
1066 } else {
1067 int xo = 0;
1068 int yo = 0;
1069 if (align & Qt::AlignVCenter)
1070 yo = (cr.height()-rh)/2;
1071 else if (align & Qt::AlignBottom)
1072 yo = cr.height()-rh;
1073 if (align & Qt::AlignRight)
1074 xo = cr.width()-rw;
1075 else if (align & Qt::AlignHCenter)
1076 xo = (cr.width()-rw)/2;
1077 painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
1078 }
1079 } else
1080#endif
1081 if (d->icon && !d->icon->isNull()) {
1082 const qreal dpr = devicePixelRatio();
1083 const QSize size = d->scaledcontents ? cr.size() : d->pixmapSize;
1084 const auto mode = isEnabled() ? QIcon::Normal : QIcon::Disabled;
1085 QPixmap pix = d->icon->pixmap(size, dpr, mode);
1086 // the size of the returned pixmap might not match when
1087 // - scaledContents is enabled
1088 // - the dpr does not match the one from the pixmap in QIcon
1089 // since QStyle::drawItemPixmap() stretches without Qt::SmoothTransformation
1090 // we do it here
1091 if (pix.size() != size * dpr) {
1092 const QString key = "qt_label_"_L1 % HexString<quint64>(pix.cacheKey())
1093 % HexString<quint8>(mode)
1094 % HexString<uint>(size.width())
1095 % HexString<uint>(size.height())
1096 % HexString<quint16>(qRound(dpr * 1000));
1097 if (!QPixmapCache::find(key, &pix)) {
1098 pix = pix.scaled(size * dpr, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
1099 pix.setDevicePixelRatio(dpr);
1100 // using QIcon to cache the newly create pixmap is not possible
1101 // because QIcon does not clear this cache (so we grow indefinitely)
1102 // and also uses the newly added pixmap as starting point for new
1103 // scaled pixmap which makes it very blurry.
1104 // Therefore use QPixmapCache here.
1105 QPixmapCache::insert(key, pix);
1106 }
1107 }
1108 QStyleOption opt;
1109 opt.initFrom(this);
1110 style->drawItemPixmap(&painter, cr, align, pix);
1111 }
1112}
1113
1114
1115/*!
1116 Updates the label, but not the frame.
1117*/
1118
1119void QLabelPrivate::updateLabel()
1120{
1121 Q_Q(QLabel);
1122 valid_hints = false;
1123
1124 if (isTextLabel) {
1125 QSizePolicy policy = q->sizePolicy();
1126 const bool wrap = align & Qt::TextWordWrap;
1127 policy.setHeightForWidth(wrap);
1128 if (policy != q->sizePolicy()) // ### should be replaced by WA_WState_OwnSizePolicy idiom
1129 q->setSizePolicy(policy);
1130 textLayoutDirty = true;
1131 }
1132 q->updateGeometry();
1133 q->update(q->contentsRect());
1134}
1135
1136#ifndef QT_NO_SHORTCUT
1137/*!
1138 Sets this label's buddy to \a buddy.
1139
1140 When the user presses the shortcut key indicated by this label,
1141 the keyboard focus is transferred to the label's buddy widget.
1142
1143 The buddy mechanism is only available for QLabels that contain
1144 text in which one character is prefixed with an ampersand, '&'.
1145 This character is set as the shortcut key. See the \l
1146 QKeySequence::mnemonic() documentation for details (to display an
1147 actual ampersand, use '&&').
1148
1149 In a dialog, you might create two data entry widgets and a label
1150 for each, and set up the geometry layout so each label is just to
1151 the left of its data entry widget (its "buddy"), for example:
1152 \snippet code/src_gui_widgets_qlabel.cpp 2
1153
1154 With the code above, the focus jumps to the Name field when the
1155 user presses Alt+N, and to the Phone field when the user presses
1156 Alt+P.
1157
1158 To unset a previously set buddy, call this function with \a buddy
1159 set to nullptr.
1160
1161 \sa buddy(), setText(), QShortcut, setAlignment()
1162*/
1163
1164void QLabel::setBuddy(QWidget *buddy)
1165{
1166 Q_D(QLabel);
1167
1168 if (d->buddy) {
1169 QObjectPrivate::disconnect(d->buddy, &QObject::destroyed,
1170 d, &QLabelPrivate::buddyDeleted);
1171 d->buddy->d_func()->labels.removeAll(this);
1172 }
1173
1174 d->buddy = buddy;
1175
1176 if (buddy) {
1177 buddy->d_func()->labels.append(this);
1178 QObjectPrivate::connect(buddy, &QObject::destroyed,
1179 d, &QLabelPrivate::buddyDeleted);
1180 }
1181
1182 if (d->isTextLabel) {
1183 if (d->shortcutId)
1184 releaseShortcut(d->shortcutId);
1185 d->shortcutId = 0;
1186 d->textDirty = true;
1187 if (buddy)
1188 d->updateShortcut(); // grab new shortcut
1189 d->updateLabel();
1190 }
1191}
1192
1193
1194/*!
1195 Returns this label's buddy, or nullptr if no buddy is currently set.
1196
1197 \sa setBuddy()
1198*/
1199
1200QWidget * QLabel::buddy() const
1201{
1202 Q_D(const QLabel);
1203 return d->buddy;
1204}
1205
1206void QLabelPrivate::updateShortcut()
1207{
1208 Q_Q(QLabel);
1209 Q_ASSERT(shortcutId == 0);
1210 // Introduce an extra boolean to indicate the presence of a shortcut in the
1211 // text. We cannot use the shortcutId itself because on the mac mnemonics are
1212 // off by default, so QKeySequence::mnemonic always returns an empty sequence.
1213 // But then we do want to hide the ampersands, so we can't use shortcutId.
1214 hasShortcut = false;
1215
1216 if (!text.contains(u'&'))
1217 return;
1218 hasShortcut = true;
1219 shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
1220}
1221
1222
1223void QLabelPrivate::buddyDeleted()
1224{
1225 Q_Q(QLabel);
1226 q->setBuddy(nullptr);
1227}
1228
1229#endif // QT_NO_SHORTCUT
1230
1231#if QT_CONFIG(movie)
1232void QLabelPrivate::movieUpdated(const QRect &rect)
1233{
1234 Q_Q(QLabel);
1235 if (movie && movie->isValid()) {
1236 QRect r;
1237 if (scaledcontents) {
1238 QRect cr = q->contentsRect();
1239 QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size());
1240 if (pixmapRect.isEmpty())
1241 return;
1242 r.setRect(cr.left(), cr.top(),
1243 (rect.width() * cr.width()) / pixmapRect.width(),
1244 (rect.height() * cr.height()) / pixmapRect.height());
1245 } else {
1246 r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap());
1247 r.translate(rect.x(), rect.y());
1248 r.setWidth(qMin(r.width(), rect.width()));
1249 r.setHeight(qMin(r.height(), rect.height()));
1250 }
1251 q->update(r);
1252 }
1253}
1254
1255void QLabelPrivate::movieResized(const QSize &size)
1256{
1257 Q_Q(QLabel);
1258 q->update(); //we need to refresh the whole background in case the new size is smaller
1259 valid_hints = false;
1260 movieUpdated(QRect(QPoint(0,0), size));
1261 q->updateGeometry();
1262}
1263
1264/*!
1265 Sets the label contents to \a movie. Any previous content is
1266 cleared. The label does NOT take ownership of the movie.
1267
1268 The buddy shortcut, if any, is disabled.
1269
1270 \sa movie(), setBuddy()
1271*/
1272
1273void QLabel::setMovie(QMovie *movie)
1274{
1275 Q_D(QLabel);
1276 d->clearContents();
1277
1278 if (!movie)
1279 return;
1280
1281 d->movie = movie;
1282 d->movieConnections = {
1283 QObjectPrivate::connect(movie, &QMovie::resized, d, &QLabelPrivate::movieResized),
1284 QObjectPrivate::connect(movie, &QMovie::updated, d, &QLabelPrivate::movieUpdated),
1285 };
1286
1287 // Assume that if the movie is running,
1288 // resize/update signals will come soon enough
1289 if (movie->state() != QMovie::Running)
1290 d->updateLabel();
1291}
1292
1293#endif // QT_CONFIG(movie)
1294
1295/*!
1296 \internal
1297
1298 Clears any contents, without updating/repainting the label.
1299*/
1300
1301void QLabelPrivate::clearContents()
1302{
1303 delete control;
1304 control = nullptr;
1305 isTextLabel = false;
1306 hasShortcut = false;
1307
1308#ifndef QT_NO_PICTURE
1309 picture.reset();
1310#endif
1311 icon.reset();
1312 pixmapSize = QSize();
1313
1314 text.clear();
1315 Q_Q(QLabel);
1316#ifndef QT_NO_SHORTCUT
1317 if (shortcutId)
1318 q->releaseShortcut(shortcutId);
1319 shortcutId = 0;
1320#endif
1321#if QT_CONFIG(movie)
1322 for (auto &conn : movieConnections)
1323 QObject::disconnect(conn);
1324 movie = nullptr;
1325#endif
1326#ifndef QT_NO_CURSOR
1327 if (onAnchor) {
1328 if (validCursor)
1329 q->setCursor(cursor);
1330 else
1331 q->unsetCursor();
1332 }
1333 validCursor = false;
1334 onAnchor = false;
1335#endif
1336}
1337
1338
1339#if QT_CONFIG(movie)
1340
1341/*!
1342 Returns a pointer to the label's movie, or nullptr if no movie has been
1343 set.
1344
1345 \sa setMovie()
1346*/
1347
1348QMovie *QLabel::movie() const
1349{
1350 Q_D(const QLabel);
1351 return d->movie;
1352}
1353
1354#endif // QT_CONFIG(movie)
1355
1356/*!
1357 \property QLabel::textFormat
1358 \brief the label's text format.
1359
1360 See the Qt::TextFormat enum for an explanation of the possible
1361 options.
1362
1363 The default format is Qt::AutoText.
1364
1365 \sa text()
1366*/
1367
1368Qt::TextFormat QLabel::textFormat() const
1369{
1370 Q_D(const QLabel);
1371 return d->textformat.value_or(Qt::AutoText);
1372}
1373
1374void QLabel::setTextFormat(Qt::TextFormat format)
1375{
1376 Q_D(QLabel);
1377 if (!d->textformat || format != d->textformat.value()) {
1378 d->textformat = format;
1379 QString t = d->text;
1380 if (!t.isNull()) {
1381 d->text.clear();
1382 setText(t);
1383 }
1384 }
1385}
1386
1387/*!
1388 \since 6.1
1389
1390 Returns the resource provider for rich text of this label.
1391*/
1392QTextDocument::ResourceProvider QLabel::resourceProvider() const
1393{
1394 Q_D(const QLabel);
1395 return d->control ? d->control->document()->resourceProvider() : d->resourceProvider;
1396}
1397
1398/*!
1399 \since 6.1
1400
1401 Sets the \a provider of resources for rich text of this label.
1402
1403 \note The label \e{does not} take ownership of the \a provider.
1404*/
1405void QLabel::setResourceProvider(const QTextDocument::ResourceProvider &provider)
1406{
1407 Q_D(QLabel);
1408 d->resourceProvider = provider;
1409 if (d->control != nullptr)
1410 d->control->document()->setResourceProvider(provider);
1411}
1412
1413/*!
1414 \reimp
1415*/
1416void QLabel::changeEvent(QEvent *ev)
1417{
1418 Q_D(QLabel);
1419 if (ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
1420 if (d->isTextLabel) {
1421 if (d->control)
1422 d->control->document()->setDefaultFont(font());
1423 d->updateLabel();
1424 }
1425 } else if (ev->type() == QEvent::PaletteChange && d->control) {
1426 d->control->setPalette(palette());
1427 } else if (ev->type() == QEvent::ContentsRectChange) {
1428 d->updateLabel();
1429 }
1430 QFrame::changeEvent(ev);
1431}
1432
1433/*!
1434 \property QLabel::scaledContents
1435 \brief whether the label will scale its contents to fill all
1436 available space.
1437
1438 When enabled and the label shows a pixmap, it will scale the
1439 pixmap to fill the available space.
1440
1441 This property's default is false.
1442*/
1443bool QLabel::hasScaledContents() const
1444{
1445 Q_D(const QLabel);
1446 return d->scaledcontents;
1447}
1448
1449void QLabel::setScaledContents(bool enable)
1450{
1451 Q_D(QLabel);
1452 if ((bool)d->scaledcontents == enable)
1453 return;
1454 d->scaledcontents = enable;
1455 update(contentsRect());
1456}
1457
1458Qt::LayoutDirection QLabelPrivate::textDirection() const
1459{
1460 if (control) {
1461 QTextOption opt = control->document()->defaultTextOption();
1462 return opt.textDirection();
1463 }
1464
1465 return text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
1466}
1467
1468
1469// Returns the rect that is available for us to draw the document
1470QRect QLabelPrivate::documentRect() const
1471{
1472 Q_Q(const QLabel);
1473 Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!");
1474 QRect cr = q->contentsRect();
1475 cr.adjust(margin, margin, -margin, -margin);
1476 const int align = QStyle::visualAlignment(isTextLabel ? textDirection()
1477 : q->layoutDirection(), QFlag(this->align));
1478 int m = indent;
1479 if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
1480 m = q->fontMetrics().horizontalAdvance(u'x') / 2 - margin;
1481 if (m > 0) {
1482 if (align & Qt::AlignLeft)
1483 cr.setLeft(cr.left() + m);
1484 if (align & Qt::AlignRight)
1485 cr.setRight(cr.right() - m);
1486 if (align & Qt::AlignTop)
1487 cr.setTop(cr.top() + m);
1488 if (align & Qt::AlignBottom)
1489 cr.setBottom(cr.bottom() - m);
1490 }
1491 return cr;
1492}
1493
1494void QLabelPrivate::ensureTextPopulated() const
1495{
1496 Q_Q(const QLabel);
1497 if (!textDirty)
1498 return;
1499 if (control) {
1500 QTextDocument *doc = control->document();
1501 if (textDirty) {
1502 if (effectiveTextFormat == Qt::PlainText) {
1503 doc->setPlainText(text);
1504#if QT_CONFIG(texthtmlparser)
1505 } else if (effectiveTextFormat == Qt::RichText) {
1506 if (!textformat && !textFormatWarningDisplayed) {
1507 qCWarning(lcWidgetLabel)
1508 << "QLabel: Rich text support has implicitly been enabled on a label with the "
1509 "default text format of Qt::AutoText. To protect against unexpected rich "
1510 "text support, the default text format will change to Qt::PlainText in a "
1511 "future version of Qt. Please explicitly choose the appropriate text format "
1512 "in your components to avoid errors in a future upgrade. "
1513 "Affected component:" << q;
1514 textFormatWarningDisplayed = true;
1515 }
1516
1517 doc->setHtml(text);
1518#endif
1519#if QT_CONFIG(textmarkdownreader)
1520 } else if (effectiveTextFormat == Qt::MarkdownText) {
1521 doc->setMarkdown(text);
1522#endif
1523 } else {
1524 doc->setPlainText(text);
1525 }
1526 doc->setUndoRedoEnabled(false);
1527
1528#ifndef QT_NO_SHORTCUT
1529 if (hasShortcut) {
1530 // Underline the first character that follows an ampersand (and remove the others ampersands)
1531 int from = 0;
1532 bool found = false;
1533 QTextCursor cursor;
1534 while (!(cursor = control->document()->find(("&"_L1), from)).isNull()) {
1535 cursor.deleteChar(); // remove the ampersand
1536 cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
1537 from = cursor.position();
1538 if (!found && cursor.selectedText() != "&"_L1) { //not a second &
1539 found = true;
1540 shortcutCursor = cursor;
1541 }
1542 }
1543 }
1544#endif
1545 }
1546 }
1547 textDirty = false;
1548}
1549
1550void QLabelPrivate::ensureTextLayouted() const
1551{
1552 if (!textLayoutDirty)
1553 return;
1554 ensureTextPopulated();
1555 if (control) {
1556 QTextDocument *doc = control->document();
1557 QTextOption opt = doc->defaultTextOption();
1558
1559 opt.setAlignment(QFlag(this->align));
1560
1561 if (this->align & Qt::TextWordWrap)
1562 opt.setWrapMode(QTextOption::WordWrap);
1563 else
1564 opt.setWrapMode(QTextOption::ManualWrap);
1565
1566 doc->setDefaultTextOption(opt);
1567
1568 QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
1569 fmt.setMargin(0);
1570 doc->rootFrame()->setFrameFormat(fmt);
1571 doc->setTextWidth(documentRect().width());
1572 }
1573 textLayoutDirty = false;
1574}
1575
1576void QLabelPrivate::ensureTextControl() const
1577{
1578 Q_Q(const QLabel);
1579 if (!isTextLabel)
1580 return;
1581 if (!control) {
1582 control = new QWidgetTextControl(const_cast<QLabel *>(q));
1583 control->document()->setUndoRedoEnabled(false);
1584 control->document()->setDefaultFont(q->font());
1585 if (resourceProvider != nullptr)
1586 control->document()->setResourceProvider(resourceProvider);
1587 control->setTextInteractionFlags(textInteractionFlags);
1588 control->setOpenExternalLinks(openExternalLinks);
1589 control->setPalette(q->palette());
1590 control->setFocus(q->hasFocus());
1591 QObject::connect(control, &QWidgetTextControl::updateRequest,
1592 q, qOverload<>(&QLabel::update));
1593 QObject::connect(control, &QWidgetTextControl::linkActivated,
1594 q, &QLabel::linkActivated);
1595 QObjectPrivate::connect(control, &QWidgetTextControl::linkHovered,
1596 this, &QLabelPrivate::linkHovered);
1597 textLayoutDirty = true;
1598 textDirty = true;
1599 }
1600}
1601
1602void QLabelPrivate::sendControlEvent(QEvent *e)
1603{
1604 Q_Q(QLabel);
1605 if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) {
1606 e->ignore();
1607 return;
1608 }
1609 control->processEvent(e, -layoutRect().topLeft(), q);
1610}
1611
1612void QLabelPrivate::linkHovered(const QString &anchor)
1613{
1614 Q_Q(QLabel);
1615#ifndef QT_NO_CURSOR
1616 if (anchor.isEmpty()) { // restore cursor
1617 if (validCursor)
1618 q->setCursor(cursor);
1619 else
1620 q->unsetCursor();
1621 onAnchor = false;
1622 } else if (!onAnchor) {
1623 validCursor = q->testAttribute(Qt::WA_SetCursor);
1624 if (validCursor) {
1625 cursor = q->cursor();
1626 }
1627 q->setCursor(Qt::PointingHandCursor);
1628 onAnchor = true;
1629 }
1630#endif
1631 emit q->linkHovered(anchor);
1632}
1633
1634// Return the layout rect - this is the rect that is given to the layout painting code
1635// This may be different from the document rect since vertical alignment is not
1636// done by the text layout code
1637QRectF QLabelPrivate::layoutRect() const
1638{
1639 QRectF cr = documentRect();
1640 if (!control)
1641 return cr;
1642 ensureTextLayouted();
1643 // Calculate y position manually
1644 qreal rh = control->document()->documentLayout()->documentSize().height();
1645 qreal yo = 0;
1646 if (align & Qt::AlignVCenter)
1647 yo = qMax((cr.height()-rh)/2, qreal(0));
1648 else if (align & Qt::AlignBottom)
1649 yo = qMax(cr.height()-rh, qreal(0));
1650 return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height());
1651}
1652
1653// Returns the point in the document rect adjusted with p
1654QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
1655{
1656 QRect lr = layoutRect().toRect();
1657 return p - lr.topLeft();
1658}
1659
1660#ifndef QT_NO_CONTEXTMENU
1661QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
1662{
1663 if (!control)
1664 return nullptr;
1665
1666 const QPoint p = layoutPoint(pos);
1667 return control->createStandardContextMenu(p, q_func());
1668}
1669#endif
1670
1671/*!
1672 \fn void QLabel::linkHovered(const QString &link)
1673 \since 4.2
1674
1675 This signal is emitted when the user hovers over a link. The URL
1676 referred to by the anchor is passed in \a link.
1677
1678 \sa linkActivated()
1679*/
1680
1681
1682/*!
1683 \fn void QLabel::linkActivated(const QString &link)
1684 \since 4.2
1685
1686 This signal is emitted when the user clicks a link. The URL
1687 referred to by the anchor is passed in \a link.
1688
1689 \sa linkHovered()
1690*/
1691
1692QT_END_NAMESPACE
1693
1694#include "moc_qlabel.cpp"
Combined button and popup list for selecting options.