Код: Выделить всё
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())
Попытка/цель/ожидание: я пытался изменить размер TextEdit как число количество строк увеличивается.
Проблема: размер других виджетов изменяется/размер окна не изменяется.
Подробнее здесь: https://stackoverflow.com/questions/786 ... -for-pyqt5