Getting Started

In this tutorial, we will go through each step in creating an address book application using the Qt Eclipse Integration. The tutorial will show you how to make a basic project using one of the project wizards. It will also teach you how to create a form using the integrated Qt Designer.

Creating a Skeleton Qt Application

The first step is to create a trivial project. To do so, invoke the New Project dialog in Eclipse and click the Qt folder. Then select the Qt Gui Project item and click Next. The Qt Gui Project wizard appears. The wizard consists of three pages. The first page lets you specify the project name. There you type "AddressBook" in the Project Name field. The following pages let you specify the name of the skeleton classes that will be generated by the wizard. Also, a page for specifying Qt modules is included. For the "AddressBook" example, the default values are fine so after entering the project name you can click Finish.

We now have the entire source code of a small Qt application. To compile it we have to set up some paths to the Qt library. For this the Qt Eclipse Integration provides a simple Qt version manager that transparently changes all the necessary settings. For more information about where to find and how to use the version manager have a look at Basic Qt Version Management.

Once Eclipse knows where Qt can be found, the project can be compiled. Go to the Project menu and click on Build Project. After a successful build, the "AddressBook" application can be launched. To do so, select the "AddressBook" project in the "C/C++ Projects" view, invoke the Run|Open Run Dialog... dialog and double click on the C/C++ Local Application item to create a new run configuration. If the "C/C++ Application" entry in the "Main" tab is empty, click on the "Search Project..." button to the right of it and select "Ok" in the dialog that pops up. Finally click the Run button.

Now you should see the "AddressBook" application which shows only an empty window so far. Close it by clicking the X button in its title bar.

Designing the Main Dialog

In this section, we'll design the application's main dialog using the integrated Qt Designer visual form editor. See the Qt Designer manual for more information.

We will start by adding the widgets and setting their properties. Then we will put them into layouts. The result is shown below.

Screenshot of the AddressBook's main dialog

Adding the Widgets

To launch Qt Designer, double-click on the addressbook.ui file in Eclipse's Navigator.

To add widgets to the form, we first need to make the Qt C++ Widget Box visible by clicking Window|Show View|Qt C++ Widget Box.

We'll start by adding the QListWidget. Expand the Item Widgets (Item-Based) group in the Qt C++ Widget Box, then click on the List Widget subitem and drag it onto the top-left corner of the form. The Qt C++ Property Editor (Window|Show View|Qt C++ Property Editor) will now display the properties for the QListWidget. Using the property editor, set the objectName property to "addressList".

Now we will insert the Add and Delete buttons. Expand the Buttons group in the Qt C++ Widget Box and drag two Push Buttons to the top-right corner of the form. Rename the buttons to "addButton" and "deleteButton", and set their text property to "Add" and "Delete".

Finally, we add two QLabels that will display the selected item in the list by dragging the Label item from the Display Widgets group onto the form once for each label. Rename the first label to "nameLabel" and change its text property to "<No item selected>"; rename the second label "emailLabel" and set its text property to be empty.

Try to position the widgets more or less as they appear on the screenshot above.

Adding the Layouts

We need to add layouts to the form to make it look better and to make it resizable.

First, we need a vertical layout for the buttons. We also need a spacer to push the buttons to the top of the layout. To add a spacer, drag the Vertical Spacer item from the Spacers group onto the form, below the push buttons. Then select the buttons and the spacer (by clicking each widget while holding Shift pressed) and click QtDesigner|Lay Out Vertically.

The entire window also needs a layout that will take care of positioning the other widgets as well as the button layout. To add this layout, select the main dialog by clicking on some space on it that isn't occupied by one of the widgets you added, then click QtDesigner|Lay Out in a Grid. Hint: Make sure that the labels are almost as wide as the form; otherwise the grid layout will make them only as wide as the address list.

Click QtDesigner|Preview to preview the form without compiling it.

Adding the "Add Address" Dialog

We will now add functionality to the application. By the end of this section, we'll have an application that pops up a dialog when the user clicks the Add button.

Designing the Dialog

First, we need to design the dialog. This time, there's no ready-made .ui file available in the project, so we need to click File|New|Qt Gui Class. This will invoke a wizard that asks for a class name. Enter "AddDialog" as the class name, select QDialog under UI Type and finish the wizard. Now the files are created but the Qt project file (.pro file) has to know about these files. Therefore, a dialog pops up asking you where the newly created files should be added. The suggested settings in this dialog mean that the created source file will be added to the Sources section of the .pro file, the header files to HEADERS and the .ui file to FORMS. These settings are fine, so click OK.

The Qt .pro file editor will be shown. If you select e.g. Source Files in the "Order Editor", the newly added "adddialog.cpp" file will be shown in the "Edit Source Files" view. To enable the build system to pick up these changes, save the .pro file.

Screenshot of the AddressBook's main dialog

Double-click adddialog.ui to open the form in Qt Designer. Click on the form and set its windowTitle property to "Add Address". Then create the following widgets and set their objectName and text properties according to the table below.

WidgetobjectNametext
QLabel"nameLabel""Name:"
QLabel"emailLabel""Email:"
QLineEdit"nameEdit"""
QLineEdit"emailEdit"""
QPushButton"okButton""OK"

Then do the layout. Hint: Use a grid layout for the labels and line edits.

Connecting the Dialog's OK Button

We want the OK button to invoke the QDialog::accept() slot. This can be done by clicking the Edit Signals/Slots toolbar button. You will then enter Qt Designer's connection editing mode.

Click the OK button of the dialog and hold the left mouse button pressed; then move the cursor to an empty area of the form and release the mouse button. The Configure Connection dialog will pop up, allowing you to establish a signal-slot connection between the OK button and the form. Use it to connect the button's clicked() signal to the form's accept() slot.

Invoking the "Add Address" Dialog from the Application

Once we're done designing the dialog, we need to invoke it when the user clicks the main dialog's Add button. To achieve this, we must add a slot to the AddressBook class and invoke the AddDialog from the slot.

To do this, open the file addressbook.h and declare a slot called on_addButton_clicked():

 class AddressBook : public QWidget
 {
 ...
 private slots:
     void on_addButton_clicked();
 ...
 };

Forms created using Qt Designer call QMetaObject::connectSlotsByName() to establish connections between signals emitted by the form's child widgets and slots that follow the naming convention on_<sender>_<signal>().

Now, open addressbook.cpp and implement the slot by inserting the following lines in the slot's body:

 void AddressBook::on_addButton_clicked()
 {
     AddDialog dialog(this);
     dialog.exec();
 }

We must also add this line to the top of addressbook.cpp:

     #include "adddialog.h"

Build and run the program now. If you click the Add button, the Add Address dialog will pop up. If you click OK, the dialog will go away.

Adding Items to the List Widget

We now want to add an item to the QListWidget when the user clicks OK. To do so, we first add two public accessors to the AddDialog in adddialog.h:

 class AddDialog : public QDialog
 {
 ...
     QString name() { return ui.nameEdit->text(); }
         QString email() { return ui.emailEdit->text(); }
 ...
 };

Now change the code in the on_addButton_clicked() slot in addressbook.cpp to the following:

 void AddressBook::on_addButton_clicked()
 {
     AddDialog dialog(this);

     if (dialog.exec()) {
                 QString name = dialog.name();
                 QString email = dialog.email();

                 if (!name.isEmpty() && !email.isEmpty()) {
                         QListWidgetItem *item = new QListWidgetItem(name, ui.addressList);
                         item->setData(Qt::UserRole, email);
                         ui.addressList->setCurrentItem(item);
                 }
         }
 }

We execute the dialog, and if the dialog is accepted (i.e. OK is clicked), we extract the Name and Email fields of the dialog and create a QListWidgetItem based on the information provided by the user.

Try the application now. Click Add, then enter "Joe Blow" as the name and "joe@blow.co.jp" as the email. Click OK. The list widget should now contain the new item.

Displaying the Selected Item

When the user selects an item in the list widget, we want to update the nameLabel and emailLabel at the bottom of the AddressBook form.

To do so, we need to add a slot to the AddressBook class. Open the addressbook.h file and add the following code in the private slots section of the class:

     void on_addressList_currentItemChanged();

Then add this code to addressbook.cpp:

     void AddressBook::on_addressList_currentItemChanged()
     {
         QListWidgetItem *curItem = ui.addressList->currentItem();

             if (curItem) {
                     ui.nameLabel->setText("Name: " + curItem->text());
                     ui.emailLabel->setText("Email: " + curItem->data(Qt::UserRole).toString());
             } else {
                     ui.nameLabel->setText("<No item selected>");
                     ui.emailLabel->clear();
             }
     }

Thanks to the naming convention, this slot will automatically be connected to addressList's currentItemChanged() signal, and will be invoked whenever the selected item in the list changes.

Adding Functionality to the Delete Button

We must also implement a slot for the Delete button. This is very similar to what we did for Add: Open addressbook.h and add a slot called on_deleteButton_clicked(). Then type in this code into the slot's body:

     QListWidgetItem *curItem = ui.addressList->currentItem();

         if (curItem) {
                 int row = ui.addressList->row(curItem);
                 ui.addressList->takeItem(row);
                 delete curItem;

                 if (ui.addressList->count() > 0)
                         ui.addressList->setCurrentRow(0);
                 else
                         on_addressList_currentItemChanged();
         }

This completes the application. The source code of this application can be found in the plugins directory of Eclipse. In order to add the project to the workspace use the Qt import wizard and specify the AddressBook.pro file (you might want to copy it first into your home folder if you don't have write permissions to eclipse's plugins directory).


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Eclipse Integration 1.6.0