how to specify the height of scrollbar in QTreeView

973 views Asked by At

just like the title described, when i redraw the scrollbar in QTreeView which has a header(QHeaderView), but the scrollbar's height is the entire height of QTreeView, and i want to let the scrollbar's height equals the QTreeView's height minus the header's height.just like the pic below: just like this, exclude the height of header

1

There are 1 answers

4
Dusteh On BEST ANSWER

A solution for your problem might be setting the location of the vertical scrollbar to a constant_offset value acquired from the QHeaderView (on the y axis).

This could be done by subclassing the QTreeView like so:

class MyTreeView : public QTreeView
{
public:
    MyTreeView(QWidget* parent = nullptr): QTreeView(parent){}

    void updateVertScrollBar()
    {
        auto* ptr = verticalScrollBar();
        QRect rect = ptr->geometry();
        rect.setTop(header()->height());
        ptr->setGeometry(rect);
    }

    void resizeEvent(QResizeEvent* ev) override
    {
        QTreeView::resizeEvent(ev);
        updateVertScrollBar();
    }
};

Depending on the sizePolicy the updateVertScrollBar method could be called just after data is filled or as presented in the sample implementation the update can occur for each resizeEvent - which should cover various resizing performed to the widget.

EDIT

Additionally removing the blank space left from the shrunk scrollbar would be tricky. First denote that the QTreeView is built from a viewport widget and scrollbars (among others). The issue you now see comes from the fact that viewport plus vertical scrollbar widths (if visible) should match and this is calculated internally.

I stated that it's tricky since there is a load of stuff happening when you try to force the size of these components. Some updates are called in-place some are called through the event loop. You can check this to get more detaile info about the concept. Similar approach is probably applied to QTreeView.

Basically what you would need to do is to stretch the viewport width. This should be probably done during the resizeEvent but calling from there methods like viewport()->setGeometry() might not end well - you might get caught into a loop. You might try blockSignals but I'm not sure this would help. In general if you want to mess with the internals of a given Qt widget you should go through it's implementation at least briefly.