sashoalm
sashoalm

Reputation: 79595

Qt: How to create a scrollable, owner-drawn widget

I need to create a scrollable, owner-drawn widget that behaves a lot like QPlainTextEdit with word-wrapped text, in the sense that the height depends on the width - as the content width decreases, the content height increases.

What is the best approach to do it? I was thinking about putting my QWidget-derived class inside a QScrollArea, but QPlainTextEdit is derived from QScrollArea instead, should I go that route?

Also, I want to paint only the visible area in paintEvent(), it would be wasteful otherwise.

Right now I'm examining the code of QPlainTextEdit, but it is rather complex and not easy to read, so if anyone knows of a code example that's simpler on the web, you can give me a link, it would help a lot.

Upvotes: 2

Views: 468

Answers (1)

sashoalm
sashoalm

Reputation: 79595

I'll post the solution I came up with. It's not the best, but it mostly works.

I did not derive from QAbstractScrollArea in the end, instead I simply embedded my widget in a QScrollArea with a vertical layout, which worked well-enough.

I implemented resizeEvent() (I saw this from QPlainTextEdit implementation), and each time the width changes, I recalculate the height, and I set the widget's minimum height to that. I set the minimum height because of how the layout works.

void MyWidget::resizeEvent(QResizeEvent *e)
{
    // If the widget's width has changed, we recalculate the new height
    // of our widget.
    if (e->size().width() == e->oldSize().width()) {
        return;
    }

    setMinimumHeight(calculateHeightFromWidth(e->size().width()));
}

For drawing only the visible area see Get visible area of QPainter

Upvotes: 1

Related Questions