From 68032fc59ae4c8a2cb372e5781a440d7cdaefa6e Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sat, 12 Apr 2025 07:38:33 +0530 Subject: [PATCH] Cache heightForWIdth calculation as recommended by Qt docs --- src/calibre/gui2/widgets2.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/calibre/gui2/widgets2.py b/src/calibre/gui2/widgets2.py index b2f2e881bd..5457a13a69 100644 --- a/src/calibre/gui2/widgets2.py +++ b/src/calibre/gui2/widgets2.py @@ -408,10 +408,22 @@ class FlowLayout(QLayout): # {{{ def __init__(self, parent=None): QLayout.__init__(self, parent) self.items = [] + self.height_for_width_cache = {} + + def clear_caches(self): + self.height_for_width_cache.clear() def addItem(self, item): + self.clear_caches() self.items.append(item) + def isEmpty(self): + return not bool(self.items) + + def invalidate(self): + self.clear_caches() + super().invalidate() + def itemAt(self, idx): try: return self.items[idx] @@ -432,7 +444,9 @@ class FlowLayout(QLayout): # {{{ return True def heightForWidth(self, width): - return self.do_layout(QRect(0, 0, width, 0), apply_geometry=False) + if (ans := self.height_for_width_cache.get(width)) is None: + ans = self.height_for_width_cache[width] = self.do_layout(QRect(0, 0, width, 0), apply_geometry=False) + return ans def setGeometry(self, rect): QLayout.setGeometry(self, rect)