Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Scrolling Areas

The QScrollArea class provides a scrollable viewport and two scroll bars. If we want to add scroll bars to a widget, it is much simpler to use a QScrollArea than to instantiate our own QScrollBars and implement the scrolling functionality ourselves.

The way to use QScrollArea is to call setWidget() with the widget to which we want to add scroll bars. QScrollArea automatically reparents the widget to make it a child of the viewport (accessible through QScrollArea::viewport()) if it isn't already. For example, if we want scroll bars around the IconEditor widget we developed in Chapter 5 (as shown in Figure 6.11), we can write this:

int main(int argc, char *argv[])
    QApplication app(argc, argv);
    IconEditor *iconEditor = new IconEditor;

    QScrollArea scrollArea;
    scrollArea.setWindowTitle(QObject::tr("Icon Editor"));

    return app.exec();

Figure 6.11 Resizing a

The QScrollArea (shown schematically in Figure 6.12) presents the widget at its current size or uses the size hint if the widget hasn't been resized yet. By calling setWidgetResizable(true), we can tell QScrollArea to automatically resize the widget to take advantage of any extra space beyond its size hint.


Figure 6.12 's constituent widgets

By default, the scroll bars are displayed only when the viewport is smaller than the child widget. We can force the scroll bars to always be shown by setting scroll bar policies:


QScrollArea inherits much of its functionality from QAbstractScrollArea. Classes such as QTextEdit and QAbstractItemView (the base class of Qt's item view classes) derive from QAbstractScrollArea, so we don't need to wrap them in a QScrollArea to get scroll bars.

  • + Share This
  • 🔖 Save To Your Account