chacham15
chacham15

Reputation: 14251

How do I place the QScrollBar on the content of the QScrollArea?

I want to make a scrollbar that fades in and out depending on usage. I subclassed QScrollBar and got the look that I want. The problem is that the scrollbar is placed next to the content. How do I instead make it go on top of the content?

Upvotes: 0

Views: 365

Answers (2)

mrg95
mrg95

Reputation: 2418

I quicker solution is to reparent the QScrollBars that the QScrollArea creates and add it to a new QLayout to position it how you want.

QScrollArea *scrollArea = new QScrollArea();

QScrollBar *scrollBar = scrollArea->horizontalScrollBar();
scrollBar->setParent(scrollArea);
scrollBar->setFixedHeight(20);//required for later

QVBoxLayout *scrollAreaLayout = new QVBoxLayout(scrollArea);
scrollAreaLayout->setContentsMargins(0, 0, 0, 10);//use whatever margins you want
scrollAreaLayout->addStretch(1);
scrollAreaLayout->addWidget(scrollBar);

This gets the basic functionality working, however the QScrollArea still adds space where the scrollbar would have been. To remove this, subclass QProxyStyle and override pixelMetric().

#include <QProxyStyle>

class StyleFixes : public QProxyStyle
{
public:
    int pixelMetric(PixelMetric metric, const QStyleOption *option = Q_NULLPTR, const QWidget *widget = Q_NULLPTR) const override
    {
        if(metric == PM_ScrollBarExtent)
        {
            return 0;
        }

        return QProxyStyle::pixelMetric(metric, option, widget);
    }
};

Then just apply it in main.cpp

QApplication::setStyle(new StyleFixes);

This will remove the arrows on the scrollbar however so you'll need to style it yourself.

Upvotes: 0

chacham15
chacham15

Reputation: 14251

I created a new QScrollbar which I connected to the original via signals and then used widget->setParent and then widget->setGeometry() to paint it on top

Upvotes: 1

Related Questions