|  | Home · Overviews · Examples |

# QWizard Class Reference
[com.trolltech.qt.gui module]

The `QWizard` class provides a framework for wizards. More...

Inherits `QDialog`.

## Detailed Description

The `QWizard` class provides a framework for wizards.

A wizard (also called an assistant on Mac OS X) is a special type of input dialog that consists of a sequence of pages. A wizard's purpose is to guide the user through a process step by step. Wizards are useful for complex or infrequent tasks that users may find difficult to learn.

`QWizard` inherits `QDialog` and represents a wizard. Each page is a `QWizardPage` (a `QWidget` subclass). To create your own wizards, you can use these classes directly, or you can subclass them for more control.

Topics:

- A Trivial Example
- Wizard Look and Feel
- Elements of a Wizard Page
- Registering and Using Fields
- Creating Linear Wizards
- Creating Non-Linear Wizards

### A Trivial Example

The following example illustrates how to create wizard pages and add them to a wizard. For more advanced examples, see Class Wizard and License Wizard.

        QWizardPage *createIntroPage()
        {
            QWizardPage *page = new QWizardPage;
            page->setTitle("Introduction");

            QLabel *label = new QLabel("This wizard will help you register your copy "
                                       "of Super Product Two.");
            label->setWordWrap(true);

            QVBoxLayout *layout = new QVBoxLayout;
            layout->addWidget(label);
            page->setLayout(layout);

            return page;
        }

        QWizardPage *createRegistrationPage()
        {
            ...
        }

        QWizardPage *createConclusionPage()
        {
            ...
        }

        int main(int argc, char *argv[])
        {
            QApplication app(argc, argv);

            QString translatorFileName = QLatin1String("qt_");
            translatorFileName += QLocale::system().name();
            QTranslator *translator = new QTranslator(&app);
            if (translator->load(translatorFileName, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
                app.installTranslator(translator);

            QWizard wizard;
            wizard.addPage(createIntroPage());
            wizard.addPage(createRegistrationPage());
            wizard.addPage(createConclusionPage());

            wizard.setWindowTitle("Trivial Wizard");
            wizard.show();

            return app.exec();
        }

### Wizard Look and Feel

`QWizard` supports four wizard looks:

- `ClassicStyle`
- `ModernStyle`
- `MacStyle`
- `AeroStyle`

You can explicitly set the look to use using `setWizardStyle` (e.g., if you want the same look on all platforms).

`ClassicStyle` | `ModernStyle` | `MacStyle` | `AeroStyle`
--- | --- | --- | ---

Note: `AeroStyle` has effect only on a Windows Vista system with alpha compositing enabled. `ModernStyle` is used as a fallback when this condition is not met.

In addition to the wizard style, there are several options that control the look and feel of the wizard. These can be set using `setOption` or `setOptions`. For example, `HaveHelpButton` makes `QWizard` show a Help button along with the other wizard buttons.

You can even change the order of the wizard buttons to any arbitrary order using `setButtonLayout`, and you can add up to three custom buttons (e.g., a Print button) to the button row. This is achieved by calling `setButton` or `setButtonText` with `CustomButton1`, `CustomButton2`, or `CustomButton3` to set up the button, and by enabling the `HaveCustomButton1`, `HaveCustomButton2`, or `HaveCustomButton3` options. Whenever the user clicks a custom button, `customButtonClicked` is emitted. For example:

                wizard()->setButtonText(QWizard::CustomButton1, tr("&Print"));
                wizard()->setOption(QWizard::HaveCustomButton1, true);
                connect(wizard(), SIGNAL(customButtonClicked(int)),
                        this, SLOT(printButtonClicked()));

### Elements of a Wizard Page

Wizards consist of a sequence of `QWizardPage`s. At any time, only one page is shown. A page has the following attributes:

- A title.
- A subTitle.
- A set of pixmaps, which may or may not be honored, depending on the wizard's style:
  - `WatermarkPixmap` (used by `ClassicStyle` and `ModernStyle`)
  - `BannerPixmap` (used by `ModernStyle`)
  - `LogoPixmap` (used by `ClassicStyle` and `ModernStyle`)
  - `BackgroundPixmap` (used by `MacStyle`)

The diagram belows showns how `QWizard` renders these attributes, assuming they are all present and `ModernStyle` is used:

When a subTitle is set, `QWizard` displays it in a header, in which case it also uses the `BannerPixmap` and the `LogoPixmap` to decorate the header. The `WatermarkPixmap` is displayed on the left side, below the header. At the bottom, there is a row of buttons allowing the user to navigate through the pages.

The page itself (the `QWizardPage` widget) occupies the area between the header, the watermark, and the button row. Typically, the page is a `QWizardPage` on which a `QGridLayout` is installed, with standard child widgets (`QLabel`s, `QLineEdit`s, etc.).

If the wizard's style is `MacStyle`, the page looks radically different:

The watermark, banner, and logo pixmaps are ignored by the `MacStyle`. If the `BackgroundPixmap` is set, it is used as the background for the wizard; otherwise, a default "assistant" image is used.

The title and subtitle are set by calling QWizardPage::setTitle() and QWizardPage::setSubTitle() on the individual pages. They may be plain text or HTML (see `titleFormat` and `subTitleFormat`). The pixmaps can be set globally for the entire wizard using `setPixmap`, or on a per-page basis using QWizardPage::setPixmap().

### Registering and Using Fields

In many wizards, the contents of a page may affect the default values of the fields of a later page. To make it easy to communicate between pages, `QWizard` supports a "field" mechanism that allows you to register a field (e.g., a `QLineEdit`) on a page and to access its value from any page. It is also possible to specify mandatory fields (i.e., fields that must be filled before the user can advance to the next page).

To register a field, call QWizardPage::registerField() field. For example:

        ClassInfoPage::ClassInfoPage(QWidget *parent)
            : QWizardPage(parent)
        {
            ...
            classNameLabel = new QLabel(tr("&Class name:"));
            classNameLineEdit = new QLineEdit;
            classNameLabel->setBuddy(classNameLineEdit);

            baseClassLabel = new QLabel(tr("B&ase class:"));
            baseClassLineEdit = new QLineEdit;
            baseClassLabel->setBuddy(baseClassLineEdit);

            qobjectMacroCheckBox = new QCheckBox(tr("Generate Q_OBJECT &macro"));

            registerField("className*", classNameLineEdit);
            registerField("baseClass", baseClassLineEdit);
            registerField("qobjectMacro", qobjectMacroCheckBox);
            ...
        }

The above code registers three fields, `className`, `baseClass`, and `qobjectMacro`, which are associated with three child widgets. The asterisk (`*`) next to `className` denotes a mandatory field.

The fields of any page are accessible from any other page. For example:

        void OutputFilesPage::initializePage()
        {
            QString className = field("className").toString();
            headerLineEdit->setText(className.toLower() + ".h");
            implementationLineEdit->setText(className.toLower() + ".cpp");
            outputDirLineEdit->setText(QDir::convertSeparators(QDir::tempPath()));
        }

Here, we call QWizardPage::field() to access the contents of the `className` field (which was defined in the `ClassInfoPage`) and use it to initialize the `OuputFilePage`. The field's contents is returned as a `QVariant`.

When we create a field using QWizardPage::registerField(), we pass a unique field name and a widget. We can also provide a Qt property name and a "changed" signal (a signal that is emitted when the property changes) as third and fourth arguments; however, this is not necessary for the most common Qt widgets, such as `QLineEdit`, `QCheckBox`, and `QComboBox`, because `QWizard` knows which properties to look for.

If an asterisk (`*`) is appended to the name when the property is registered, the field is a mandatory field. When a page has mandatory fields, the Next and/or Finish buttons are enabled only when all mandatory fields are filled.

To consider a field "filled", `QWizard` simply checks that the field's current value doesn't equal the original value (the value it had when `initializePage` was called). For `QLineEdit`, `QWizard` also checks that hasAcceptableInput() returns true, to honor any validator or mask.

`QWizard`'s mandatory field mechanism is provided for convenience. A more powerful (but also more cumbersome) alternative is to reimplement QWizardPage::isComplete() and to emit the QWizardPage::completeChanged() signal whenever the page becomes complete or incomplete.

The enabled/disabled state of the Next and/or Finish buttons is one way to perform validation on the user input. Another way is to reimplement `validateCurrentPage` (or QWizardPage::validatePage()) to perform some last-minute validation (and show an error message if the user has entered incomplete or invalid information). If the function returns true, the next page is shown (or the wizard finishes); otherwise, the current page stays up.

### Creating Linear Wizards

Most wizards have a linear structure, with page 1 followed by page 2 and so on until the last page. The Class Wizard example is such a wizard. With `QWizard`, linear wizards are created by instantiating the `QWizardPage`s and inserting them using `addPage`. By default, the pages are shown in the order in which they were added. For example:

        ClassWizard::ClassWizard(QWidget *parent)
            : QWizard(parent)
        {
            addPage(new IntroPage);
            addPage(new ClassInfoPage);
            addPage(new CodeStylePage);
            addPage(new OutputFilesPage);
            addPage(new ConclusionPage);
            ...
        }

When a page is about to be shown, `QWizard` calls `initializePage` (which in turn calls QWizardPage::initializePage()) to fill the page with default values. By default, this function does nothing, but it can be reimplemented to initialize the page's contents based on other pages' fields (see the example above).

If the user presses Back, `cleanupPage` is called (which in turn calls QWizardPage::cleanupPage()). The default implementation resets the page's fields to their original values (the values they had before `initializePage` was called). If you want the Back button to be non-destructive and keep the values entered by the user, simply enable the `IndependentPages` option.

### Creating Non-Linear Wizards

Some wizards are more complex in that they allow different traversal paths based on the information provided by the user. The License Wizard example illustrates this. It provides five wizard pages; depending on which options are selected, the user can reach different pages.

In complex wizards, pages are identified by IDs. These IDs are typically defined using an enum. For example:

        class LicenseWizard : public QWizard
        {
            ...
            enum { Page_Intro, Page_Evaluate, Page_Register, Page_Details,
                   Page_Conclusion };
            ...
        };

The pages are inserted using `setPage`, which takes an ID and an instance of `QWizardPage` (or of a subclass):

        LicenseWizard::LicenseWizard(QWidget *parent)
            : QWizard(parent)
        {
            setPage(Page_Intro, new IntroPage);
            setPage(Page_Evaluate, new EvaluatePage);
            setPage(Page_Register, new RegisterPage);
            setPage(Page_Details, new DetailsPage);
            setPage(Page_Conclusion, new ConclusionPage);
            ...
        }

By default, the pages are shown in increasing ID order. To provide a dynamic order that depends on the options chosen by the user, we must reimplement QWizardPage::nextId(). For example:

        int IntroPage::nextId() const
        {
            if (evaluateRadioButton->isChecked()) {
                return LicenseWizard::Page_Evaluate;
            } else {
                return LicenseWizard::Page_Register;
            }
        }

        int EvaluatePage::nextId() const
        {
            return LicenseWizard::Page_Conclusion;
        }

        int RegisterPage::nextId() const
        {
            if (upgradeKeyLineEdit->text().isEmpty()) {
                return LicenseWizard::Page_Details;
            } else {
                return LicenseWizard::Page_Conclusion;
            }
        }

        int DetailsPage::nextId() const
        {
            return LicenseWizard::Page_Conclusion;
        }

        int ConclusionPage::nextId() const
        {
            return -1;
        }

It would also be possible to put all the logic in one place, in a QWizard::nextId() reimplementation. For example:

        int LicenseWizard::nextId() const
        {
            switch (currentId()) {
            case Page_Intro:
                if (field("intro.evaluate").toBool()) {
                    return Page_Evaluate;
                } else {
                    return Page_Register;
                }
            case Page_Evaluate:
                return Page_Conclusion;
            case Page_Register:
                if (field("register.upgradeKey").toString().isEmpty()) {
                    return Page_Details;
                } else {
                    return Page_Conclusion;
                }
            case Page_Details:
                return Page_Conclusion;
            case Page_Conclusion:
            default:
                return -1;
            }
        }

To start at another page than the page with the lowest ID, call `setStartId`.

To test whether a page has been visited or not, call `hasVisitedPage`. For example:

        void ConclusionPage::initializePage()
        {
            QString licenseText;

            if (wizard()->hasVisitedPage(LicenseWizard::Page_Evaluate)) {
                licenseText = tr("<u>Evaluation License Agreement:</u> "
                                 "You can use this software for 30 days and make one "
                                 "backup, but you are not allowed to distribute it.");
            } else if (wizard()->hasVisitedPage(LicenseWizard::Page_Details)) {
                licenseText = tr("<u>First-Time License Agreement:</u> "
                                 "You can use this software subject to the license "
                                 "you will receive by email.");
            } else {
                licenseText = tr("<u>Upgrade License Agreement:</u> "
                                 "This software is licensed under the terms of your "
                                 "current license.");
            }
            bottomLabel->setText(licenseText);
        }

See also `QWizardPage`, Class Wizard Example, and License Wizard Example.