9

いくつかの QTextEdit ウィジェットでフォームを作成しています。

QTextEdit のデフォルトの高さは 1 行のテキストを超えており、コンテンツの高さが QTextEdit の高さを超えると、コンテンツをスクロールするためのスクロール バーが作成されます。

この動作をオーバーライドして、高さをコンテンツにラップする QTextEdit を作成したいと思います。これは、デフォルトの高さが 1 行であり、折り返しまたは新しい行を入力すると、QTextEdit がその高さを自動的に増加させることを意味します。コンテンツの高さが QTextEdit の高さを超えた場合、QTextEdit はスクロール バーを作成せず、単純に高さを増やします。

どうすればこれを行うことができますか?ありがとう。

4

2 に答える 2

6

次のコードは、QTextEdit ウィジェットをコンテンツの高さに設定します。

# using QVBoxLayout in this example
grid = QVBoxLayout()
text_edit = QTextEdit('Some content. I make this a little bit longer as I want to see the effect on a widget with more than one line.')

# read-only
text_edit.setReadOnly(True)

# no scroll bars in this example
text_edit.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 
text_edit.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 
text_edit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

# you can set the width to a specific value
# text_edit.setFixedWidth(400)

# this is the trick, we nee to show the widget without making it visible.
# only then the document is created and the size calculated.

# Qt.WA_DontShowOnScreen = 103, PyQt does not have this mapping?!
text_edit.setAttribute(103)
text_edit.show()

# now that we have a document we can use it's size to set the QTextEdit's size
# also we add the margins
text_edit.setFixedHeight(text_edit.document().size().height() + text_edit.contentsMargins().top()*2)

# finally we add the QTextEdit to our layout
grid.addWidget(text_edit)

これが役立つことを願っています。

于 2012-11-28T06:33:32.403 に答える