summaryrefslogtreecommitdiffstats
path: root/src/widgets/widgets/qlabel.cpp
blob: 9b13cfcb9b6f44ec68a6dc39b22c9bc9a1ad5326 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qpainter.h"
#include "qevent.h"
#include "qdrawutil.h"
#include "qapplication.h"
#if QT_CONFIG(abstractbutton)
#include "qabstractbutton.h"
#endif
#include "qstyle.h"
#include "qstyleoption.h"
#include <limits.h>
#include "qclipboard.h"
#include <qdebug.h>
#include <qurl.h>
#include "qlabel_p.h"
#include "private/qstylesheetstyle_p.h"
#include <qmath.h>

#ifndef QT_NO_ACCESSIBILITY
#include <qaccessible.h>
#endif

QT_BEGIN_NAMESPACE

QLabelPrivate::QLabelPrivate()
    : QFramePrivate(),
      sh(),
      msh(),
      text(),
      pixmap(nullptr),
      scaledpixmap(nullptr),
      cachedimage(nullptr),
#ifndef QT_NO_PICTURE
      picture(nullptr),
#endif
#if QT_CONFIG(movie)
      movie(),
#endif
      control(nullptr),
      shortcutCursor(),
#ifndef QT_NO_CURSOR
      cursor(),
#endif
#ifndef QT_NO_SHORTCUT
      buddy(),
      shortcutId(0),
#endif
      textformat(Qt::AutoText),
      effectiveTextFormat(Qt::PlainText),
      textInteractionFlags(Qt::LinksAccessibleByMouse),
      sizePolicy(),
      margin(0),
      align(Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs),
      indent(-1),
      valid_hints(false),
      scaledcontents(false),
      textLayoutDirty(false),
      textDirty(false),
      isTextLabel(false),
      hasShortcut(/*???*/),
#ifndef QT_NO_CURSOR
      validCursor(false),
      onAnchor(false),
#endif
      openExternalLinks(false),
      resourceProvider(nullptr)
{
}

QLabelPrivate::~QLabelPrivate()
{
}

/*!
    \class QLabel
    \brief The QLabel widget provides a text or image display.

    \ingroup basicwidgets
    \inmodule QtWidgets

    \image windows-label.png

    QLabel is used for displaying text or an image. No user
    interaction functionality is provided. The visual appearance of
    the label can be configured in various ways, and it can be used
    for specifying a focus mnemonic key for another widget.

    A QLabel can contain any of the following content types:

    \table
    \header \li Content \li Setting
    \row \li Plain text
         \li Pass a QString to setText().
    \row \li Rich text
         \li Pass a QString that contains rich text to setText().
    \row \li A pixmap
         \li Pass a QPixmap to setPixmap().
    \row \li A movie
         \li Pass a QMovie to setMovie().
    \row \li A number
         \li Pass an \e int or a \e double to setNum(), which converts
            the number to plain text.
    \row \li Nothing
         \li The same as an empty plain text. This is the default. Set
            by clear().
    \endtable

    \warning When passing a QString to the constructor or calling setText(),
    make sure to sanitize your input, as QLabel tries to guess whether it
    displays the text as plain text or as rich text, a subset of HTML 4
    markup. You may want to call
    setTextFormat() explicitly, e.g. in case you expect the text to be in
    plain format but cannot control the text source (for instance when
    displaying data loaded from the Web).

    When the content is changed using any of these functions, any
    previous content is cleared.

    By default, labels display \l{alignment}{left-aligned, vertically-centered}
    text and images, where any tabs in the text to be displayed are
    \l{Qt::TextExpandTabs}{automatically expanded}. However, the look
    of a QLabel can be adjusted and fine-tuned in several ways.

    The positioning of the content within the QLabel widget area can
    be tuned with setAlignment() and setIndent(). Text content can
    also wrap lines along word boundaries with setWordWrap(). For
    example, this code sets up a sunken panel with a two-line text in
    the bottom right corner (both lines being flush with the right
    side of the label):

    \snippet code/src_gui_widgets_qlabel.cpp 0

    The properties and functions QLabel inherits from QFrame can also
    be used to specify the widget frame to be used for any given label.

    A QLabel is often used as a label for an interactive widget. For
    this use QLabel provides a useful mechanism for adding an
    mnemonic (see QKeySequence) that will set the keyboard focus to
    the other widget (called the QLabel's "buddy"). For example:

    \snippet code/src_gui_widgets_qlabel.cpp 1

    In this example, keyboard focus is transferred to the label's
    buddy (the QLineEdit) when the user presses Alt+P. If the buddy
    was a button (inheriting from QAbstractButton), triggering the
    mnemonic would emulate a button click.

    \sa QLineEdit, QTextEdit, QPixmap, QMovie
*/

#ifndef QT_NO_PICTURE
/*!
    \fn QPicture QLabel::picture(Qt::ReturnByValueConstant) const
    \deprecated Use the overload without argument instead.
    \since 5.15

    Returns the label's picture.

    Previously, Qt provided a version of \c picture() which returned the picture
    by-pointer. That version is now removed. This overload allowed to
    explicitly differentiate between the by-pointer function and the by-value.
*/

/*!
    \since 6.0

    Returns the label's picture.
*/
QPicture QLabel::picture() const
{
    Q_D(const QLabel);
    if (d->picture)
        return *(d->picture);
    return QPicture();
}
#endif // QT_NO_PICTURE


/*!
    Constructs an empty label.

    The \a parent and widget flag \a f, arguments are passed
    to the QFrame constructor.

    \sa setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(QWidget *parent, Qt::WindowFlags f)
    : QFrame(*new QLabelPrivate(), parent, f)
{
    Q_D(QLabel);
    d->init();
}

/*!
    Constructs a label that displays the text, \a text.

    The \a parent and widget flag \a f, arguments are passed
    to the QFrame constructor.

    \sa setText(), setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f)
    : QLabel(parent, f)
{
    setText(text);
}



/*!
    Destroys the label.
*/

QLabel::~QLabel()
{
    Q_D(QLabel);
    d->clearContents();
}

void QLabelPrivate::init()
{
    Q_Q(QLabel);

    q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred,
                                 QSizePolicy::Label));
    setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
}


/*!
    \property QLabel::text
    \brief the label's text

    If no text has been set this will return an empty string. Setting
    the text clears any previous content.

    The text will be interpreted either as plain text or as rich
    text, depending on the text format setting; see setTextFormat().
    The default setting is Qt::AutoText; i.e. QLabel will try to
    auto-detect the format of the text set.
    See \l {Supported HTML Subset} for the definition of rich text.

    If a buddy has been set, the buddy mnemonic key is updated
    from the new text.

    Note that QLabel is well-suited to display small rich text
    documents, such as small documents that get their document
    specific settings (font, text color, link color) from the label's
    palette and font properties. For large documents, use QTextEdit
    in read-only mode instead. QTextEdit can also provide a scroll bar
    when necessary.

    \note This function enables mouse tracking if \a text contains rich
    text.

    \sa setTextFormat(), setBuddy(), alignment
*/

void QLabel::setText(const QString &text)
{
    Q_D(QLabel);
    if (d->text == text)
        return;

    QWidgetTextControl *oldControl = d->control;
    d->control = nullptr;

    d->clearContents();
    d->text = text;
    d->isTextLabel = true;
    d->textDirty = true;
    if (d->textformat == Qt::AutoText) {
        if (Qt::mightBeRichText(d->text))
            d->effectiveTextFormat = Qt::RichText;
        else
            d->effectiveTextFormat = Qt::PlainText;
    } else {
        d->effectiveTextFormat = d->textformat;
    }

    d->control = oldControl;

    if (d->needTextControl()) {
        d->ensureTextControl();
    } else {
        delete d->control;
        d->control = nullptr;
    }

    if (d->effectiveTextFormat != Qt::PlainText) {
        setMouseTracking(true);
    } else {
        // Note: mouse tracking not disabled intentionally
    }

#ifndef QT_NO_SHORTCUT
    if (d->buddy)
        d->updateShortcut();
#endif

    d->updateLabel();

#ifndef QT_NO_ACCESSIBILITY
    if (accessibleName().isEmpty()) {
        QAccessibleEvent event(this, QAccessible::NameChanged);
        QAccessible::updateAccessibility(&event);
    }
#endif
}

QString QLabel::text() const
{
    Q_D(const QLabel);
    return d->text;
}

/*!
    Clears any label contents.
*/

void QLabel::clear()
{
    Q_D(QLabel);
    d->clearContents();
    d->updateLabel();
}

/*!
    \property QLabel::pixmap
    \brief the label's pixmap.

    Setting the pixmap clears any previous content. The buddy
    shortcut, if any, is disabled.
*/
void QLabel::setPixmap(const QPixmap &pixmap)
{
    Q_D(QLabel);
    if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) {
        d->clearContents();
        d->pixmap = new QPixmap(pixmap);
    }

    if (d->pixmap->depth() == 1 && !d->pixmap->mask())
        d->pixmap->setMask(*((QBitmap *)d->pixmap));

    d->updateLabel();
}

QPixmap QLabel::pixmap() const
{
    Q_D(const QLabel);
    if (d->pixmap)
        return *(d->pixmap);
    return QPixmap();
}

/*!
    \fn QPixmap QLabel::pixmap(Qt::ReturnByValueConstant) const

    \deprecated Use the overload without argument instead.
    \since 5.15

    Returns the label's pixmap.

    Previously, Qt provided a version of \c pixmap() which returned the pixmap
    by-pointer. That version has now been removed. This overload allowed to
    explicitly differentiate between the by-pointer function and the by-value.

    \code
    QPixmap pixmapVal = label->pixmap(Qt::ReturnByValue);
    \endcode
*/

#ifndef QT_NO_PICTURE
/*!
    Sets the label contents to \a picture. Any previous content is
    cleared.

    The buddy shortcut, if any, is disabled.

    \sa picture(), setBuddy()
*/

void QLabel::setPicture(const QPicture &picture)
{
    Q_D(QLabel);
    d->clearContents();
    d->picture = new QPicture(picture);

    d->updateLabel();
}
#endif // QT_NO_PICTURE

/*!
    Sets the label contents to plain text containing the textual
    representation of integer \a num. Any previous content is cleared.
    Does nothing if the integer's string representation is the same as
    the current contents of the label.

    The buddy shortcut, if any, is disabled.

    \sa setText(), QString::setNum(), setBuddy()
*/

void QLabel::setNum(int num)
{
    QString str;
    str.setNum(num);
    setText(str);
}

/*!
    \overload

    Sets the label contents to plain text containing the textual
    representation of double \a num. Any previous content is cleared.
    Does nothing if the double's string representation is the same as
    the current contents of the label.

    The buddy shortcut, if any, is disabled.

    \sa setText(), QString::setNum(), setBuddy()
*/

void QLabel::setNum(double num)
{
    QString str;
    str.setNum(num);
    setText(str);
}

/*!
    \property QLabel::alignment
    \brief the alignment of the label's contents

    By default, the contents of the label are left-aligned and vertically-centered.

    \sa text
*/

void QLabel::setAlignment(Qt::Alignment alignment)
{
    Q_D(QLabel);
    if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)))
        return;
    d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))
               | (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));

    d->updateLabel();
}


Qt::Alignment QLabel::alignment() const
{
    Q_D(const QLabel);
    return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
}


/*!
    \property QLabel::wordWrap
    \brief the label's word-wrapping policy

    If this property is \c true then label text is wrapped where
    necessary at word-breaks; otherwise it is not wrapped at all.

    By default, word wrap is disabled.

    \sa text
*/
void QLabel::setWordWrap(bool on)
{
    Q_D(QLabel);
    if (on)
        d->align |= Qt::TextWordWrap;
    else
        d->align &= ~Qt::TextWordWrap;

    d->updateLabel();
}

bool QLabel::wordWrap() const
{
    Q_D(const QLabel);
    return d->align & Qt::TextWordWrap;
}

/*!
    \property QLabel::indent
    \brief the label's text indent in pixels

    If a label displays text, the indent applies to the left edge if
    alignment() is Qt::AlignLeft, to the right edge if alignment() is
    Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and
    to the bottom edge if alignment() is Qt::AlignBottom.

    If indent is negative, or if no indent has been set, the label
    computes the effective indent as follows: If frameWidth() is 0,
    the effective indent becomes 0. If frameWidth() is greater than 0,
    the effective indent becomes half the width of the "x" character
    of the widget's current font().

    By default, the indent is -1, meaning that an effective indent is
    calculating in the manner described above.

    \sa alignment, margin, frameWidth(), font()
*/

void QLabel::setIndent(int indent)
{
    Q_D(QLabel);
    d->indent = indent;
    d->updateLabel();
}

int QLabel::indent() const
{
    Q_D(const QLabel);
    return d->indent;
}


/*!
    \property QLabel::margin
    \brief the width of the margin

    The margin is the distance between the innermost pixel of the
    frame and the outermost pixel of contents.

    The default margin is 0.

    \sa indent
*/
int QLabel::margin() const
{
    Q_D(const QLabel);
    return d->margin;
}

void QLabel::setMargin(int margin)
{
    Q_D(QLabel);
    if (d->margin == margin)
        return;
    d->margin = margin;
    d->updateLabel();
}

/*!
    Returns the size that will be used if the width of the label is \a
    w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned
*/
QSize QLabelPrivate::sizeForWidth(int w) const
{
    Q_Q(const QLabel);
    if (q->minimumWidth() > 0)
        w = qMax(w, q->minimumWidth());
    QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);

    QRect br;

    int hextra = 2 * margin;
    int vextra = hextra;
    QFontMetrics fm = q->fontMetrics();

    if (pixmap && !pixmap->isNull()) {
        br = pixmap->rect();
        br.setSize(pixmap->deviceIndependentSize().toSize());
#ifndef QT_NO_PICTURE
    } else if (picture && !picture->isNull()) {
        br = picture->boundingRect();
#endif
#if QT_CONFIG(movie)
    } else if (movie && !movie->currentPixmap().isNull()) {
        br = movie->currentPixmap().rect();
        br.setSize(movie->currentPixmap().deviceIndependentSize().toSize());
#endif
    } else if (isTextLabel) {
        int align = QStyle::visualAlignment(textDirection(), QFlag(this->align));
        // Add indentation
        int m = indent;

        if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
            m = fm.horizontalAdvance(QLatin1Char('x')) - margin*2;
        if (m > 0) {
            if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
                hextra += m;
            if ((align & Qt::AlignTop) || (align & Qt::AlignBottom))
                vextra += m;
        }

        if (control) {
            ensureTextLayouted();
            const qreal oldTextWidth = control->textWidth();
            // Calculate the length of document if w is the width
            if (align & Qt::TextWordWrap) {
                if (w >= 0) {
                    w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent
                    control->setTextWidth(w);
                } else {
                    control->adjustSize();
                }
            } else {
                control->setTextWidth(-1);
            }

            QSizeF controlSize = control->size();
            br = QRect(QPoint(0, 0), QSize(qCeil(controlSize.width()), qCeil(controlSize.height())));

            // restore state
            control->setTextWidth(oldTextWidth);
        } else {
            // Turn off center alignment in order to avoid rounding errors for centering,
            // since centering involves a division by 2. At the end, all we want is the size.
            int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter);
            if (hasShortcut) {
                flags |= Qt::TextShowMnemonic;
                QStyleOption opt;
                opt.initFrom(q);
                if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q))
                    flags |= Qt::TextHideMnemonic;
            }

            bool tryWidth = (w < 0) && (align & Qt::TextWordWrap);
            if (tryWidth)
                w = qMin(fm.averageCharWidth() * 80, q->maximumSize().width());
            else if (w < 0)
                w = 2000;
            w -= (hextra + contentsMargin.width());
            br = fm.boundingRect(0, 0, w ,2000, flags, text);
            if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2)
                br = fm.boundingRect(0, 0, w/2, 2000, flags, text);
            if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4)
                br = fm.boundingRect(0, 0, w/4, 2000, flags, text);
        }
    } else {
        br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing()));
    }

    const QSize contentsSize(br.width() + hextra, br.height() + vextra);
    return (contentsSize + contentsMargin).expandedTo(q->minimumSize());
}


/*!
  \reimp
*/

int QLabel::heightForWidth(int w) const
{
    Q_D(const QLabel);
    if (d->isTextLabel)
        return d->sizeForWidth(w).height();
    return QWidget::heightForWidth(w);
}

/*!
    \property QLabel::openExternalLinks
    \since 4.2

    Specifies whether QLabel should automatically open links using
    QDesktopServices::openUrl() instead of emitting the
    linkActivated() signal.

    \b{Note:} The textInteractionFlags set on the label need to include
    either LinksAccessibleByMouse or LinksAccessibleByKeyboard.

    The default value is false.

    \sa textInteractionFlags()
*/
bool QLabel::openExternalLinks() const
{
    Q_D(const QLabel);
    return d->openExternalLinks;
}

void QLabel::setOpenExternalLinks(bool open)
{
    Q_D(QLabel);
    d->openExternalLinks = open;
    if (d->control)
        d->control->setOpenExternalLinks(open);
}

/*!
    \property QLabel::textInteractionFlags
    \since 4.2

    Specifies how the label should interact with user input if it displays text.

    If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also
    automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set
    then the focus policy is set to Qt::ClickFocus.

    The default value is Qt::LinksAccessibleByMouse.
*/
void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags)
{
    Q_D(QLabel);
    if (d->textInteractionFlags == flags)
        return;
    d->textInteractionFlags = flags;
    if (flags & Qt::LinksAccessibleByKeyboard)
        setFocusPolicy(Qt::StrongFocus);
    else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse))
        setFocusPolicy(Qt::ClickFocus);
    else
        setFocusPolicy(Qt::NoFocus);

    if (d->needTextControl()) {
        d->ensureTextControl();
    } else {
        delete d->control;
        d->control = nullptr;
    }

    if (d->control)
        d->control->setTextInteractionFlags(d->textInteractionFlags);
}

Qt::TextInteractionFlags QLabel::textInteractionFlags() const
{
    Q_D(const QLabel);
    return d->textInteractionFlags;
}

/*!
    Selects text from position \a start and for \a length characters.

    \sa selectedText()

    \b{Note:} The textInteractionFlags set on the label need to include
    either TextSelectableByMouse or TextSelectableByKeyboard.

    \since 4.7
*/
void QLabel::setSelection(int start, int length)
{
    Q_D(QLabel);
    if (d->control) {
        d->ensureTextPopulated();
        QTextCursor cursor = d->control->textCursor();
        cursor.setPosition(start);
        cursor.setPosition(start + length, QTextCursor::KeepAnchor);
        d->control->setTextCursor(cursor);
    }
}

/*!
    \property QLabel::hasSelectedText
    \brief whether there is any text selected

    hasSelectedText() returns \c true if some or all of the text has been
    selected by the user; otherwise returns \c false.

    By default, this property is \c false.

    \sa selectedText()

    \b{Note:} The textInteractionFlags set on the label need to include
    either TextSelectableByMouse or TextSelectableByKeyboard.

    \since 4.7
*/
bool QLabel::hasSelectedText() const
{
    Q_D(const QLabel);
    if (d->control)
        return d->control->textCursor().hasSelection();
    return false;
}

/*!
    \property QLabel::selectedText
    \brief the selected text

    If there is no selected text this property's value is
    an empty string.

    By default, this property contains an empty string.

    \sa hasSelectedText()

    \b{Note:} The textInteractionFlags set on the label need to include
    either TextSelectableByMouse or TextSelectableByKeyboard.

    \since 4.7
*/
QString QLabel::selectedText() const
{
    Q_D(const QLabel);
    if (d->control)
        return d->control->textCursor().selectedText();
    return QString();
}

/*!
    selectionStart() returns the index of the first selected character in the
    label or -1 if no text is selected.

    \sa selectedText()

    \b{Note:} The textInteractionFlags set on the label need to include
    either TextSelectableByMouse or TextSelectableByKeyboard.

    \since 4.7
*/
int QLabel::selectionStart() const
{
    Q_D(const QLabel);
    if (d->control && d->control->textCursor().hasSelection())
        return d->control->textCursor().selectionStart();
    return -1;
}

/*!\reimp
*/
QSize QLabel::sizeHint() const
{
    Q_D(const QLabel);
    if (!d->valid_hints)
        (void) QLabel::minimumSizeHint();
    return d->sh;
}

/*!
  \reimp
*/
QSize QLabel::minimumSizeHint() const
{
    Q_D(const QLabel);
    if (d->valid_hints) {
        if (d->sizePolicy == sizePolicy())
            return d->msh;
    }

    ensurePolished();
    d->valid_hints = true;
    d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size
    QSize msh(-1, -1);

    if (!d->isTextLabel) {
        msh = d->sh;
    } else {
        msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line
        msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size
        if (d->sh.height() < msh.height())
            msh.rheight() = d->sh.height();
    }
    d->msh = msh;
    d->sizePolicy = sizePolicy();
    return msh;
}

/*!\reimp
*/
void QLabel::mousePressEvent(QMouseEvent *ev)
{
    Q_D(QLabel);
    d->sendControlEvent(ev);
}

/*!\reimp
*/
void QLabel::mouseMoveEvent(QMouseEvent *ev)
{
    Q_D(QLabel);
    d->sendControlEvent(ev);
}

/*!\reimp
*/
void QLabel::mouseReleaseEvent(QMouseEvent *ev)
{
    Q_D(QLabel);
    d->sendControlEvent(ev);
}

#ifndef QT_NO_CONTEXTMENU
/*!\reimp
*/
void QLabel::contextMenuEvent(QContextMenuEvent *ev)
{
    Q_D(QLabel);
    if (!d->isTextLabel) {
        ev->ignore();
        return;
    }
    QMenu *menu = d->createStandardContextMenu(ev->pos());
    if (!menu) {
        ev->ignore();
        return;
    }
    ev->accept();
    menu->setAttribute(Qt::WA_DeleteOnClose);
    menu->popup(ev->globalPos());
}
#endif // QT_NO_CONTEXTMENU

/*!
    \reimp
*/
void QLabel::focusInEvent(QFocusEvent *ev)
{
    Q_D(QLabel);
    if (d->isTextLabel) {
        d->ensureTextControl();
        d->sendControlEvent(ev);
    }
    QFrame::focusInEvent(ev);
}

/*!
    \reimp
*/
void QLabel::focusOutEvent(QFocusEvent *ev)
{
    Q_D(QLabel);
    if (d->control) {
        d->sendControlEvent(ev);
        QTextCursor cursor = d->control->textCursor();
        Qt::FocusReason reason = ev->reason();
        if (reason != Qt::ActiveWindowFocusReason
            && reason != Qt::PopupFocusReason
            && cursor.hasSelection()) {
            cursor.clearSelection();
            d->control->setTextCursor(cursor);
        }
    }

    QFrame::focusOutEvent(ev);
}

/*!\reimp
*/
bool QLabel::focusNextPrevChild(bool next)
{
    Q_D(QLabel);
    if (d->control && d->control->setFocusToNextOrPreviousAnchor(next))
        return true;
    return QFrame::focusNextPrevChild(next);
}

/*!\reimp
*/
void QLabel::keyPressEvent(QKeyEvent *ev)
{
    Q_D(QLabel);
    d->sendControlEvent(ev);
}

/*!\reimp
*/
bool QLabel::event(QEvent *e)
{
    Q_D(QLabel);
    QEvent::Type type = e->type();

#ifndef QT_NO_SHORTCUT
    if (type == QEvent::Shortcut) {
        QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
        if (se->shortcutId() == d->shortcutId) {
            QWidget *w = d->buddy;
            if (!w)
                return QFrame::event(e);
            if (w->focusPolicy() != Qt::NoFocus)
                w->setFocus(Qt::ShortcutFocusReason);
#if QT_CONFIG(abstractbutton)
            QAbstractButton *button = qobject_cast<QAbstractButton *>(w);
            if (button && !se->isAmbiguous())
                button->animateClick();
            else
#endif
                window()->setAttribute(Qt::WA_KeyboardFocusChange);
            return true;
        }
    } else
#endif
    if (type == QEvent::Resize) {
        if (d->control)
            d->textLayoutDirty = true;
    } else if (e->type() == QEvent::StyleChange
#ifdef Q_OS_MAC
               || e->type() == QEvent::MacSizeChange
#endif
               ) {
        d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
        d->updateLabel();
    } else if (type == QEvent::Polish) {
        if (d->needTextControl())
            d->ensureTextControl();
    }

    return QFrame::event(e);
}

/*!\reimp
*/
void QLabel::paintEvent(QPaintEvent *)
{
    Q_D(QLabel);
    QStyle *style = QWidget::style();
    QPainter painter(this);
    drawFrame(&painter);
    QRect cr = contentsRect();
    cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
    int align = QStyle::visualAlignment(d->isTextLabel ? d->textDirection()
                                                       : layoutDirection(), QFlag(d->align));

#if QT_CONFIG(movie)
    if (d->movie && !d->movie->currentPixmap().isNull()) {
        if (d->scaledcontents)
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
        else
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
    }
    else
#endif
    if (d->isTextLabel) {
        QRectF lr = d->layoutRect().toAlignedRect();
        QStyleOption opt;
        opt.initFrom(this);
#ifndef QT_NO_STYLE_STYLESHEET
        if (QStyleSheetStyle* cssStyle = qt_styleSheet(style))
            cssStyle->styleSheetPalette(this, &opt, &opt.palette);
#endif
        if (d->control) {
#ifndef QT_NO_SHORTCUT
            const bool underline = static_cast<bool>(style->styleHint(QStyle::SH_UnderlineShortcut,
                                                                      nullptr, this, nullptr));
            if (d->shortcutId != 0
                && underline != d->shortcutCursor.charFormat().fontUnderline()) {
                QTextCharFormat fmt;
                fmt.setFontUnderline(underline);
                d->shortcutCursor.mergeCharFormat(fmt);
            }
#endif
            d->ensureTextLayouted();

            QAbstractTextDocumentLayout::PaintContext context;
            // Adjust the palette
            context.palette = opt.palette;

            if (foregroundRole() != QPalette::Text && isEnabled())
                context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));

            painter.save();
            painter.translate(lr.topLeft());
            painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
            d->control->setPalette(context.palette);
            d->control->drawContents(&painter, QRectF(), this);
            painter.restore();
        } else {
            int flags = align | (d->textDirection() == Qt::LeftToRight ? Qt::TextForceLeftToRight
                                                                       : Qt::TextForceRightToLeft);
            if (d->hasShortcut) {
                flags |= Qt::TextShowMnemonic;
                if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
                    flags |= Qt::TextHideMnemonic;
            }
            style->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), d->text, foregroundRole());
        }
    } else
#ifndef QT_NO_PICTURE
    if (d->picture) {
        QRect br = d->picture->boundingRect();
        int rw = br.width();
        int rh = br.height();
        if (d->scaledcontents) {
            painter.save();
            painter.translate(cr.x(), cr.y());
            painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
            painter.drawPicture(-br.x(), -br.y(), *d->picture);
            painter.restore();
        } else {
            int xo = 0;
            int yo = 0;
            if (align & Qt::AlignVCenter)
                yo = (cr.height()-rh)/2;
            else if (align & Qt::AlignBottom)
                yo = cr.height()-rh;
            if (align & Qt::AlignRight)
                xo = cr.width()-rw;
            else if (align & Qt::AlignHCenter)
                xo = (cr.width()-rw)/2;
            painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
        }
    } else
#endif
    if (d->pixmap && !d->pixmap->isNull()) {
        QPixmap pix;
        if (d->scaledcontents) {
            QSize scaledSize = cr.size() * devicePixelRatio();
            if (!d->scaledpixmap || d->scaledpixmap->size() != scaledSize) {
                if (!d->cachedimage)
                    d->cachedimage = new QImage(d->pixmap->toImage());
                delete d->scaledpixmap;
                QImage scaledImage =
                    d->cachedimage->scaled(scaledSize,
                                           Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                d->scaledpixmap = new QPixmap(QPixmap::fromImage(std::move(scaledImage)));
                d->scaledpixmap->setDevicePixelRatio(devicePixelRatio());
            }
            pix = *d->scaledpixmap;
        } else
            pix = *d->pixmap;
        QStyleOption opt;
        opt.initFrom(this);
        if (!isEnabled())
            pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt);
        style->drawItemPixmap(&painter, cr, align, pix);
    }
}


/*!
    Updates the label, but not the frame.
*/

void QLabelPrivate::updateLabel()
{
    Q_Q(QLabel);
    valid_hints = false;

    if (isTextLabel) {
        QSizePolicy policy = q->sizePolicy();
        const bool wrap = align & Qt::TextWordWrap;
        policy.setHeightForWidth(wrap);
        if (policy != q->sizePolicy())  // ### should be replaced by WA_WState_OwnSizePolicy idiom
            q->setSizePolicy(policy);
        textLayoutDirty = true;
    }
    q->updateGeometry();
    q->update(q->contentsRect());
}

#ifndef QT_NO_SHORTCUT
/*!
    Sets this label's buddy to \a buddy.

    When the user presses the shortcut key indicated by this label,
    the keyboard focus is transferred to the label's buddy widget.

    The buddy mechanism is only available for QLabels that contain
    text in which one character is prefixed with an ampersand, '&'.
    This character is set as the shortcut key. See the \l
    QKeySequence::mnemonic() documentation for details (to display an
    actual ampersand, use '&&').

    In a dialog, you might create two data entry widgets and a label
    for each, and set up the geometry layout so each label is just to
    the left of its data entry widget (its "buddy"), for example:
    \snippet code/src_gui_widgets_qlabel.cpp 2

    With the code above, the focus jumps to the Name field when the
    user presses Alt+N, and to the Phone field when the user presses
    Alt+P.

    To unset a previously set buddy, call this function with \a buddy
    set to nullptr.

    \sa buddy(), setText(), QShortcut, setAlignment()
*/

void QLabel::setBuddy(QWidget *buddy)
{
    Q_D(QLabel);

    if (d->buddy)
        disconnect(d->buddy, SIGNAL(destroyed()), this, SLOT(_q_buddyDeleted()));

    d->buddy = buddy;

    if (buddy)
        connect(buddy, SIGNAL(destroyed()), this, SLOT(_q_buddyDeleted()));

    if (d->isTextLabel) {
        if (d->shortcutId)
            releaseShortcut(d->shortcutId);
        d->shortcutId = 0;
        d->textDirty = true;
        if (buddy)
            d->updateShortcut(); // grab new shortcut
        d->updateLabel();
    }
}


/*!
    Returns this label's buddy, or nullptr if no buddy is currently set.

    \sa setBuddy()
*/

QWidget * QLabel::buddy() const
{
    Q_D(const QLabel);
    return d->buddy;
}

void QLabelPrivate::updateShortcut()
{
    Q_Q(QLabel);
    Q_ASSERT(shortcutId == 0);
    // Introduce an extra boolean to indicate the presence of a shortcut in the
    // text. We cannot use the shortcutId itself because on the mac mnemonics are
    // off by default, so QKeySequence::mnemonic always returns an empty sequence.
    // But then we do want to hide the ampersands, so we can't use shortcutId.
    hasShortcut = false;

    if (!text.contains(QLatin1Char('&')))
        return;
    hasShortcut = true;
    shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
}


void QLabelPrivate::_q_buddyDeleted()
{
    Q_Q(QLabel);
    q->setBuddy(nullptr);
}

#endif // QT_NO_SHORTCUT

#if QT_CONFIG(movie)
void QLabelPrivate::_q_movieUpdated(const QRect& rect)
{
    Q_Q(QLabel);
    if (movie && movie->isValid()) {
        QRect r;
        if (scaledcontents) {
            QRect cr = q->contentsRect();
            QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size());
            if (pixmapRect.isEmpty())
                return;
            r.setRect(cr.left(), cr.top(),
                      (rect.width() * cr.width()) / pixmapRect.width(),
                      (rect.height() * cr.height()) / pixmapRect.height());
        } else {
            r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap());
            r.translate(rect.x(), rect.y());
            r.setWidth(qMin(r.width(), rect.width()));
            r.setHeight(qMin(r.height(), rect.height()));
        }
        q->update(r);
    }
}

void QLabelPrivate::_q_movieResized(const QSize& size)
{
    Q_Q(QLabel);
    q->update(); //we need to refresh the whole background in case the new size is smaller
    valid_hints = false;
    _q_movieUpdated(QRect(QPoint(0,0), size));
    q->updateGeometry();
}

/*!
    Sets the label contents to \a movie. Any previous content is
    cleared. The label does NOT take ownership of the movie.

    The buddy shortcut, if any, is disabled.

    \sa movie(), setBuddy()
*/

void QLabel::setMovie(QMovie *movie)
{
    Q_D(QLabel);
    d->clearContents();

    if (!movie)
        return;

    d->movie = movie;
    connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize)));
    connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect)));

    // Assume that if the movie is running,
    // resize/update signals will come soon enough
    if (movie->state() != QMovie::Running)
        d->updateLabel();
}

#endif // QT_CONFIG(movie)

/*!
  \internal

  Clears any contents, without updating/repainting the label.
*/

void QLabelPrivate::clearContents()
{
    delete control;
    control = nullptr;
    isTextLabel = false;
    hasShortcut = false;

#ifndef QT_NO_PICTURE
    delete picture;
    picture = nullptr;
#endif
    delete scaledpixmap;
    scaledpixmap = nullptr;
    delete cachedimage;
    cachedimage = nullptr;
    delete pixmap;
    pixmap = nullptr;

    text.clear();
    Q_Q(QLabel);
#ifndef QT_NO_SHORTCUT
    if (shortcutId)
        q->releaseShortcut(shortcutId);
    shortcutId = 0;
#endif
#if QT_CONFIG(movie)
    if (movie) {
        QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize)));
        QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect)));
    }
    movie = nullptr;
#endif
#ifndef QT_NO_CURSOR
    if (onAnchor) {
        if (validCursor)
            q->setCursor(cursor);
        else
            q->unsetCursor();
    }
    validCursor = false;
    onAnchor = false;
#endif
}


#if QT_CONFIG(movie)

/*!
    Returns a pointer to the label's movie, or nullptr if no movie has been
    set.

    \sa setMovie()
*/

QMovie *QLabel::movie() const
{
    Q_D(const QLabel);
    return d->movie;
}

#endif  // QT_CONFIG(movie)

/*!
    \property QLabel::textFormat
    \brief the label's text format

    See the Qt::TextFormat enum for an explanation of the possible
    options.

    The default format is Qt::AutoText.

    \sa text()
*/

Qt::TextFormat QLabel::textFormat() const
{
    Q_D(const QLabel);
    return d->textformat;
}

void QLabel::setTextFormat(Qt::TextFormat format)
{
    Q_D(QLabel);
    if (format != d->textformat) {
        d->textformat = format;
        QString t = d->text;
        if (!t.isNull()) {
            d->text.clear();
            setText(t);
        }
    }
}

/*!
    \since 6.1

    Returns the resource provider for rich text of this label.
*/
QTextDocument::ResourceProvider QLabel::resourceProvider() const
{
    Q_D(const QLabel);
    return d->control ? d->control->document()->resourceProvider() : d->resourceProvider;
}

/*!
    \since 6.1

    Sets the \a provider of resources for rich text of this label.

    \note The label \e{does not} take ownership of the \a provider.
*/
void QLabel::setResourceProvider(const QTextDocument::ResourceProvider &provider)
{
    Q_D(QLabel);
    d->resourceProvider = provider;
    if (d->control != nullptr)
        d->control->document()->setResourceProvider(provider);
}

/*!
  \reimp
*/
void QLabel::changeEvent(QEvent *ev)
{
    Q_D(QLabel);
    if (ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
        if (d->isTextLabel) {
            if (d->control)
                d->control->document()->setDefaultFont(font());
            d->updateLabel();
        }
    } else if (ev->type() == QEvent::PaletteChange && d->control) {
        d->control->setPalette(palette());
    } else if (ev->type() == QEvent::ContentsRectChange) {
        d->updateLabel();
    }
    QFrame::changeEvent(ev);
}

/*!
    \property QLabel::scaledContents
    \brief whether the label will scale its contents to fill all
    available space.

    When enabled and the label shows a pixmap, it will scale the
    pixmap to fill the available space.

    This property's default is false.
*/
bool QLabel::hasScaledContents() const
{
    Q_D(const QLabel);
    return d->scaledcontents;
}

void QLabel::setScaledContents(bool enable)
{
    Q_D(QLabel);
    if ((bool)d->scaledcontents == enable)
        return;
    d->scaledcontents = enable;
    if (!enable) {
        delete d->scaledpixmap;
        d->scaledpixmap = nullptr;
        delete d->cachedimage;
        d->cachedimage = nullptr;
    }
    update(contentsRect());
}

Qt::LayoutDirection QLabelPrivate::textDirection() const
{
    if (control) {
        QTextOption opt = control->document()->defaultTextOption();
        return opt.textDirection();
    }

    return text.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
}


// Returns the rect that is available for us to draw the document
QRect QLabelPrivate::documentRect() const
{
    Q_Q(const QLabel);
    Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!");
    QRect cr = q->contentsRect();
    cr.adjust(margin, margin, -margin, -margin);
    const int align = QStyle::visualAlignment(isTextLabel ? textDirection()
                                                          : q->layoutDirection(), QFlag(this->align));
    int m = indent;
    if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
        m = q->fontMetrics().horizontalAdvance(QLatin1Char('x')) / 2 - margin;
    if (m > 0) {
        if (align & Qt::AlignLeft)
            cr.setLeft(cr.left() + m);
        if (align & Qt::AlignRight)
            cr.setRight(cr.right() - m);
        if (align & Qt::AlignTop)
            cr.setTop(cr.top() + m);
        if (align & Qt::AlignBottom)
            cr.setBottom(cr.bottom() - m);
    }
    return cr;
}

void QLabelPrivate::ensureTextPopulated() const
{
    if (!textDirty)
        return;
    if (control) {
        QTextDocument *doc = control->document();
        if (textDirty) {
            if (effectiveTextFormat == Qt::PlainText) {
                doc->setPlainText(text);
#if QT_CONFIG(texthtmlparser)
            } else if (effectiveTextFormat == Qt::RichText) {
                doc->setHtml(text);
#endif
#if QT_CONFIG(textmarkdownreader)
            } else if (effectiveTextFormat == Qt::MarkdownText) {
                doc->setMarkdown(text);
#endif
            } else {
                doc->setPlainText(text);
            }
            doc->setUndoRedoEnabled(false);

#ifndef QT_NO_SHORTCUT
            if (hasShortcut) {
                // Underline the first character that follows an ampersand (and remove the others ampersands)
                int from = 0;
                bool found = false;
                QTextCursor cursor;
                while (!(cursor = control->document()->find((QLatin1String("&")), from)).isNull()) {
                    cursor.deleteChar(); // remove the ampersand
                    cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
                    from = cursor.position();
                    if (!found && cursor.selectedText() != QLatin1String("&")) { //not a second &
                        found = true;
                        shortcutCursor = cursor;
                    }
                }
            }
#endif
        }
    }
    textDirty = false;
}

void QLabelPrivate::ensureTextLayouted() const
{
    if (!textLayoutDirty)
        return;
    ensureTextPopulated();
    if (control) {
        QTextDocument *doc = control->document();
        QTextOption opt = doc->defaultTextOption();

        opt.setAlignment(QFlag(this->align));

        if (this->align & Qt::TextWordWrap)
            opt.setWrapMode(QTextOption::WordWrap);
        else
            opt.setWrapMode(QTextOption::ManualWrap);

        doc->setDefaultTextOption(opt);

        QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        doc->rootFrame()->setFrameFormat(fmt);
        doc->setTextWidth(documentRect().width());
    }
    textLayoutDirty = false;
}

void QLabelPrivate::ensureTextControl() const
{
    Q_Q(const QLabel);
    if (!isTextLabel)
        return;
    if (!control) {
        control = new QWidgetTextControl(const_cast<QLabel *>(q));
        control->document()->setUndoRedoEnabled(false);
        control->document()->setDefaultFont(q->font());
        if (resourceProvider != nullptr)
            control->document()->setResourceProvider(resourceProvider);
        control->setTextInteractionFlags(textInteractionFlags);
        control->setOpenExternalLinks(openExternalLinks);
        control->setPalette(q->palette());
        control->setFocus(q->hasFocus());
        QObject::connect(control, SIGNAL(updateRequest(QRectF)),
                         q, SLOT(update()));
        QObject::connect(control, SIGNAL(linkHovered(QString)),
                         q, SLOT(_q_linkHovered(QString)));
        QObject::connect(control, SIGNAL(linkActivated(QString)),
                         q, SIGNAL(linkActivated(QString)));
        textLayoutDirty = true;
        textDirty = true;
    }
}

void QLabelPrivate::sendControlEvent(QEvent *e)
{
    Q_Q(QLabel);
    if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) {
        e->ignore();
        return;
    }
    control->processEvent(e, -layoutRect().topLeft(), q);
}

void QLabelPrivate::_q_linkHovered(const QString &anchor)
{
    Q_Q(QLabel);
#ifndef QT_NO_CURSOR
    if (anchor.isEmpty()) { // restore cursor
        if (validCursor)
            q->setCursor(cursor);
        else
            q->unsetCursor();
        onAnchor = false;
    } else if (!onAnchor) {
        validCursor = q->testAttribute(Qt::WA_SetCursor);
        if (validCursor) {
            cursor = q->cursor();
        }
        q->setCursor(Qt::PointingHandCursor);
        onAnchor = true;
    }
#endif
    emit q->linkHovered(anchor);
}

// Return the layout rect - this is the rect that is given to the layout painting code
// This may be different from the document rect since vertical alignment is not
// done by the text layout code
QRectF QLabelPrivate::layoutRect() const
{
    QRectF cr = documentRect();
    if (!control)
        return cr;
    ensureTextLayouted();
    // Calculate y position manually
    qreal rh = control->document()->documentLayout()->documentSize().height();
    qreal yo = 0;
    if (align & Qt::AlignVCenter)
        yo = qMax((cr.height()-rh)/2, qreal(0));
    else if (align & Qt::AlignBottom)
        yo = qMax(cr.height()-rh, qreal(0));
    return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height());
}

// Returns the point in the document rect adjusted with p
QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
{
    QRect lr = layoutRect().toRect();
    return p - lr.topLeft();
}

#ifndef QT_NO_CONTEXTMENU
QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
{
    if (!control || effectiveTextFormat == Qt::PlainText)
        return nullptr;

    const QPoint p = layoutPoint(pos);
    QString linkToCopy = control->document()->documentLayout()->anchorAt(p);

    if (linkToCopy.isEmpty())
        return nullptr;

    return control->createStandardContextMenu(p, q_func());
}
#endif

/*!
    \fn void QLabel::linkHovered(const QString &link)
    \since 4.2

    This signal is emitted when the user hovers over a link. The URL
    referred to by the anchor is passed in \a link.

    \sa linkActivated()
*/


/*!
    \fn void QLabel::linkActivated(const QString &link)
    \since 4.2

    This signal is emitted when the user clicks a link. The URL
    referred to by the anchor is passed in \a link.

    \sa linkHovered()
*/

QT_END_NAMESPACE

#include "moc_qlabel.cpp"