Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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



  • 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 QTextEdit's height, it creates a scroll-bar to scroll the content.

    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.

    How can I go about doing this? Thanks.



  • Some ideas, nothing tested:

    • connect to the signal contentsChanged of the QTextDocument attached to the text edit
    • grab the viewport widget of the QAbstractScrollArea (QTextEdit inherits it), check its size and adjust the edit


  • Indeed!

    I also got "a nice response on StackOverflow":http://stackoverflow.com/questions/11851020/a-qwidget-like-qtextedit-that-wraps-its-height-automatically-to-its-contents/11858803#11858803.

    Also in order to make the QTextEdit wrap its height around its document when the window / widget is resized, I had to use: @self.document().documentLayout().documentSizeChanged.connect(self.wrapHeightToContents)@

    Thanks.



  • Ah good, I didn't remember that QTextDocument had that signal. That would work even more elegantly.


Log in to reply