I’m trying to create a custom QTextEdit
widget in PyQt5 that automatically expands and contracts based on its content. The widget should grow in height as the user types new lines and shrink when lines are removed. I have some code but when the TextEdit is resized, the window size remains constant so the widget above the TextEdit, which is supposed to have a dynamic size, increases in size. My code for the CustomTextEdit is as follows:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class CustomTextEdit(QTextEdit):
def __init__(self, max_lines=5, parent=None):
super().__init__(parent)
self.max_lines = max_lines
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
self.document().contentsChanged.connect(self.update_height)
self.setFixedHeight(self.fontMetrics().height())
def update_height(self):
document_height = self.document().size().height()
line_height = self.fontMetrics().lineSpacing()
text_layout = self.document().documentLayout()
block = self.document().begin()
num_lines = 0
while block.isValid():
layout = block.layout()
num_lines += layout.lineCount()
block = block.next()
desired_height = document_height + self.contentsMargins().top() + self.contentsMargins().bottom()
if num_lines > self.max_lines:
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
else:
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setFixedHeight(int(desired_height))
self.scroll_to_bottom()
def scroll_to_bottom(self):
scrollbar = self.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
I’d appreciate it if someone could help, thanks!
Attempt/Goal/Expectation: I tried to make the TextEdit resize as the number of lines increase.
Problem: The other widgets are being resized / The window is not being resized.
ExUltra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.