Qt Notes: Managing QStackedWidget with Qt Designer

While working on my iTunes remote control software, which uses the Qt cross-platform application and UI framework, I found the need to change the contents of a UI form based on system state.  QStackedWidget seemed like the perfect tool for the job, but there was one slight problem; it couldn't be fully managed with Qt Designer.  At least not with the version of Qt Designer that is packaged with Qt Creator IDE version 2.2.1.

I don't know if this is a bug, or if it is intentional, but it is not currently possible to assign a layout to a QStackedWidget page from within Qt Designer.  The layout of a QStackedWidget page starts as a broken layout and stays that way.  A broken layout means that the contents of the QStackedWidget page will not resize properly.  Fortunately, there is a work around for this problem in the form of widget promotion.  

The QtStackedWidget pages are of the type QWidget, and Qt Designer includes functionality for promoting objects of type QWidget (or other Qt widget types) to objects of types derived from QWidget.  This allows custom widgets to be managed with Qt Designer.  By placing the intended contents of a QStackedWidget page into a custom form, and promoting the QStackedWidget page to the custom form, the page can be fully managed from within Qt Designer.  

The steps for creating a custom form and promoting a QStackedWidget page to that form are simple and straightforward:

  1. Create a custom form.  This is done by selecting "New..." from the file dialog to launch the New Form dialog, selecting "Widget" from the "templates\forms" list and clicking the "Create" button.  

    Creating a New Form

  2. Populate the form with the desired widgets and then save it to a file.  

    Empty Form

  3. Open the Promoted Widgets dialog by left clicking on the widget that you would like to promote and clicking on the "Promote to ..." option.  

    Promote to ... Menu Option

  4. Add the custom form to the Promoted Widgets list and promote the QStackedWidget page to the custom form by selecting the custom form in the list and clicking the "Promote" button.  Note that the base class specified for the custom widget must be the same as, or a descendent of, the class type for the widget being promoted.  

    Promoted Widgets Dialog

 

That's all it takes.  Of course, you can also use a custom widget, something like MyListWidget derived from QListWidget, instead of a custom form.  Just make sure to specify the custom widget's base class as QWidget when promoting to a QStackedWidget page.  

 

Programming: