77
88#include < QIconEngine>
99#include < QPainter>
10+ #include < QPixmapCache>
1011
1112using namespace OCC ::Resources;
1213
@@ -25,7 +26,6 @@ class FontIconEngine : public QIconEngine
2526 void paint (QPainter *painter, const QRect &rect, QIcon::Mode, QIcon::State) override
2627 {
2728 painter->save ();
28- painter->fillRect (rect, Qt::transparent);
2929 painter->setRenderHint (QPainter::Antialiasing);
3030
3131 auto pen = painter->pen ();
@@ -50,24 +50,46 @@ class FontIconEngine : public QIconEngine
5050 font.setPixelSize (rect.height () / 2.0 );
5151 break ;
5252 }
53- painter->setFont (font);
5453
55- painter->drawText (rect, Qt::AlignHCenter | Qt::AlignVCenter, _glyph);
54+ // inspired by https://github.com/gamecreature/QtAwesome/
55+ const auto flags = Qt::AlignHCenter | Qt::AlignVCenter;
56+ QFontMetricsF metrics (font);
57+ QRectF boundingRect = metrics.boundingRect (rect, flags, _glyph);
58+ if (boundingRect.width () > rect.width ()) {
59+ auto drawSize =
60+ static_cast <int >(font.pixelSize () * qMin (rect.width () * 0.95 / boundingRect.width (), metrics.height () * 0.95 / boundingRect.height ()));
61+ font.setPixelSize (drawSize);
62+ }
63+
64+ painter->setFont (font);
65+ painter->drawText (rect, flags, _glyph);
5666 painter->restore ();
5767 }
5868
5969 QPixmap pixmap (const QSize &size, QIcon::Mode mode, QIcon::State state) override
6070 {
61- QPixmap pixmap (size);
62- pixmap.fill (Qt::transparent); // we need transparency
71+ QPixmap pixmap;
72+ const QString key = pixmapKey (size, mode, state);
73+ if (QPixmapCache::find (key, &pixmap)) {
74+ return pixmap;
75+ }
76+
77+ pixmap = QPixmap (size);
78+ pixmap.fill (Qt::transparent);
6379 QPainter painter (&pixmap);
6480 paint (&painter, {{0 , 0 }, size}, mode, state);
6581 painter.end ();
82+ QPixmapCache::insert (key, pixmap);
6683 return pixmap;
6784 }
6885
6986 QIconEngine *clone () const override { return new FontIconEngine (this ->_family , this ->_glyph , this ->_size ); }
7087
88+ QString pixmapKey (const QSize &size, QIcon::Mode mode, QIcon::State state)
89+ {
90+ return QStringLiteral (" FontIcon:%1" ).arg (QString::number (qHashMulti (0 , _family, _glyph, _size, size, mode, state), 16 ));
91+ }
92+
7193 const FontIcon::FontFamily _family;
7294 const QChar _glyph;
7395 const FontIcon::Size _size;
0 commit comments