QTextBrowser vs QLabel in Qt Applications

When working with label widgets in Qt applications, QLabel is often the first choice due to its built-in support for word wrapping and rich text parsing. However, I discovered limitations with QLabel's line-breaking behavior that prompted me to explore alternatives.

Specifically, QLabel prevents splitting individual chraacters across lines, which causes issues when displaying long strings. This leads to either horizontal scrollbars appearing or text truncation. To address these problems, I investigated QTextBrowser, which offers more flexible text handling capabilities.

I created a custom wrapper class named CLabelBrowser based on QTextBrowser to achieve the desired functionality:

Header File

class CLabelBrowser : public QTextBrowser
{
    Q_OBJECT

public:
    CLabelBrowser(QWidget *parent = nullptr, bool enable = false);
    ~CLabelBrowser();

public:
    void SetAutoHeight(bool enable) { m_autoHeight = enable; }

    void ResetHeight();

protected:
    virtual bool event(QEvent *) override;
    virtual void resizeEvent(QResizeEvent *) override;
    virtual void changeEvent(QEvent *) override;

private:
    bool m_autoHeight = false;
};

Implementation File

CLabelBrowser::CLabelBrowser(QWidget *parent, bool enable)
    : QTextBrowser(parent)
    , m_autoHeight(enable)
{
    setOpenLinks(false);
    setContextMenuPolicy(Qt::NoContextMenu);
    connect(document(), &QTextDocument::contentsChanged, this, [this]{ ResetHeight(); });
}

CLabelBrowser::~CLabelBrowser()
{}

void CLabelBrowser::ResetHeight()
{
    if (m_autoHeight)
    {
        setFixedHeight(document()->size().rheight() + frameWidth() * 2);
    }
}

bool CLabelBrowser::event(QEvent *event)
{
    if (event->type() == QEvent::Show)
    {
        ResetHeight();
    }
    return QTextBrowser::event(event);
}

void CLabelBrowser::resizeEvent(QResizeEvent *event)
{
    ResetHeight();
    QTextBrowser::resizeEvent(event);
}

void CLabelBrowser::changeEvent(QEvent *event)
{
    QTextBrowser::changeEvent(event);
}

The implementation ensures dynamic height adjustment to prevent vertical scrolling by monitoring key events such as showing and resizing. This approach avoids calculating dimensions during initialization since the widget's actual size isnt available at that time.

For scenarios where long English words don't require special line-breaking rules, QLabel remains sufficient. The custom CLabelBrowser class provides enhanced control over text rendering and layout management.

Tags: Qt QLabel QTextBrowser gui Widget

Posted on Tue, 28 Jul 2026 16:45:26 +0000 by jokkis