I have QScrollArea which has QVBoxLayout where I place widgets and one of them is QTextBrowser and I want to make QTextBrowser to have size of its content and to remove its scrollbars. I inherited QTextBrowser, changed sizePolicy, hid scrollbars and overrided sizeHint() like this:
TextBrowserWidget::TextBrowserWidget(QWidget* parent)
: QTextBrowser(parent)
{
setSizePolicy(
QSizePolicy::Preferred,
QSizePolicy::Minimum);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
QSize TextBrowserWidget::sizeHint() const
{
if (document()) {
auto docSize = document()->size();
return QSize(docSize.width(), docSize.height() + 10);
} else
return QTextBrowser::sizeHint();
}
But this works with delay, at first widget becomes small and after 1-2 seconds it becomes bigger. I am not sure if it's good solution. What is the right way to do it?
TextBrowserWidget::TextBrowserWidget(QWidget* parent)
: QTextBrowser(parent)
{
setSizePolicy(
QSizePolicy::Minimum,
QSizePolicy::MinimumExpanding);
connect(
this, &TextBrowserWidget::textChanged,
this, &TextBrowserWidget::updateSize);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
QSize TextBrowserWidget::sizeHint()
{
updateSize();
return QTextBrowser::sizeHint();
}
void TextBrowserWidget::updateSize()
{
document()->setTextWidth(viewport()->size().width());
auto docSize = document()->size().toSize();
setMinimumWidth(docSize.width());
setMinimumHeight(docSize.height() + 10);
}