像 QTextEdit 这样的 QWidget 自动将其高度包装到其内容中? [英] A QWidget like QTextEdit that wraps its height automatically to its contents?
问题描述
我正在创建一个带有一些 QTextEdit 小部件的表单.
I am creating a form with some QTextEdit widgets.
QTextEdit 的默认高度超过一行文本,当内容的高度超过 QTextEdit 的高度时,它会创建一个滚动条来滚动内容.
The default height of the QTextEdit exceeds a single line of text and as the contents' height exceeds the QTextEdit's height, it creates a scroll-bar to scroll the content.
我想覆盖此行为以创建一个 QTextEdit,它宁愿将其高度包装到其内容中.这意味着默认高度将为一行,并且在换行或输入新行时,QTextEdit 将自动增加其高度.每当内容高度超过 QTextEdit 的高度时,后者不应创建滚动条而只是增加高度.
I would like to override this behaviour to create a QTextEdit that would rather wrap its height to its contents. This means that the default height would be one line and that on wrapping or entering a new line, the QTextEdit would increase its height automatically. Whenever the contents height exceeds the QTextEdit's height, the latter should not create a scroll bar but simply increase in height.
我该怎么做?谢谢.
推荐答案
这几乎就像我前几天回答的一个关于使 QTextEdit 调整其高度以响应内容更改的问题:PySide Qt:TextEdit Widget 的自动垂直增长
This is almost exactly like a question I answer the other day about making a QTextEdit adjust its height in reponse to content changes: PySide Qt: Auto vertical growth for TextEdit Widget
我正在回答而不是标记重复,因为我怀疑您可能想要对此进行更改.如果您希望我扩展此答案,请告诉我:
I am answering instead of marking a duplicate as I suspect its possible you want a variation on this. Let me know if you want me to expand this answer:
另一个问题有多个部分.以下是生长高度小部件的摘录:
The other question had multiple parts. Here is the excerpt of the growing height widget:
class Window(QtGui.QDialog):
def __init__(self):
super(Window, self).__init__()
self.resize(600,400)
self.mainLayout = QtGui.QVBoxLayout(self)
self.mainLayout.setMargin(10)
self.scroll = QtGui.QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.mainLayout.addWidget(self.scroll)
scrollContents = QtGui.QWidget()
self.scroll.setWidget(scrollContents)
self.textLayout = QtGui.QVBoxLayout(scrollContents)
self.textLayout.setMargin(10)
for _ in xrange(5):
text = GrowingTextEdit()
text.setMinimumHeight(50)
self.textLayout.addWidget(text)
class GrowingTextEdit(QtGui.QTextEdit):
def __init__(self, *args, **kwargs):
super(GrowingTextEdit, self).__init__(*args, **kwargs)
self.document().contentsChanged.connect(self.sizeChange)
self.heightMin = 0
self.heightMax = 65000
def sizeChange(self):
docHeight = self.document().size().height()
if self.heightMin <= docHeight <= self.heightMax:
self.setMinimumHeight(docHeight)
这篇关于像 QTextEdit 这样的 QWidget 自动将其高度包装到其内容中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!