I have a class of textboxs subclassed from QTextEdit, it automatically resizes to its content and it also resizes when the window is resized.
The texts can be very long, and the textboxs automatically line-wrap the texts, so when the horizontal space increases, the textboxs can shrunk in height, because of less wrapped lines.
The problem is when the textboxs shrunk, their bottom border will be missing, they will only have left, top, and right borders unless the window's width shrunk.
Minimal, reproducible example:
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
class Editor(QTextEdit):
def __init__(self):
super().__init__()
self.textChanged.connect(self.autoResize)
def autoResize(self):
self.document().setTextWidth(self.viewport().width())
margins = self.contentsMargins()
height = int(self.document().size().height() + margins.top() + margins.bottom())
self.setFixedHeight(height)
def resizeEvent(self, e: QResizeEvent) -> None:
self.autoResize()
class Window(QWidget):
def __init__(self):
super().__init__()
self.resize(405, 720)
frame = self.frameGeometry()
center = self.screen().availableGeometry().center()
frame.moveCenter(center)
self.move(frame.topLeft())
self.vbox = QVBoxLayout(self)
self.vbox.setAlignment(Qt.AlignmentFlag.AlignTop)
self.textbox = Editor()
self.textbox.setText(
'Symphony No.6 in F, Op.68 \u2014Pastoral\u2014I. Erwachen heiterer Empfindungen bei der Ankunft auf dem Lande\u2014 Allegro ma non troppo'
)
self.vbox.addWidget(self.textbox)
app = QApplication([])
window = Window()
window.show()
app.exec()
When you click the maximize button, the textbox goes from three wrapped lines to one line, and the bottom border will be missing until you restore the window.
I would like to redraw the borders, I have Google searched for 8+ hours and can't find a solution, and I have tried to the add following autoResize
function to no avail:
self.update()
self.viewport().update()
self.repaint()
self.viewport().repaint()
self.setFrameRect(QRect(0, 0, self.width(), height))
How can this be done?