0
votes

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?

1
Hiding the bars will not prevent your widget to crop the content, it is not a policy for the size (i.e. it does not mean resize so you don't need scrollbar). You can remove this, when your widget will have the size you want the scrollbars will be hidden.Why did you change the QSizePolicy ? The default Expanding seems to be what you want. You can take a look at QAbstractScrollArea::sizeAdjustPolicy, maybe this will do what you want without touching to sizeHint().ymoreau
@ymoreau, yes, I know about scrollbar policy. With default size policy widget decreases in size. And sizeAdjustPolicy also doesn't workdevalone
@ymoreau, I solved it(look down). I am not sure if it's the best solution, but it works pretty cool.devalone

1 Answers

0
votes
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);
}