htmlqtresize

Qt - How to make QTextBrowser resize to contents (vertical layout)


I have a QTextBrowser object in my dialog which will have HTML written to it. It is in a vertical layout with several other objects. I have the vertical size policy currently set to MinimumExpanding for this QTextbrowser. The problem is if the HTML written to the browser ends up taller than the QTextBrowser's minimum set height, its height stays the same and it instead makes me scroll down through the browser to see all the data, where I would like it instead to show all the data at once. I have tried changing around the size policies for the QTextBrowser and the layout it is in, but nothing I have tried has worked. Is there a way to do this that I am overlooking?


Solution

  • If you know how many lines you are going to add then you can work out a height and then set that height.

    int number_of_lines; // If you can get this value from somewhere this should work
    
    // Get the height of the font being used
    QFontMetrics font_metrics(ui->text_browser->font());
    int font_height = font_metrics.height();
    
    // Get the height by multiplying number of lines by font height, Maybe add to this a bit for a slight margin?
    int height = font_height * number_of_lines;
    
    // Set the height to the text broswer
    ui->text_browser->setMinimumHeight(height);
    ui->text_browser->setMaximumHeight(height);