diff --git a/src/pyqt_reactive/widgets/virtual_rows.py b/src/pyqt_reactive/widgets/virtual_rows.py index 75267fd..10cdae5 100644 --- a/src/pyqt_reactive/widgets/virtual_rows.py +++ b/src/pyqt_reactive/widgets/virtual_rows.py @@ -218,6 +218,9 @@ def __init__(self, parent: QWidget | None = None) -> None: self._pending: set[Hashable] = set() self._documents: OrderedDict[tuple[Hashable, int], QTextDocument] = OrderedDict() self._size_hints: dict[tuple[Hashable, int], QSize] = {} + # A laid-out row wider than its layout width (unwrapped content): how wide, by the + # same key the height is kept under. + self._extents: dict[tuple[Hashable, int], int] = {} # The widths each key has a document or height cached at, so an arrival drops them. self._cached_widths: dict[Hashable, set[int]] = {} # A batch of finished preparations lays the view out once, in the next frame. @@ -302,14 +305,39 @@ def final_document(self, index: QModelIndex, font: QFont, width: int) -> QTextDo formatting = self.formatting(index, font, width) if not formatting.final: return None + return self.laid_out(key[0], font, width, formatting) + + def laid_out( + self, key: Hashable, font: QFont, width: int, formatting: RowFormatting + ) -> QTextDocument: + """The document of a row's final formatting at `width`, laid out once and kept: the + measurement that sizes the row and the paint that draws it read the same document. + A measurement used to lay out a document of its own and drop it, so a row a member + measured before drawing it (a pager sizing a page it is about to publish) was laid + out twice.""" + cache_key = (key, width) + document = self._documents.get(cache_key) + if document is not None: + self._documents.move_to_end(cache_key) + return document document = self.new_document(font, width) formatting.fill(document) - self._documents[key] = document - self._cached_widths.setdefault(key[0], set()).add(width) + self._documents[cache_key] = document + self._cached_widths.setdefault(key, set()).add(width) + extent = max(math.ceil(document.idealWidth()), math.ceil(document.size().width())) + if extent > width: + self._extents[cache_key] = extent if len(self._documents) > self.MAX_DOCUMENTS: self._documents.popitem(last=False) return document + def row_extent(self, key: Hashable, width: int) -> int: + """How wide the row's content is when laid out at `width`: `width` itself where it + wraps, more where it holds content that does not (a `pre` block). Recorded when the + row is laid out and kept with its height, so asking it lays nothing out; a row not + laid out yet answers `width`.""" + return self._extents.get((key, width), width) + def row_document(self, index: QModelIndex, font: QFont, width: int) -> QTextDocument: """The row's document; a pending row's is its plain text, laid out for this one ask (a tap over it) and not kept.""" @@ -343,10 +371,8 @@ def measured_height(self, key: Hashable, font: QFont, width: int, formatting: Ro formatting = formatting.resolved() if not formatting.final: return formatting.estimated_height(font, self.text_width(width)) + self.ROW_PADDING - document = self.new_document(font, width) - formatting.fill(document) + document = self.laid_out(key, font, width, formatting) size = self._size_hints[cache_key] = QSize(width, int(document.size().height()) + self.ROW_PADDING) - self._cached_widths.setdefault(key, set()).add(width) return size.height() def _rows_prepared(self, batch: list[tuple[Hashable, RowFormatting]]) -> None: @@ -373,6 +399,7 @@ def _row_prepared(self, key: Hashable, prepared: RowFormatting) -> None: for width in self._cached_widths.pop(key, ()): self._documents.pop((key, width), None) self._size_hints.pop((key, width), None) + self._extents.pop((key, width), None) if self._moves_rows(key, prepared, awaited): self._arrivals_moved_rows = True if not self._viewport_update_timer.isActive(): @@ -430,6 +457,7 @@ def width_changed(self) -> None: """Documents and heights hold one width; prepared formatting may hold any.""" self.release_documents() self._size_hints.clear() + self._extents.clear() self._cached_widths.clear() self.forget_row_sizes() diff --git a/tests/test_virtual_rows.py b/tests/test_virtual_rows.py index dd44482..7c9075f 100644 --- a/tests/test_virtual_rows.py +++ b/tests/test_virtual_rows.py @@ -122,6 +122,64 @@ def test_measured_height_is_kept_only_for_final_formatting(qtbot) -> None: delegate.cleanup() +@dataclass(frozen=True) +class UnwrappedRow(RowFormatting): + text: str + + def fill(self, document: QTextDocument) -> None: + document.setHtml(f"
{self.text}")
+
+
+def test_a_row_measured_before_it_is_drawn_is_laid_out_once(qtbot) -> None:
+ """A member that sizes a row before drawing it (a pager measuring the page it is about to
+ publish) and the paint that follows read one document: the measurement keeps what it
+ laid out."""
+ model = QStringListModel(["row 0"])
+ view = VirtualRowView(BoldRows())
+ qtbot.addWidget(view)
+ view.setModel(model)
+ delegate, font, index = view.rows, QFont(), model.index(0, 0)
+ key = delegate.preparation_key(index, font, 300)
+ laid_out = []
+ new_document = delegate.new_document
+ def counted(*arguments):
+ laid_out.append(arguments)
+ return new_document(*arguments)
+ delegate.new_document = counted
+ try:
+ delegate._row_prepared(key, BoldRow("row 0"))
+ height = delegate.measured_height(key, font, 300, BoldRow("row 0"))
+ document = delegate.final_document(index, font, 300)
+ assert len(laid_out) == 1
+ assert int(document.size().height()) + delegate.ROW_PADDING == height
+ finally:
+ delegate.cleanup()
+
+
+def test_a_rows_extent_is_recorded_when_it_is_laid_out(qtbot) -> None:
+ """Content that does not wrap is wider than the width it was laid out at; the delegate
+ keeps that with the height, so asking it lays nothing out, and it outlives the documents."""
+ delegate = BoldRows()
+ qtbot.addWidget(VirtualRowView(delegate))
+ font = QFont()
+ wrapped, unwrapped = ("wrapped", font.family()), ("unwrapped", font.family())
+ try:
+ # Not laid out yet: the layout width.
+ assert delegate.row_extent(unwrapped, 200) == 200
+ delegate.measured_height(wrapped, font, 200, BoldRow("a short row"))
+ delegate.measured_height(unwrapped, font, 200, UnwrappedRow("x" * 200))
+ assert delegate.row_extent(wrapped, 200) == 200
+ extent = delegate.row_extent(unwrapped, 200)
+ assert extent > 200
+ delegate.release_documents()
+ assert delegate.row_extent(unwrapped, 200) == extent
+ # New formatting under the key drops what was laid out from the old.
+ delegate._row_prepared(unwrapped, BoldRow("now it wraps"))
+ assert delegate.row_extent(unwrapped, 200) == 200
+ finally:
+ delegate.cleanup()
+
+
def test_a_page_of_rows_arrives_as_one_batch(qtbot) -> None:
"""Rows queued together are worked out by one drain of the pool's queue and reach the
GUI thread together, so the view lays them out once rather than once per row."""