Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

[Prev: Preface] [Home] [Next: Creating a Main Window Application]

## Quick Start

This chapter provides a quick start for users of Qt Designer. The chapter takes you step-by-step through the creation of a small dialog-style metric conversion application. It introduces adding widgets to a form, setting widget properties, making signals and slots connections, laying out widgets, and adding custom code. This chapter only covers a proportion of Qt Designer's functionality and explanations and details are mostly left for the more detailed `colortool` tutorial presented in chapters two and three.

> The Metric Conversion Dialog

### Starting and Exiting Qt Designer

#### Starting

- To start Qt Designer under Windows click the Start button and click Programs|Qt X.x.x|Designer. (X.x.x is the Qt version number, e.g. 3.2.1.)

- If you're running a Unix or Linux operating system you can either double click the Qt Designer icon or enter `designer &` in an xterm.

- Start Qt Designer now. When Qt Designer starts, it shows the New/Open dialog. We'll just click Cancel to skip it.

#### Exiting

When you've finished using Qt Designer click File|Exit; you will be prompted to save any unsaved changes.

### Creating the Project

The metric conversion application is a standard C++ application, so we must create a C++ project and add our files and code to this project.

Create the new project as follows:

- Click File|New to invoke the New File dialog.

- Click "C++ Project" to create a C++ project, then click OK to pop up the Project Settings dialog.

- Click the ellipsis (...) button next to the Project File line edit to invoke the Save As dialog. Use this dialog to navigate to where you want to create the new project, ideally creating a new folder for it (e.g. called "metric"), using the Create New Folder toolbar button.

- Enter a filename of "metric.pro", then click Save. The project's name will now be "metric"; click OK to close the Project Settings dialog.

- Click File|Save to save the project.

See also Creating the Project.

### Creating the Dialog

- Click File|New to invoke the New File dialog, then click "Dialog", then click OK.

- Drag a corner of the new form to make it a lot smaller. Change the form's name (in the Property Editor) to "ConversionForm", and change its caption to "Metric Conversion".

- Click File|Save, accept the default form name, and then click Save to save it.

See also Creating Dialogs and Layouts.

#### Adding Widgets to the Dialog

##### Adding Text Labels

- Click the Common Widgets button listed in the Toolbox toolbar at the left of Qt Designer's main window.

- Double click the TextLabel button and click towards the top left of the dialog.

- Click four more times below the top text label until you have 5 labels from top to bottom. Don't worry about exact placement of the labels since the layout tools will handle this automatically.

- Click the Pointer toolbar button to deselect the text label.

See also Adding the Widgets.

Now we will change the properties of the text labels to suit the application.

- Click on the top text label. Go to the Property Editor window and change the label's text property to "Enter &Number:". The & (ampserand) makes the following letter an Alt key accelerator (keyboard shortcuts).

- Click the second label. Change the label's text property to "Convert &From:".

- Click the third label. Change the label's text property to "Convert &To:".

- Click the fourth label. Change the label's text property to "Result:".

- Click the fifth label. Change the label's text property to "&Decimals:".

See also Using the Property Editor.

##### Adding Line Edits, Comboboxes, and Spinboxes

- Click the Common Widgets button listed in the Toolbox toolbar at the left of Qt Designer's main window.

- Click the LineEdit button and then click to the right of the Enter Number label. Change its name property to "numberLineEdit". Change the hAlign property to AlignRight and change vAlign to AlignTop. Finally, change wordwrap to False. Note that whenever you click a widget, its properties appear in the Property Editor.

- Double click the ComboBox button and click to the right of the Convert From label. Now click to the right of the Convert To label. Click the Pointer toolbar button to deselect the ComboBox. Change the name property of the first combobox to "fromComboBox". Change the name property of the second to "toComboBox".

- Click the LineEdit button and then click to the right of the "Result" label. Change its name property to "resultLineEdit". Change the paletteBackgroundColor property to a shade of yellow (just to make the result stand out). Change hAlign to AlignRight, vAlign to AlignVCenter and wordwrap to False. Now change the readOnly property to "True".

- Click the SpinBox button and then click to the right of the Decimals label. Place the SpinBox below the right side of the resultLineEdit. Change the spinbox's name property to "decimalsSpinBox". Change its max value property to "6" and the value to "3".

- Click File|Save.

Now we need to relate each of the text labels to the corresponding widget. We do this by creating "buddies".

A widget that does not accept focus itself, e.g. a QLabel, can have an accelerator that will pass the focus to its "buddy", e.g. a QLineEdit, by setting the first widget's buddy property to the name of the buddy widget.

- Click the Set Buddy toolbar button (or press F12). Click the Enter Number label and drag the line to the numberLineEdit; then release.

- Click the Set Buddy toolbar button. Click the Convert From label and drag the line to the fromComboBox; then release.

- Click the Set Buddy toolbar button. Click the Convert To label and drag the line to the toComboBox; then release.

- Click the Set Buddy toolbar button. Click the Decimals label and drag the line to the decimalsSpinBox; then release.

##### Adding Push Buttons

- Click the Common Widgets button in the Toolbox.

- Double click the Pushbutton button and click towards the bottom left of the dialog, below the Decimals label.

- Click to the right of the new push button twice more so that you have three push buttons horizontally in a row at the bottom of the dialog.

- Click the Pointer toolbar button to deselect the push button.

We will change a few properties for each of the push buttons in the Property Editor window.

- Click the left-most push button, and change its name to "clearPushButton" and its text to "&Clear".

- Click the middle push button and change its name to "calculatePushButton", its text to "Calculate" and its default property to "True".

- Click the right-most push button and change its name to "quitPushButton" and its text to "&Quit".

##### Adding Spacers

We need to add spacers to absorb redundant space in our dialog so that it will lay out nicely at whatever size the user resizes it to. Usually spacers are added as you experiment with the layout, but since this is a quick guide to Qt Designer, we will add the spacers now since we already know that they will be needed.

- Click the Common Widgets button in the Toolbox.

- Click the Spacer button and click to the right of the Decimal label and drag right towards the spinbox; then release. A horizontal spacer will appear.

- Click the Spacer button again and click to the right of the Calculate push button and drag right towards the Quit push button; then release.

- Click the Spacer button and click just below the spin box and drag vertically towards the buttons; then release. A vertical spacer will appear.

Click File|Save to save the dialog.

##### Editing Widgets

We'll now edit some of the widgets to contain the values needed for the conversions.

The fromComboBox:

- Right click the fromComboBox and then click Edit from the context menu.

- Click New Item and then delete the "New Item" text and type "Kilometers". Click New Item and change the text to "Meters". Repeat this twice more, changing the text to "Centimeters" and to "Millimeters" respectively.

- Click OK to close the Edit Listbox dialog.

The toComboBox:

- Right click the toComboBox and then click Edit from the context menu.

- Delete the "New Item" text and type "Miles". Click New Item and change the text to "Yards". Repeat this twice more, changing the text to "Feet" and to "Inches".

- Click OK to close the Edit Listbox dialog.

#### Laying Out the Dialog

We'll lay out the text labels and their corresponding widgets first and we'll do the push buttons last.

- Click the decimalsSpinBox and press Shift+Click on the spacer next to it. Click the Lay Out Horizontally (Ctrl+H) toolbar button.

- Click the form (to deselect anything that's selected), then click the form to the left of the Decimals text label and then drag the rubber band so that it touches every label and widget, including the decimals spacer, but avoiding the other spacers and the push buttons. Release the mouse and notice that the desired widgets are selected. Click the Lay Out in a Grid (Ctrl+G) toolbar button.

- Click the Clear push button in the Object Explorer window (Objects tab) and then Shift+Click the Calculate push button, the Quit push button and the Spacer between the push buttons. Click the Lay Out Horizontally toolbar button.

- Click the form to deselect all the widgets and layouts and then click the Lay Out Vertically (Ctrl+L) toolbar button.

- Finally, click the form and then click the Adjust Size (Ctrl+J) toolbar button.

Click File|Save to save the dialog.

See also Laying Out the Widgets.

##### Tab Order

We should make sure that our dialog's tab order is set correctly.

- Click the Tab Order toolbar button. A number in a blue circle will appear next to every widget that can accept focus.

- Click every widget in turn in the order you want them to accept focus.

- Press Esc to leave tab order mode.

See also Changing the Tab Order.

#### Previewing the Dialog

To preview the dialog, press Ctrl+T or click Preview|Preview Form from the menubar. Try dragging the corner of the dialog to adjust the size. Note that the the widgets always stay in proportion no matter what size you make the dialog. Check the tab order of the widgets by pressing the Tab key.

#### Connecting the Widgets

We need to connect three buttons; the Clear button, the Calculate button and the Quit button. We also need to connect some of the other widgets. For convenience, we can do all of our connections in one go using the View and Edit Connections dialog.

We will now connect our clearButton:

- Click Edit|Connections to invoke the View and Edit Connections dialog.

- Click New to enter a new connection.

- For the first connection, select clearPushButton for the Sender, clicked() for the Signal, numberLineEdit for the Receiver, and clear() for the Slot.

- Click New again.

- Select clearPushButton for the Sender, clicked() for the Signal, resultLineEdit for the Receiver, and clear() for the Slot.

- Click New again.

- Select clearPushButton for the Sender, clicked() for the Signal, numberLineEdit for the Receiver, and setfocus() for the Slot.

We also need to connect the quit button to the form:

- Click New.

- Select quitPushButton for Sender, clicked() for Signal, ConversionForm for Receiver, and close() for Slot.

We want to connect the calculate button and the other widgets, but the slot we want to use is not listed in the combobox. We will need to create a new slot so that we can select it from the list to complete our connections.

- Click New.

- Select calculatePushButton for the Sender, clicked() for the Signal, and ConversionForm for the Receiver.

- Click Edit Slots to invoke the Edit Functions dialog. Click New Function. Type over the Function name with the name of our new function: convert(), then click OK.

- Select convert() from the Slot combobox to complete our connection.

We will now connect the last few widgets:

- Click New.

- Select decimalsSpinBox as the Sender, valueChanged(int) as the Signal, ConversionForm as the Receiver, and convert() as the Slot.

- Click New.

- Select fromComboBox as the Sender, activated(int) as the Signal, ConversionForm as the Receiver, and convert() as the Slot.

- Click New.

- Select toComboBox as the Sender, activated(int) as the Signal, ConversionForm as the Receiver, and convert() as the Slot.

Click OK to exit the View and Edit Connections dialog.

Click Save to save the project.

### Coding the Dialog

Click "conversionform.ui.h" in the Project Overview window to invoke the code editor. We'll implement the `convert()` function and also the `init()` function. For faster implementation, copy the code from this section and then follow the brief explanations below:

        void ConversionForm::convert()
        {
            enum MetricUnits {
                Kilometers,
                Meters,
                Centimeters,
                Millimeters
            };
            enum OldUnits {
                Miles,
                Yards,
                Feet,
                Inches
            };

            // Retrieve the input
            double input = numberLineEdit->text().toDouble();
            double scaledInput = input;

            // internally convert the input to millimeters
            switch ( fromComboBox->currentItem() ) {
            case Kilometers:
                scaledInput *= 1000000;
                break;
            case Meters:
                scaledInput *= 1000;
                break;
            case Centimeters:
                scaledInput *= 10;
                break;
            }

            //convert to inches
            double result = scaledInput * 0.0393701;

            switch ( toComboBox->currentItem() ) {
            case Miles:
                result /= 63360;
                break;
            case Yards:
                result /= 36;
                break;
            case Feet:
                result /= 12;
                break;
            }

            // set the result
            int decimals = decimalsSpinBox->value();
            resultLineEdit->setText( QString::number( result, 'f', decimals ) );
            numberLineEdit->setText( QString::number( input, 'f', decimals ) );
        }

First, we define some enums for the input and output units. Then we retrieve the input from the numberLineEdit. We convert the input to millimeters because this is the most precise metric unit we support. Then we convert it to inches which is the most precise output unit we support. We then scale it to the selected output unit. Finally, we put the result in the resultLineEdit.

Next, we will implement the `init()` function which is called when the dialog is created.

        void ConversionForm::init()
        {
            numberLineEdit->setValidator( new QDoubleValidator( numberLineEdit ) );
            numberLineEdit->setText( "10" );
            convert();
            numberLineEdit->selectAll();
        }

For this function, we set a validator on the numberLineEdit so that the user can only input numbers. To be able to do this, we also need to add `#include <qvalidator.h>` at the top of the form, right above the `init()`. Lastly, we set the initial input.

We are almost ready to run the application. Before we compile the application, we need a `main.cpp` file.

- Click File|New and click C++ Main File (`main.cpp`).

- Accept the default selections for the Configure Main-File dialog.

- Click Save to save the project.

Compiling and Running the Application

- Start or switch to a console and navigate to the directory where you saved your project.

- Run qmake on the project file (`metric.pro`) by typing `qmake -o Makefile metric.pro`.

- Run make (or nmake depending on your system).

- After the project has compiled, run the application.

### Wrapping Up

This application has given a very quick introduction to Qt Designer. It has introduced adding widgets to a form, setting widget properties, making signals and slots connections, laying out and adding custom code. Much of the detail and explanations have been deferred. The next two chapters provide a tutorial that covers the development of a small but complete application, and the reference chapters complete the detailed coverage.

[Prev: Preface] [Home] [Next: Creating a Main Window Application]