Search code examples
macosqtqstyle

Transient scrollbar in Qt


I want to use transient scrollbar (Transient scroll bars appear when the content is scrolled and disappear when they are no longer needed) in Qt application. For this purpose I have inheritanced class QproxyStyle and reimplemented function styleHint. Code placed below. File ScrollBar.h:

#include <QStyle>
#include <QCommonStyle>
#include <QProxyStyle>

class ScrollBarStyle : public QProxyStyle
{
public:
    int styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *widget, QStyleHintReturn *hret) const;
};

File ScrollBar.c:

#include "ScrollBar.h"

int ScrollBarStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *widget,QStyleHintReturn *hret) const
{
    int ret = 0;

    switch (sh) {
    case SH_ScrollBar_Transient:
        ret = true;
        break;
    default:
        return QProxyStyle::styleHint(sh, opt, widget, hret);
    } 

    return ret;
}

File MainWindow.h:

#include <QMainWindow>
#include <QTextEdit>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

File MainWindow.cpp:

#include <QTextEdit>
#include "MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QTextEdit *l = new (std::nothrow) QTextEdit(this);
    if (l == 0)
        return;
    setCentralWidget(l);
}

MainWindow::~MainWindow()
{
}

File main.cpp:

#include "ScrollBar.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    ScrollBarStyle *style = new (std::nothrow) ScrollBarStyle;
    if(style == 0)
        return -1;

    style->setBaseStyle(a.style());
    w.show();

    return a.exec();
}

But I have got a problem: transient scrollbar has been appearing only once (when text doesn't fit in the text area) then it has been disappeared and never come back visible.

So how can I fix this problem? Thanks!


Solution

  • You have forgotten to set the style to application.

    a.setStyle(style);