Tutorial: Qt Widgets Application

This tutorial illustrates how to use Qt VS Tools to create a Qt Widgets application. You will create a project using a project wizard and design a widget-based UI using Qt Designer. In addition, you will learn how to convert a Microsoft Visual Studio project file into a qmake compatible .pro file.

You can use Qt VS Tools to develop also Qt Quick applications.

Before You Start

Before you start, you have to:

Create a Qt Widgets Application Project

To create a Qt Widgets application project in Visual Studio:

  1. Select File > New > Project, and search for Qt Widgets Application.
  2. Select the project wizard, and then select Next.
  3. In the Project name field, enter AddressBook, and then select OK.
  4. To acknowledge the Welcome dialog, select Next.
  5. Set up the Debug build configuration and select the modules to include in the project:

    "Selecting Qt modules in Qt Widgets Application Wizard"

    The modules that are typically needed in widget application projects are selected by default.

  6. Select Next to continue to the class creation page:

    "Creating a class in Qt Widgets Application Wizard"

  7. In the Base class field, enter QWidget as the base class type.
  8. Select the Lower case filenames check box to only use lower case characters in the names of the generated files.
  9. Select the Precompiled header check box to use a precompiled header file.
  10. Select the Add default application icon check box to use a default application icon for the application.
  11. Select Finish to create the project.

You now have a small working Qt application. Select Build > Build Solution to build it, and then select Debug > Start Without Debugging (or press Ctrl+F5) to run it. For now, the result is an empty window.

Design the Main Window

You can use Qt Designer to design the application's main window, which contains some widgets placed in layouts:

AddressBook's main dialog

By default, Qt Designer opens in Visual Studio. To open it as a stand-alone application, select Detach.

To run Qt Designer in a separate window by default, select Extensions > Qt VS Tools > Options > Qt Designer, and set Run in detached window to True.

For more information about using Qt Designer, see the Qt Designer Manual.

Add Widgets

To add widgets to the UI and to set properties for them:

  1. In Visual Studio's Solution Explorer, double-click the addressbook.ui file to open it in Qt Designer.
  2. In Qt Designer's Widget Box, select List Widget and drag and drop it to the form to add a QListWidget.
  3. In the Property Editor, set the ObjectName property to addressList.
  4. Drag and drop two Push Button widgets to the top-right corner of the form to add QPushButton objects for the Add and Delete buttons.
  5. Set the button names to addButton and deleteButton and text property values to Add and Delete.
  6. Drag and drop two Label widgets to the form to add QLabel objects for displaying the selected item in the list.
  7. Rename the first label to nameLabel and change its text property to <No item selected>.
  8. Rename the second label to emailLabel and leave its text property empty.

Position the widgets approximately as they appear in the screenshot above. In order to properly position the widgets and to ensure that they are resized correctly when the form is resized, you need to add layouts to the form.

Add Widgets to Layouts

You will need a vertical layout for the buttons as well as a spacer to push the buttons to the top of the layout. In addition, you will need a second layout to manage the positioning of the other widgets as well as the button layout.

To add wigdets to layouts:

  1. Drag a Vertical Spacer item to the form to add a spacer.
  2. Select the buttons and the spacer, and then select Form > Lay Out Vertically to add a vertical layout (QVBoxLayout).
  3. Select the list widgets, the two labels, and the button layout, and then select Form > Lay Out in a Grid to add a grid layout (QGridLayout).

    Note: 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.

  4. Select Form > Preview to preview your form without compiling it.
  5. Select File > Save to save the form.

Build and run the application to check the main window.

Add a Dialog

Now that the main window is ready, you can move on to add functionality to the application. To have the application open a dialog when the user clicks the Add button, you must create an Add Address dialog and invoke the dialog from a slot connected to the Add button.

You can use a Qt file wizard in Visual Studio to create a UI form that contains the OK and Cancel buttons connected to the QDialog::accept() and QDialog::reject() slots, respectively. You can use Qt Designer to add other widgets to the form.

Create the Dialog

To add a dialog to a project:

  1. In Visual Studio, select Project > Add New Item > Installed > Visual C++ > Qt > Qt Widgets Class.
  2. To acknowledge the Welcome dialog, select Next.
  3. In the Name field, enter AddDialog.

    "Creating a class in Qt Widgets Class Wizard"

  4. In the Base class field, enter QDialog as the base class type.
  5. Select the Multiple inheritance radio button.
  6. Select the Lower case filenames check box to only use lower case characters in the names of the generated files.
  7. Select Finish to create source, header, and UI files for the dialog.

Design the Dialog

Add Address Dialog

To design the dialog:

  1. In Visual Studio's Solution Explorer, double-click the adddialog.ui file to open it in Qt Designer.
  2. In Qt Designer, set Add Address as the windowTitle.
  3. Add a Label to the form and set its objectName property to nameText and text property to Name:.
  4. Add another Label and set its objectName property to emailText and text property to Email:.
  5. Add a Line Edit (QLineEdit) and set its objectName property to nameEdit. Leave the text property empty.
  6. Add another Line Edit and set its objectName property to emailEdit. Leave the text property empty.
  7. Select the labels and line edits, and then select Form > Lay Out in a Grid to add a grid layout.
  8. Add a Push Button and set its objectName property to okButton and text property to OK.
  9. Add a horizontal spacer to the left of the button.
  10. Add a horizontal layout for the spacer and the button.
  11. Add a vertical spacer between the labels and the button.
  12. Add a vertical layout for the labels and the spacer.
  13. Add a grid layout for both layouts.
  14. Select Form > Preview to preview your form without compiling it.
  15. Select File > Save to save the form.

Connect to the Dialog's OK Button

To have the OK button invoke the QDialog::accept() slot, click the Edit Signals/Slots toolbar button to enter Qt Designer's Signals and Slots Editing Mode.

Click the OK button, drag the mouse cursor to an empty area of the form, and release the mouse button. In the Configure Connection dialog, connect the button's QPushButton::clicked() signal to the form's QDialog::accept() slot.

Open Dialogs from the Main Window

To invoke the dialog when the user selects Add in the main window, you must add a slot to the AddressBook class and invoke AddDialog from this slot.

Forms that are 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>(). For the application to react appropriately when the Add button is clicked, you must implement a slot called on_addButton_clicked().

To implement the slot, open the addressbook.h file in Visual Studio and add a declaration for the slot:

private slots:
    void on_addButton_clicked();

Then open addressbook.cpp and add the slot definition:

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

To connect to some other signal, you must add the signal to the AddressBook class. This requires editing both the header file, addressbook.h, and the implementation file, addressbook.cpp.

Include adddialog.h to addressbook.cpp:

#include "adddialog.h"

To test your changes, build and run the application. Select the Add button to open the Add Address dialog, and then select OK to close it.

Add Items to the List Widget

When the user selects OK, an item should be added to the QListWidget. To implement this function, modify the code in the on_addButton_clicked() slot, as follows:

    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);
        }
    }

The dialog is executed. If the user accepts it by selecting OK, the Name and Email fields are extracted and a QListWidgetItem that contains the specified information is created.

Display the Selected Item

When the user selects an item in the list widget, the nameLabel and emailLabel at the bottom of the form should be updated. This behavior requires another slot to be added to the AddressBook class.

In the addressbook.h file, add the following code in the private slots section of the class:

    void on_addressList_currentItemChanged();

Then, add the block of code below 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 the QListWidget::currentItemChanged() signal of addressList and invoked whenever the selected item in the list changes.

Add Functionality for the Delete Button

To implement a slot for the Delete button, open the addressbook.h file in Visual Studio and add a declaration for the on_deleteButton_clicked() slot. Then open addressbook.cpp and add the slot definition for on_deleteButton_clicked().

Type the following code in the slot's body:

void AddressBook::on_deleteButton_clicked()
{
    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();
    }
}

Your application is now complete.

Create Qt Project Files

To build the application on other platforms, you need to create a .pro file for the project.

To let Qt VS Tools create a basic .pro file for you:

  1. Select Extensions > Qt VS Tools > Create Basic .pro File.
  2. In the Export Project dialog, make sure that the Create .pri file check box is selected, and then select OK.
  3. Select Save to use the default location and name for saving the .pri file.

For more information about .pro files and their associated .pri files, see Creating Projects.

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 platforms. However, for the example project, the generated .pro file is sufficient.

© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.