Search code examples
c++qtstylesqscrollarea

Add widget next to qscrollbar


How do I place a widget next to a QScrollbar like here seen: enter image description here

I use a QScrollArea and overwrite the Horizontal-QScrollBar. First I thought, I could use the paintEvent to draw a text like the "100 %" next to the bar. But I can only overwrite the existing painting.

Now I think, the only opportunity would be to implement the hole QScorllBarPrivate from the source code... anyone any idea?


Solution

  • The main idea is to create an overlay obscuring default horizontal scroll bar and displaing your own bottom line instead.

    1. Create a widget representing the bottom line, i.e. a widget with labels displaying some information and a horizontal QScrollBar, all together put in a hbox layout.
    2. Put this widget in the scroll area without adding it to a layout by making QScrollArea direct parent widget of this widget.
    3. Use move() and resize() on the bottom line widget to position it properly on initialization. Also resize and reposition it on scroll area resize (you can use event filters or inheritance to get to resize events).
    4. Make sure that scroll area's horizontalScrollBarPolicy is Qt::ScrollBarAlwaysOn so that scroll area's internal layout always keeps space enough for bottom line widget to fit in.
    5. Also make sure that bottom line widget has the same height as default scroll bar. It should be easy as long as you remove spacing and margins in the hbox layout and labels (or other widgets) don't require more vertical space than a scroll bar.
    6. Use horizontalScrollBar() to get scroll area's internal QScrollBar and syncronize it with your own bar. QScrollBar has rangeChanged() and valueChanged() signals so you can connect to them and update your bar properly. When user changes value of your scroll bar and triggers its valueChanged() signal, you should set the same value for the internal scrollbar. You can protect from infinite recursion in there by using a flag that indicates that this is your own change.