|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2024 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing a QTextBrowser widget that resizes automatically. |
|
8 """ |
|
9 |
|
10 from PyQt6.QtCore import Qt |
|
11 from PyQt6.QtWidgets import QFrame, QSizePolicy, QTextBrowser |
|
12 |
|
13 |
|
14 class AutoResizeTextBrowser(QTextBrowser): |
|
15 """ |
|
16 Class implementing a QTextBrowser widget that resizes automatically. |
|
17 """ |
|
18 |
|
19 def __init__(self, parent=None): |
|
20 """ |
|
21 Constructor |
|
22 |
|
23 @param parent reference to the parent widget (defaults to None) |
|
24 @type QWidget (optional) |
|
25 """ |
|
26 super().__init__(parent=parent) |
|
27 |
|
28 self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) |
|
29 self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) |
|
30 self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) |
|
31 self.setFrameShape(QFrame.Shape.NoFrame) |
|
32 |
|
33 self.textChanged.connect(self.updateGeometry) |
|
34 |
|
35 def resizeEvent(self, evt): |
|
36 """ |
|
37 Protected method to handle resize events. |
|
38 |
|
39 @param evt reference to the resize event |
|
40 @type QResizeEvent |
|
41 """ |
|
42 super().resizeEvent(evt) |
|
43 self.updateGeometry() |
|
44 |
|
45 def updateGeometry(self): |
|
46 """ |
|
47 Public method to update the geometry depending on the current text. |
|
48 """ |
|
49 # Set the text width of the document to match the width of the text browser. |
|
50 self.document().setTextWidth( |
|
51 self.width() - 2 * int(self.document().documentMargin()) |
|
52 ) |
|
53 |
|
54 # Get the document height and set it as the fixed height of the text browser. |
|
55 docHeight = self.document().size().height() |
|
56 self.setFixedHeight(int(docHeight)) |
|
57 |
|
58 # Call the base class updateGeometry() method. |
|
59 super().updateGeometry() |