diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index 016cd1a9873..82b7060d6f0 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -439,6 +439,7 @@ void QPMCache::clear() killTimer(theid); theid = 0; } + cacheKeys.clear(); } QPixmapCache::KeyData* QPMCache::getKeyData(QPixmapCache::Key *key) diff --git a/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp b/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp index d4c39a2130b..de785fd160d 100644 --- a/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp +++ b/tests/auto/gui/image/qpixmapcache/tst_qpixmapcache.cpp @@ -13,6 +13,8 @@ Q_AUTOTEST_EXPORT int qt_qpixmapcache_qpixmapcache_total_used(); Q_AUTOTEST_EXPORT int q_QPixmapCache_keyHashSize(); QT_END_NAMESPACE +using namespace Qt::StringLiterals; + class tst_QPixmapCache : public QObject { Q_OBJECT @@ -34,6 +36,7 @@ private slots: void clear(); void pixmapKey(); void noLeak(); + void clearDoesNotLeakStringKeys(); void strictCacheLimit(); void noCrashOnLargeInsert(); }; @@ -478,6 +481,39 @@ void tst_QPixmapCache::noLeak() QCOMPARE(oldSize, newSize); } +void tst_QPixmapCache::clearDoesNotLeakStringKeys() +{ + QPixmapCache::setCacheLimit(20); // 20KiB + // + // GIVEN: a QPixmap with QString key `key` in QPixmapCache + // + QString key; + { + QPixmap pm(64, 64); + QCOMPARE_LT(pm.width() * pm.height() * std::ceil(pm.depth() / 8.0), + QPixmapCache::cacheLimit() * 1024); + pm.fill(Qt::transparent); + key = u"theKey"_s.repeated(20); // avoid eventual QString SSO + QVERIFY(key.isDetached()); + QPixmapCache::insert(key, pm); + } + QVERIFY(!key.isDetached()); // was saved inside QPixmapCache + + // + // WHEN: clearing the cache: + // + QPixmapCache::clear(); + + // + // THEN: `key` is no longer referenced by QPixmapCache: + // + QVERIFY(key.isDetached()); + // verify that the pixmap is really gone from the cache + // (do it after the key check, because QPixmapCache cleans up `key` on a failed lookup) + QPixmap r; + QVERIFY(!QPixmapCache::find(key, &r)); +} + void tst_QPixmapCache::strictCacheLimit() {