A QWidget like QTextEdit that wraps its height automatically to its contents?

前端 未结 2 461
深忆病人
深忆病人 2020-12-17 00:25

I am creating a form with some QTextEdit widgets.

The default height of the QTextEdit exceeds a single line of text and as the contents\' height exceeds the QTextEdi

2条回答
  •  误落风尘
    2020-12-17 00:52

    the following code sets a QTextEdit widget to the height of the content:

    # 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)
    

    I hope this helps.

提交回复
热议问题