Home > Articles > Programming > C/C++

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

Stacked Layouts

The QStackedLayout class lays out a set of child widgets, or "pages", and shows only one at a time, hiding the others from the user. The QStackedLayout itself is invisible and provides no intrinsic means for the user to change the page. The small arrows and the dark gray frame in Figure 6.5 are provided by Qt Designer to make the layout easier to design with. For convenience, Qt also includes QStackedWidget, which provides a QWidget with a built-in QStackedLayout.

The pages are numbered from 0. To make a specific child widget visible, we can call setCurrentIndex() with a page number. The page number for a child widget is available using indexOf().

The Preferences dialog shown in Figure 6.6 is an example that uses QStackedLayout. The dialog consists of a QListWidget on the left and a QStackedLayout on the right. Each item in the QListWidget corresponds to a different page in the QStackedLayout. Here's the relevant code from the dialog's constructor:

PreferenceDialog::PreferenceDialog(QWidget *parent)
    : QDialog(parent)
    listWidget = new QListWidget;
    listWidget->addItem(tr("Web Browser"));
    listWidget->addItem(tr("Mail & News"));

    stackedLayout = new QStackedLayout;
    connect(listWidget, SIGNAL(currentRowChanged(int)),
            stackedLayout, SLOT(setCurrentIndex(int)));

Figure 6.6 Two pages of the Preferences dialog

We create a QListWidget and populate it with the page names. Then we create a QStackedLayout and call addWidget() for each page. We connect the list widget's currentRowChanged(int) signal to the stacked layout's setCurrentIndex(int) to implement the page switching and call setCurrentRow() on the list widget at the end of the constructor to start on page 0.

Forms such as this are also very easy to create using Qt Designer:

  1. Create a new form based on one of the "Dialog" templates or on the "Widget" template.
  2. Add a QListWidget and a QStackedWidget to the form.
  3. Fill each page with child widgets and layouts. (To create a new page, right-click and choose Insert Page; to switch pages, click the tiny left or right arrow located at the top right of the QStackedWidget.)
  4. Lay out the widgets side by side using a horizontal layout.
  5. Connect the list widget's currentRowChanged(int) signal to the stacked widget's setCurrentIndex(int) slot.
  6. Set the value of the list widget's currentRow property to 0.

Since we have implemented page switching using predefined signals and slots, the dialog will exhibit the correct behavior when previewed in Qt Designer.

For cases where the number of pages is small and likely to remain small, a simpler alternative to using a QStackedWidget and QListWidget is to use a QTabWidget.

  • + Share This
  • 🔖 Save To Your Account