Search code examples
c++qtsizeqtextdocument

Update QTextDocument's size


I have a problem with QTextDocument::size()

The size of the document is updated every time user enters something to TextEdit manually. (So in SIGNAL textChanged it works fine). However, I insert some text by code.

textEdit->insertPlainText("blablablabla\n");

When I use this:

int iHeight = textEdit->document()->size().height();

The iHeight is always equal to 21, even though the textEdit has multiple lines of text. When I use the same line of code in the SIGNAL i talked about, the iHeight magically turns into the correct number.

So basically, my question is how to update the document's size so it returns proper number?


Solution

  • You have to set the QDocuments width to the width of the QTextEdit to let it know whether there are line breaks. Afterwards it returns the right size.

    Example:

    QTextEdit textEdit;
    textEdit.setMaximumWidth(50);
    textEdit.setText("Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test");
    textEdit.document()->adjustSize();
    QSizeF size1 = textEdit.document()->size();
    textEdit.document()->setTextWidth(textEdit.width());
    QSizeF sizew = textEdit.document()->size();
    textEdit.show();
    

    Indeed, adjustSize is not enough.