-
Notifications
You must be signed in to change notification settings - Fork 1k
/
qicon.cpp
1586 lines (1314 loc) · 46.8 KB
/
qicon.cpp
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
// Copyright (C) 2020 The Qt Company Ltd.
// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qicon.h"
#include "qicon_p.h"
#include "qiconengine.h"
#include "qiconengineplugin.h"
#include "qimagereader.h"
#include "private/qfactoryloader_p.h"
#include "private/qiconloader_p.h"
#include "qpainter.h"
#include "qfileinfo.h"
#if QT_CONFIG(mimetype)
#include <qmimedatabase.h>
#include <qmimetype.h>
#endif
#include "qpixmapcache.h"
#include "qvariant.h"
#include "qcache.h"
#include "qdebug.h"
#include "qdir.h"
#include "qpalette.h"
#include "qmath.h"
#include "private/qhexstring_p.h"
#include "private/qguiapplication_p.h"
#include "qpa/qplatformtheme.h"
#ifndef QT_NO_ICON
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
/*!
\enum QIcon::Mode
This enum type describes the mode for which a pixmap is intended
to be used. The currently defined modes are:
\value Normal
Display the pixmap when the user is
not interacting with the icon, but the
functionality represented by the icon is available.
\value Disabled
Display the pixmap when the
functionality represented by the icon is not available.
\value Active
Display the pixmap when the
functionality represented by the icon is available and
the user is interacting with the icon, for example, moving the
mouse over it or clicking it.
\value Selected
Display the pixmap when the item represented by the icon is
selected.
*/
/*!
\enum QIcon::State
This enum describes the state for which a pixmap is intended to be
used. The \e state can be:
\value Off Display the pixmap when the widget is in an "off" state
\value On Display the pixmap when the widget is in an "on" state
*/
static int nextSerialNumCounter()
{
Q_CONSTINIT static QBasicAtomicInt serial = Q_BASIC_ATOMIC_INITIALIZER(0);
return 1 + serial.fetchAndAddRelaxed(1);
}
static void qt_cleanup_icon_cache();
namespace {
struct IconCache : public QCache<QString, QIcon>
{
IconCache()
{
// ### note: won't readd if QApplication is re-created!
qAddPostRoutine(qt_cleanup_icon_cache);
}
};
}
Q_GLOBAL_STATIC(IconCache, qtIconCache)
static void qt_cleanup_icon_cache()
{
qtIconCache()->clear();
}
QIconPrivate::QIconPrivate(QIconEngine *e)
: engine(e), ref(1),
serialNum(nextSerialNumCounter()),
detach_no(0),
is_mask(false)
{
}
void QIconPrivate::clearIconCache()
{
qt_cleanup_icon_cache();
}
/*! \internal
Computes the displayDevicePixelRatio for a pixmap.
If displayDevicePixelRatio is 1.0 the reurned value is 1.0, always.
For a displayDevicePixelRatio of 2.0 the returned value will be between
1.0 and 2.0, depending on requestedSize and actualsize:
* If actualsize < requestedSize : 1.0 (not enough pixels for a normal-dpi pixmap)
* If actualsize == requestedSize * 2.0 : 2.0 (enough pixels for a high-dpi pixmap)
* else : a scaled value between 1.0 and 2.0. (pixel count is between normal-dpi and high-dpi)
*/
qreal QIconPrivate::pixmapDevicePixelRatio(qreal displayDevicePixelRatio, const QSize &requestedSize, const QSize &actualSize)
{
QSize targetSize = requestedSize * displayDevicePixelRatio;
if ((actualSize.width() == targetSize.width() && actualSize.height() <= targetSize.height()) ||
(actualSize.width() <= targetSize.width() && actualSize.height() == targetSize.height())) {
// Correctly scaled for dpr, just having different aspect ratio
return displayDevicePixelRatio;
}
qreal scale = 0.5 * (qreal(actualSize.width()) / qreal(targetSize.width()) +
qreal(actualSize.height() / qreal(targetSize.height())));
return qMax(qreal(1.0), displayDevicePixelRatio *scale);
}
QPixmapIconEngine::QPixmapIconEngine()
{
}
QPixmapIconEngine::QPixmapIconEngine(const QPixmapIconEngine &other)
: QIconEngine(other), pixmaps(other.pixmaps)
{
}
QPixmapIconEngine::~QPixmapIconEngine()
{
}
void QPixmapIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
{
auto paintDevice = painter->device();
qreal dpr = paintDevice ? paintDevice->devicePixelRatio() : qApp->devicePixelRatio();
const QSize pixmapSize = rect.size() * dpr;
QPixmap px = scaledPixmap(pixmapSize, mode, state, dpr);
painter->drawPixmap(rect, px);
}
static inline int area(const QSize &s) { return s.width() * s.height(); }
// Returns the smallest of the two that is still larger than or equal to size.
// Pixmaps at the correct scale are preferred, pixmaps at lower scale are
// used as fallbacks. We assume that the pixmap set is complete, in the sense
// that no 2x pixmap is going to be a better match than a 3x pixmap for the the
// target scale of 3 (It's OK if 3x pixmaps are missing - we'll fall back to
// the 2x pixmaps then.)
static QPixmapIconEngineEntry *bestSizeScaleMatch(const QSize &size, qreal scale, QPixmapIconEngineEntry *pa, QPixmapIconEngineEntry *pb)
{
// scale: we can only differentiate on scale if the scale differs
if (pa->scale != pb->scale) {
// Score the pixmaps: 0 is an exact scale match, positive
// scores have more detail than requested, negative scores
// have less detail than requested.
qreal ascore = pa->scale - scale;
qreal bscore = pb->scale - scale;
// Take the one closest to 0
return (qAbs(ascore) < qAbs(bscore)) ? pa : pb;
}
int s = area(size);
if (pa->size == QSize() && pa->pixmap.isNull()) {
pa->pixmap = QPixmap(pa->fileName);
pa->size = pa->pixmap.size();
}
int a = area(pa->size);
if (pb->size == QSize() && pb->pixmap.isNull()) {
pb->pixmap = QPixmap(pb->fileName);
pb->size = pb->pixmap.size();
}
int b = area(pb->size);
int res = a;
if (qMin(a,b) >= s)
res = qMin(a,b);
else
res = qMax(a,b);
if (res == a)
return pa;
return pb;
}
QPixmapIconEngineEntry *QPixmapIconEngine::tryMatch(const QSize &size, qreal scale, QIcon::Mode mode, QIcon::State state)
{
QPixmapIconEngineEntry *pe = nullptr;
for (int i = 0; i < pixmaps.size(); ++i)
if (pixmaps.at(i).mode == mode && pixmaps.at(i).state == state) {
if (pe)
pe = bestSizeScaleMatch(size, scale, &pixmaps[i], pe);
else
pe = &pixmaps[i];
}
return pe;
}
QPixmapIconEngineEntry *QPixmapIconEngine::bestMatch(const QSize &size, qreal scale, QIcon::Mode mode, QIcon::State state, bool sizeOnly)
{
QPixmapIconEngineEntry *pe = tryMatch(size, scale, mode, state);
while (!pe){
QIcon::State oppositeState = (state == QIcon::On) ? QIcon::Off : QIcon::On;
if (mode == QIcon::Disabled || mode == QIcon::Selected) {
QIcon::Mode oppositeMode = (mode == QIcon::Disabled) ? QIcon::Selected : QIcon::Disabled;
if ((pe = tryMatch(size, scale, QIcon::Normal, state)))
break;
if ((pe = tryMatch(size, scale, QIcon::Active, state)))
break;
if ((pe = tryMatch(size, scale, mode, oppositeState)))
break;
if ((pe = tryMatch(size, scale, QIcon::Normal, oppositeState)))
break;
if ((pe = tryMatch(size, scale, QIcon::Active, oppositeState)))
break;
if ((pe = tryMatch(size, scale, oppositeMode, state)))
break;
if ((pe = tryMatch(size, scale, oppositeMode, oppositeState)))
break;
} else {
QIcon::Mode oppositeMode = (mode == QIcon::Normal) ? QIcon::Active : QIcon::Normal;
if ((pe = tryMatch(size, scale, oppositeMode, state)))
break;
if ((pe = tryMatch(size, scale, mode, oppositeState)))
break;
if ((pe = tryMatch(size, scale, oppositeMode, oppositeState)))
break;
if ((pe = tryMatch(size, scale, QIcon::Disabled, state)))
break;
if ((pe = tryMatch(size, scale, QIcon::Selected, state)))
break;
if ((pe = tryMatch(size, scale, QIcon::Disabled, oppositeState)))
break;
if ((pe = tryMatch(size, scale, QIcon::Selected, oppositeState)))
break;
}
if (!pe)
return pe;
}
if (sizeOnly ? (pe->size.isNull() || !pe->size.isValid()) : pe->pixmap.isNull()) {
pe->pixmap = QPixmap(pe->fileName);
if (!pe->pixmap.isNull())
pe->size = pe->pixmap.size();
}
return pe;
}
QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
return scaledPixmap(size, mode, state, 1.0);
}
QPixmap QPixmapIconEngine::scaledPixmap(const QSize &size, QIcon::Mode mode, QIcon::State state, qreal scale)
{
QPixmap pm;
QPixmapIconEngineEntry *pe = bestMatch(size, scale, mode, state, false);
if (pe)
pm = pe->pixmap;
if (pm.isNull()) {
int idx = pixmaps.size();
while (--idx >= 0) {
if (pe == &pixmaps.at(idx)) {
pixmaps.remove(idx);
break;
}
}
if (pixmaps.isEmpty())
return pm;
else
return pixmap(size, mode, state);
}
QSize actualSize = pm.size();
if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
actualSize.scale(size, Qt::KeepAspectRatio);
QString key = "qt_"_L1
% HexString<quint64>(pm.cacheKey())
% HexString<uint>(pe ? pe->mode : QIcon::Normal)
% HexString<quint64>(QGuiApplication::palette().cacheKey())
% HexString<uint>(actualSize.width())
% HexString<uint>(actualSize.height());
if (mode == QIcon::Active) {
if (QPixmapCache::find(key % HexString<uint>(mode), &pm))
return pm; // horray
if (QPixmapCache::find(key % HexString<uint>(QIcon::Normal), &pm)) {
QPixmap active = pm;
if (QGuiApplication *guiApp = qobject_cast<QGuiApplication *>(qApp))
active = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(guiApp))->applyQIconStyleHelper(QIcon::Active, pm);
if (pm.cacheKey() == active.cacheKey())
return pm;
}
}
if (!QPixmapCache::find(key % HexString<uint>(mode), &pm)) {
if (pm.size() != actualSize)
pm = pm.scaled(actualSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
if (pe->mode != mode && mode != QIcon::Normal) {
QPixmap generated = pm;
if (QGuiApplication *guiApp = qobject_cast<QGuiApplication *>(qApp))
generated = static_cast<QGuiApplicationPrivate*>(QObjectPrivate::get(guiApp))->applyQIconStyleHelper(mode, pm);
if (!generated.isNull())
pm = generated;
}
QPixmapCache::insert(key % HexString<uint>(mode), pm);
}
return pm;
}
QSize QPixmapIconEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state)
{
QSize actualSize;
// The returned actual size is the size in device independent pixels,
// so we limit the search to scale 1 and assume that e.g. @2x versions
// does not proviode extra actual sizes not also provided by the 1x versions.
qreal scale = 1;
if (QPixmapIconEngineEntry *pe = bestMatch(size, scale, mode, state, true))
actualSize = pe->size;
if (actualSize.isNull())
return actualSize;
if (!actualSize.isNull() && (actualSize.width() > size.width() || actualSize.height() > size.height()))
actualSize.scale(size, Qt::KeepAspectRatio);
return actualSize;
}
QList<QSize> QPixmapIconEngine::availableSizes(QIcon::Mode mode, QIcon::State state)
{
QList<QSize> sizes;
for (int i = 0; i < pixmaps.size(); ++i) {
QPixmapIconEngineEntry &pe = pixmaps[i];
if (pe.size == QSize() && pe.pixmap.isNull()) {
pe.pixmap = QPixmap(pe.fileName);
pe.size = pe.pixmap.size();
}
if (pe.mode == mode && pe.state == state && !pe.size.isEmpty())
sizes.push_back(pe.size);
}
return sizes;
}
void QPixmapIconEngine::addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state)
{
if (!pixmap.isNull()) {
QPixmapIconEngineEntry *pe = tryMatch(pixmap.size(), pixmap.devicePixelRatio(), mode, state);
if (pe && pe->size == pixmap.size() && pe->scale == pixmap.devicePixelRatio()) {
pe->pixmap = pixmap;
pe->fileName.clear();
} else {
pixmaps += QPixmapIconEngineEntry(pixmap, mode, state);
}
}
}
// Read out original image depth as set by ICOReader
static inline int origIcoDepth(const QImage &image)
{
const QString s = image.text(QStringLiteral("_q_icoOrigDepth"));
return s.isEmpty() ? 32 : s.toInt();
}
static inline int findBySize(const QList<QImage> &images, const QSize &size)
{
for (int i = 0; i < images.size(); ++i) {
if (images.at(i).size() == size)
return i;
}
return -1;
}
// Convenience class providing a bool read() function.
namespace {
class ImageReader
{
public:
ImageReader(const QString &fileName) : m_reader(fileName), m_atEnd(false) {}
QByteArray format() const { return m_reader.format(); }
bool read(QImage *image)
{
if (m_atEnd)
return false;
*image = m_reader.read();
if (!image->size().isValid()) {
m_atEnd = true;
return false;
}
m_atEnd = !m_reader.jumpToNextImage();
return true;
}
private:
QImageReader m_reader;
bool m_atEnd;
};
} // namespace
void QPixmapIconEngine::addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state)
{
if (fileName.isEmpty())
return;
const QString abs = fileName.startsWith(u':') ? fileName : QFileInfo(fileName).absoluteFilePath();
const bool ignoreSize = !size.isValid();
ImageReader imageReader(abs);
const QByteArray format = imageReader.format();
if (format.isEmpty()) // Device failed to open or unsupported format.
return;
QImage image;
if (format != "ico") {
if (ignoreSize) { // No size specified: Add all images.
while (imageReader.read(&image))
pixmaps += QPixmapIconEngineEntry(abs, image, mode, state);
} else {
// Try to match size. If that fails, add a placeholder with the filename and empty pixmap for the size.
while (imageReader.read(&image) && image.size() != size) {}
pixmaps += image.size() == size ?
QPixmapIconEngineEntry(abs, image, mode, state) : QPixmapIconEngineEntry(abs, size, mode, state);
}
return;
}
// Special case for reading Windows ".ico" files. Historically (QTBUG-39287),
// these files may contain low-resolution images. As this information is lost,
// ICOReader sets the original format as an image text key value. Read all matching
// images into a list trying to find the highest quality per size.
QList<QImage> icoImages;
while (imageReader.read(&image)) {
if (ignoreSize || image.size() == size) {
const int position = findBySize(icoImages, image.size());
if (position >= 0) { // Higher quality available? -> replace.
if (origIcoDepth(image) > origIcoDepth(icoImages.at(position)))
icoImages[position] = image;
} else {
icoImages.append(image);
}
}
}
for (const QImage &i : std::as_const(icoImages))
pixmaps += QPixmapIconEngineEntry(abs, i, mode, state);
if (icoImages.isEmpty() && !ignoreSize) // Add placeholder with the filename and empty pixmap for the size.
pixmaps += QPixmapIconEngineEntry(abs, size, mode, state);
}
bool QPixmapIconEngine::isNull()
{
return pixmaps.isEmpty();
}
QString QPixmapIconEngine::key() const
{
return "QPixmapIconEngine"_L1;
}
QIconEngine *QPixmapIconEngine::clone() const
{
return new QPixmapIconEngine(*this);
}
bool QPixmapIconEngine::read(QDataStream &in)
{
int num_entries;
QPixmap pm;
QString fileName;
QSize sz;
uint mode;
uint state;
in >> num_entries;
for (int i=0; i < num_entries; ++i) {
if (in.atEnd()) {
pixmaps.clear();
return false;
}
in >> pm;
in >> fileName;
in >> sz;
in >> mode;
in >> state;
if (pm.isNull()) {
addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
} else {
QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state));
pe.pixmap = pm;
pixmaps += pe;
}
}
return true;
}
bool QPixmapIconEngine::write(QDataStream &out) const
{
int num_entries = pixmaps.size();
out << num_entries;
for (int i=0; i < num_entries; ++i) {
if (pixmaps.at(i).pixmap.isNull())
out << QPixmap(pixmaps.at(i).fileName);
else
out << pixmaps.at(i).pixmap;
out << pixmaps.at(i).fileName;
out << pixmaps.at(i).size;
out << (uint) pixmaps.at(i).mode;
out << (uint) pixmaps.at(i).state;
}
return true;
}
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, iceLoader,
(QIconEngineFactoryInterface_iid, "/iconengines"_L1, Qt::CaseInsensitive))
QFactoryLoader *qt_iconEngineFactoryLoader()
{
return iceLoader();
}
/*!
\class QIcon
\brief The QIcon class provides scalable icons in different modes
and states.
\ingroup painting
\ingroup shared
\inmodule QtGui
A QIcon can generate smaller, larger, active, and disabled pixmaps
from the set of pixmaps it is given. Such pixmaps are used by Qt
widgets to show an icon representing a particular action.
The simplest use of QIcon is to create one from a QPixmap file or
resource, and then use it, allowing Qt to work out all the required
icon styles and sizes. For example:
\snippet code/src_gui_image_qicon.cpp 0
To undo a QIcon, simply set a null icon in its place:
\snippet code/src_gui_image_qicon.cpp 1
Use the QImageReader::supportedImageFormats() and
QImageWriter::supportedImageFormats() functions to retrieve a
complete list of the supported file formats.
When you retrieve a pixmap using pixmap(QSize, Mode, State), and no
pixmap for this given size, mode and state has been added with
addFile() or addPixmap(), then QIcon will generate one on the
fly. This pixmap generation happens in a QIconEngine. The default
engine scales pixmaps down if required, but never up, and it uses
the current style to calculate a disabled appearance. By using
custom icon engines, you can customize every aspect of generated
icons. With QIconEnginePlugin it is possible to register different
icon engines for different file suffixes, making it possible for
third parties to provide additional icon engines to those included
with Qt.
\note Since Qt 4.2, an icon engine that supports SVG is included.
\section1 Making Classes that Use QIcon
If you write your own widgets that have an option to set a small
pixmap, consider allowing a QIcon to be set for that pixmap. The
Qt class QToolButton is an example of such a widget.
Provide a method to set a QIcon, and when you draw the icon, choose
whichever pixmap is appropriate for the current state of your widget.
For example:
\snippet code/src_gui_image_qicon.cpp 2
You might also make use of the \c Active mode, perhaps making your
widget \c Active when the mouse is over the widget (see \l
QWidget::enterEvent()), while the mouse is pressed pending the
release that will activate the function, or when it is the currently
selected item. If the widget can be toggled, the "On" mode might be
used to draw a different icon.
\image icon.png QIcon
\note QIcon needs a QGuiApplication instance before the icon is created.
\section1 High DPI Icons
There are two ways that QIcon supports \l {High DPI}{high DPI}
icons: via \l addFile() and \l fromTheme().
\l addFile() is useful if you have your own custom directory structure and do
not need to use the \l {Freedesktop Icon Theme Specification}. Icons
created via this approach use Qt's \l {High Resolution Versions of Images}
{"@nx" high DPI syntax}.
Using \l fromTheme() is necessary if you plan on following the Icon Theme
Specification. To make QIcon use the high DPI version of an image, add an
additional entry to the appropriate \c index.theme file:
\badcode
[Icon Theme]
Name=Test
Comment=Test Theme
Directories=32x32/actions,32x32@2/actions
[32x32/actions]
Size=32
Context=Actions
Type=Fixed
# High DPI version of the entry above.
[32x32@2/actions]
Size=32
Scale=2
Type=Fixed
\endcode
Your icon theme directory would then look something like this:
\badcode
├── 32x32
│ └── actions
│ └── appointment-new.png
├── 32x32@2
│ └── actions
│ └── appointment-new.png
└── index.theme
\endcode
*/
/*!
Constructs a null icon.
*/
QIcon::QIcon() noexcept
: d(nullptr)
{
}
/*!
Constructs an icon from a \a pixmap.
*/
QIcon::QIcon(const QPixmap &pixmap)
:d(nullptr)
{
addPixmap(pixmap);
}
/*!
Constructs a copy of \a other. This is very fast.
*/
QIcon::QIcon(const QIcon &other)
:d(other.d)
{
if (d)
d->ref.ref();
}
/*!
\fn QIcon::QIcon(QIcon &&other)
Move-constructs a QIcon instance, making it point to the same object
that \a other was pointing to.
*/
/*!
Constructs an icon from the file with the given \a fileName. The
file will be loaded on demand.
If \a fileName contains a relative path (e.g. the filename only)
the relevant file must be found relative to the runtime working
directory.
The file name can refer to an actual file on disk or to
one of the application's embedded resources. See the
\l{resources.html}{Resource System} overview for details on how to
embed images and other resource files in the application's
executable.
Use the QImageReader::supportedImageFormats() and
QImageWriter::supportedImageFormats() functions to retrieve a
complete list of the supported file formats.
*/
QIcon::QIcon(const QString &fileName)
: d(nullptr)
{
addFile(fileName);
}
/*!
Creates an icon with a specific icon \a engine. The icon takes
ownership of the engine.
*/
QIcon::QIcon(QIconEngine *engine)
:d(new QIconPrivate(engine))
{
}
/*!
Destroys the icon.
*/
QIcon::~QIcon()
{
if (d && !d->ref.deref())
delete d;
}
/*!
Assigns the \a other icon to this icon and returns a reference to
this icon.
*/
QIcon &QIcon::operator=(const QIcon &other)
{
if (other.d)
other.d->ref.ref();
if (d && !d->ref.deref())
delete d;
d = other.d;
return *this;
}
/*!
\fn QIcon &QIcon::operator=(QIcon &&other)
Move-assigns \a other to this QIcon instance.
\since 5.2
*/
/*!
\fn void QIcon::swap(QIcon &other)
\since 4.8
Swaps icon \a other with this icon. This operation is very
fast and never fails.
*/
/*!
Returns the icon as a QVariant.
*/
QIcon::operator QVariant() const
{
return QVariant::fromValue(*this);
}
/*!
Returns a number that identifies the contents of this QIcon
object. Distinct QIcon objects can have the same key if
they refer to the same contents.
\since 4.3
The cacheKey() will change when the icon is altered via
addPixmap() or addFile().
Cache keys are mostly useful in conjunction with caching.
\sa QPixmap::cacheKey()
*/
qint64 QIcon::cacheKey() const
{
if (!d)
return 0;
return (((qint64) d->serialNum) << 32) | ((qint64) (d->detach_no));
}
/*!
Returns a pixmap with the requested \a size, \a mode, and \a
state, generating one if necessary. The pixmap might be smaller than
requested, but never larger, unless the device-pixel ratio of the returned
pixmap is larger than 1.
\sa actualSize(), paint()
*/
QPixmap QIcon::pixmap(const QSize &size, Mode mode, State state) const
{
if (!d)
return QPixmap();
const qreal dpr = -1; // don't know target dpr
return pixmap(size, dpr, mode, state);
}
/*!
\fn QPixmap QIcon::pixmap(int w, int h, Mode mode = Normal, State state = Off) const
\overload
Returns a pixmap of size QSize(\a w, \a h). The pixmap might be smaller than
requested, but never larger, unless the device-pixel ratio of the returned
pixmap is larger than 1.
*/
/*!
\fn QPixmap QIcon::pixmap(int extent, Mode mode = Normal, State state = Off) const
\overload
Returns a pixmap of size QSize(\a extent, \a extent). The pixmap might be smaller
than requested, but never larger, unless the device-pixel ratio of the returned
pixmap is larger than 1.
*/
/*!
\overload
\since 6.0
Returns a pixmap with the requested \a size, \a devicePixelRatio, \a mode, and \a
state, generating one if necessary.
\sa actualSize(), paint()
*/
QPixmap QIcon::pixmap(const QSize &size, qreal devicePixelRatio, Mode mode, State state) const
{
if (!d)
return QPixmap();
// Use the global devicePixelRatio if the caller does not know the target dpr
if (devicePixelRatio == -1)
devicePixelRatio = qApp->devicePixelRatio();
// Handle the simple normal-dpi case
if (!(devicePixelRatio > 1.0)) {
QPixmap pixmap = d->engine->pixmap(size, mode, state);
pixmap.setDevicePixelRatio(1.0);
return pixmap;
}
// Try get a pixmap that is big enough to be displayed at device pixel resolution.
QPixmap pixmap = d->engine->scaledPixmap(size * devicePixelRatio, mode, state, devicePixelRatio);
pixmap.setDevicePixelRatio(d->pixmapDevicePixelRatio(devicePixelRatio, size, pixmap.size()));
return pixmap;
}
#if QT_DEPRECATED_SINCE(6, 0)
/*!
\since 5.1
\deprecated [6.0] Use pixmap(size, devicePixelRatio) instead.
Returns a pixmap with the requested \a window \a size, \a mode, and \a
state, generating one if necessary.
The pixmap can be smaller than the requested size. If \a window is on
a high-dpi display the pixmap can be larger. In that case it will have
a devicePixelRatio larger than 1.
\sa actualSize(), paint()
*/
QPixmap QIcon::pixmap(QWindow *window, const QSize &size, Mode mode, State state) const
{
if (!d)
return QPixmap();
qreal devicePixelRatio = window ? window->devicePixelRatio() : qApp->devicePixelRatio();
return pixmap(size, devicePixelRatio, mode, state);
}
#endif
/*! Returns the actual size of the icon for the requested \a size, \a
mode, and \a state. The result might be smaller than requested, but
never larger. The returned size is in device-independent pixels (This
is relevant for high-dpi pixmaps.)
\sa pixmap(), paint()
*/
QSize QIcon::actualSize(const QSize &size, Mode mode, State state) const
{
if (!d)
return QSize();
const qreal devicePixelRatio = qApp->devicePixelRatio();
// Handle the simple normal-dpi case:
if (!(devicePixelRatio > 1.0))
return d->engine->actualSize(size, mode, state);
const QSize actualSize = d->engine->actualSize(size * devicePixelRatio, mode, state);
return actualSize / d->pixmapDevicePixelRatio(devicePixelRatio, size, actualSize);
}
#if QT_DEPRECATED_SINCE(6, 0)
/*!
\since 5.1
\deprecated [6.0] Use actualSize(size) instead.
Returns the actual size of the icon for the requested \a window \a size, \a
mode, and \a state.
The pixmap can be smaller than the requested size. The returned size
is in device-independent pixels (This is relevant for high-dpi pixmaps.)
\sa actualSize(), pixmap(), paint()
*/
QSize QIcon::actualSize(QWindow *window, const QSize &size, Mode mode, State state) const
{
if (!d)
return QSize();
qreal devicePixelRatio = window ? window->devicePixelRatio() : qApp->devicePixelRatio();
// Handle the simple normal-dpi case:
if (!(devicePixelRatio > 1.0))
return d->engine->actualSize(size, mode, state);
QSize actualSize = d->engine->actualSize(size * devicePixelRatio, mode, state);
return actualSize / d->pixmapDevicePixelRatio(devicePixelRatio, size, actualSize);
}
#endif
/*!
Uses the \a painter to paint the icon with specified \a alignment,
required \a mode, and \a state into the rectangle \a rect.
\sa actualSize(), pixmap()
*/
void QIcon::paint(QPainter *painter, const QRect &rect, Qt::Alignment alignment, Mode mode, State state) const
{
if (!d || !painter)
return;
// Copy of QStyle::alignedRect
const QSize size = d->engine->actualSize(rect.size(), mode, state);
alignment = QGuiApplicationPrivate::visualAlignment(painter->layoutDirection(), alignment);
int x = rect.x();
int y = rect.y();
int w = size.width();
int h = size.height();
if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
y += rect.size().height()/2 - h/2;
else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
y += rect.size().height() - h;
if ((alignment & Qt::AlignRight) == Qt::AlignRight)
x += rect.size().width() - w;
else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
x += rect.size().width()/2 - w/2;
QRect alignedRect(x, y, w, h);
d->engine->paint(painter, alignedRect, mode, state);
}
/*!
\fn void QIcon::paint(QPainter *painter, int x, int y, int w, int h, Qt::Alignment alignment,
Mode mode, State state) const
\overload
Paints the icon into the rectangle QRect(\a x, \a y, \a w, \a h).
*/
/*!
Returns \c true if the icon is empty; otherwise returns \c false.
An icon is empty if it has neither a pixmap nor a filename.
Note: Even a non-null icon might not be able to create valid
pixmaps, eg. if the file does not exist or cannot be read.
*/
bool QIcon::isNull() const
{
return !d || d->engine->isNull();
}
/*!\internal
*/
bool QIcon::isDetached() const
{
return !d || d->ref.loadRelaxed() == 1;
}
/*! \internal
*/
void QIcon::detach()
{
if (d) {
if (d->engine->isNull()) {
if (!d->ref.deref())
delete d;
d = nullptr;
return;
} else if (d->ref.loadRelaxed() != 1) {
QIconPrivate *x = new QIconPrivate(d->engine->clone());
if (!d->ref.deref())