Create New Slot Qt Designer

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

Forms created with Qt Designer can be subclassed together with a standard QWidget-based class. This approach makes all the user interface components defined in the form directly accessible within the scope of the subclass, and enables signal and slot connections to be made in the usual way with the connect function. Jun 13, 2018  In this tutorial we create a GUI with Qt5's designer, take the ui file resulting from it, convert it to a py file with the pyuic5 utility, and add a custom slot.

To create a Qt VS Tools project, you must add at least one Qt version.

Select Tools > Extensions and Updates > Online to install or update Qt VS Tools.

Creating Qt GUI Application Projects

To create a Qt GUI application project in Visual Studio:

  1. Select New Project > Installed > Templates > Visual C++ > Qt > Qt GUI Application.
  2. In the Name field, enter AddressBook, and then select OK.
  3. To acknowledge the Welcome dialog, select Next.
  4. Select the modules to include in the project, and then select Next.

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

  5. In the Base class field, enter QWidget as the base class type.
  6. Select the Lower case filenames check box to only use lower case characters in the names of the generated files.
  7. Select the Precompiled header check box to use a precompiled header file.
  8. Select the Add default application icon check box to use a default application icon for the application.
  9. 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 Debugging to run it. For now, the result is an empty window.

Designing the Main Window

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

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

Adding 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 Widgetbox, 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.

Adding 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.

Adding Dialogs

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.

Creating the Dialog

To add a dialog to a project:

  1. In Visual Studio, select Project > Add Qt Class > Installed > Visual C++ > Qt > Qt GUI Class.
  2. In the Name field, enter AddDialog, and then select Add.
  3. To acknowledge the Welcome dialog, select Next.
  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.

Designing the 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.

Connecting 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.

Opening 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:

Then open addressbook.cpp and add the slot definition:

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:

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.

Adding 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:

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.

Displaying 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:

Then, add the block of code below to addressbook.cpp:

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.

Adding 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:

Your application is now complete.

Creating 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 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 Managing 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.

© 2016 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.

EnArBgDeElEsFaFiFrHiHuItJaKnKoMsNlPlPtRuSqThTrUkZh

This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt 5.

  • Differences between String-Based and Functor-Based Connections (Official documentation)
  • Introduction (Woboq blog)
  • Implementation Details (Woboq blog)

Note: This is in addition to the old string-based syntax which remains valid.

  • 1Connecting in Qt 5
  • 2Disconnecting in Qt 5
  • 4Error reporting
  • 5Open questions

Connecting in Qt 5

There are several ways to connect a signal in Qt 5.

Old syntax

Qt 5 continues to support the old string-based syntax for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget)

New: connecting to QObject member

Here's Qt 5's new way to connect two QObjects and pass non-string objects:

Pros

  • Compile time check of the existence of the signals and slot, of the types, or if the Q_OBJECT is missing.
  • Argument can be by typedefs or with different namespace specifier, and it works.
  • Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
  • It is possible to connect to any member function of QObject, not only slots.

Cons

  • More complicated syntax? (you need to specify the type of your object)
  • Very complicated syntax in cases of overloads? (see below)
  • Default arguments in slot is not supported anymore.

New: connecting to simple function

The new syntax can even connect to functions, not just QObjects:

Pros

  • Can be used with std::bind:
  • Can be used with C++11 lambda expressions:

Cons

How To Use Qt Designer

Designer
  • There is no automatic disconnection when the 'receiver' is destroyed because it's a functor with no QObject. However, since 5.2 there is an overload which adds a 'context object'. When that object is destroyed, the connection is broken (the context is also used for the thread affinity: the lambda will be called in the thread of the event loop of the object used as context).

Disconnecting in Qt 5

As you might expect, there are some changes in how connections can be terminated in Qt 5, too.

Old way

You can disconnect in the old way (using SIGNAL, SLOT) but only if

  • You connected using the old way, or
  • If you want to disconnect all the slots from a given signal using wild card character
How to use qt designer

Symetric to the function pointer one

Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card)In particular, does not work with static function, functors or lambda functions.

New way using QMetaObject::Connection

Works in all cases, including lambda functions or functors.

Asynchronous made easier

With C++11 it is possible to keep the code inline

Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:

Another example using QHttpServer : http://pastebin.com/pfbTMqUm

Error reporting

Tested with GCC.

Fortunately, IDEs like Qt Creator simplifies the function naming

Missing Q_OBJECT in class definition

Type mismatch

Open questions

Qt Designer Download

Default arguments in slot

If you have code like this:

The old method allows you to connect that slot to a signal that does not have arguments.But I cannot know with template code if a function has default arguments or not.So this feature is disabled.

There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal.This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.

Overload

As you might see in the example above, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting, e.g. a connection that previously was made as follows:

cannot be simply converted to:

...because QSpinBox has two signals named valueChanged() with different arguments. Instead, the new code needs to be:

Unfortunately, using an explicit cast here allows several types of errors to slip past the compiler. Adding a temporary variable assignment preserves these compile-time checks:

Some macro could help (with C++11 or typeof extensions). A template based solution was introduced in Qt 5.7: qOverload

The best thing is probably to recommend not to overload signals or slots …

… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.

Disconnect

Should QMetaObject::Connection have a disconnect() function?

The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that takes a closure.One could add a list of objects in the disconnection, or a new function like QMetaObject::Connection::require


Callbacks

Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot.This does not work for the new method.If one wants to do callback C++ way, one should use std::functionBut we cannot use STL types in our ABI, so a QFunction should be done to copy std::function.In any case, this is irrelevant for QObject connections.

Retrieved from 'https://wiki.qt.io/index.php?title=New_Signal_Slot_Syntax&oldid=34943'