Home

[Previous: Qt Visual Studio .NET Integration] [Contents] [Next: Managing Projects]

Getting Started

In this tutorial, we will go through each step in creating an address book application using the Qt Visual Studio .NET 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 and how to convert a Visual Studio project file into a qmake-compatible .pro file.

Creating a Skeleton Qt Application

The first step is to create a trivial project. To do so, invoke the New Project dialog in Visual Studio and click the Qt Projects folder. Then select the Qt Application item and type "AddressBook" in the Name field.

When you click OK, a project wizard appears. The wizard includes a page for specify which Qt modules you want to link against, followed by a page that enables you to specify the name of a skeleton class that will be generated by the wizard to get you started. For the "AddressBook" example, the default values are fine.

We now have a small working Qt application. To try it out, press F5. The result should be an empty window. 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 Form Files\addressbook.ui file in Visual Studio's Solution Explorer.

To add widgets to the form, we first need to make the Qt Toolbox visible by clicking Qt|Qt Toolbox.

We'll start by adding the QListWidget. Expand the Item Widgets (Item-Based) group in the Qt Toolbox, then click on the List Widget subitem and drag it onto the top-left corner of the form. The Visual Studio 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 Toolbox and drag two Push Buttons to the top-right corner of the form. Rename the buttons "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 "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 Qt|Form Editor|Layout 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 list widget, the list widget, the two labels, and the button layout, then click Qt|Form Editor|Layout 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 Qt|Form Editor|Preview Form to preview the form without compiling it. Press F5 to build and run the application.

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 Project|Add Qt GUI Class. This will invoke a wizard that asks for a class name. Enter "AddDialog" as the name and "QDialog" as the base class. Then check the "Multiple Inheritance" checkbox and click Finish. There should now be an adddialog.ui file in the project's Form Files folder.

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"nameText""Name:"
QLabel"emailText""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 Connections toolbar button. You will then enter Qt Designer's connection mode.

Click the OK button 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.

The Qt Visual Studio Integration makes this very easy. Simply double-click the Add button; this will open the .cpp file associated to the dialog and generate a skeleton slot called on_addButton_clicked(). Type in the following code lines in the slot's body:

 AddDialog dialog(this);
 dialog.exec();

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>().

If we wanted to connect to another signal than clicked(), we would have to manually add the slot to the AddressBook class's. This requires editing both the header file (addressbook.h) and the implementation file (addressbook.cpp).

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, change the code in the on_addButton_clicked() slot to the following:

 AddDialog dialog(this);

 if (dialog.exec()) {
             QString name = dialog.nameEdit->text();
             QString email = dialog.emailEdit->text();

             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.

Earlier, we added some code by double-clicking the Add button. This automatically creates a slot corresponding to the widget's "default signal". The default signal is the signal that you're most likely to be interested in (for example, clicked() for QPushButton). If you want to connect to another signal, you must write the code manually as we did here for the addressList's currentItemChanged() signal.

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.ui and double-click the Delete button. This will pop up a code editor with an empty slot called on_deleteButton_clicked(). 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.

Creating Qt Project File

If you want to build this application on other platforms, you need to create a .pro file for the project. A simple way to do this is to let the Visual Studio integration create a basic .pro file for you by clicking Qt|Create Basic .pro File. When the Export Project dialog shows up, make sure the Create .pri File option is checked, then click OK. Visual Studio will then ask you where to save the .pri file. The default location and name is usually fine, so just click Save. For more information about .pro files and their associated .pri files, see Managing Projects.

That's it! You should now have a working .pro file and .pri file for your project. For more complex projects, manually editing the .pro file is required to make it work on all plaforms, but for our simple project the generated .pro file is sufficient.

[Previous: Qt Visual Studio .NET Integration] [Contents] [Next: Managing Projects]


Copyright © 2007 Trolltech Trademarks
Qt