Qt Designer Connect Signal Slot
Qt Designer UI files represent the widget tree of the form in XML format. The forms can be processed:
Qt documentation: Multi window signal slot connection. A simple multiwindow example using signals and slots. There is a MainWindow class that controls the Main Window view. Oct 22, 2012 Python GUI Development with Qt - QtDesigner's Signal-Slot Editor, Tab Order Management - Video 12. We learn a bit more about Qt Designer and its abilities to handle Signals and Slots, as well. Sep 15, 2016 Qt Tutorials For Beginners – Adding Click Event to QPushbutton Example September 15, 2016 admin Qt 1 In this post we will see how to add the click event to the QPushbutton with an example. In this article, I will demonstrate to you two types of demos that are how we can make a signal & slot operation and simple progress bar for Python applications by using PyQt5 (Qt designer) GUI toolkit.
- At compile time, which means that forms are converted to C++ code that can be compiled.
- At runtime, which means that forms are processed by the QUiLoader class that dynamically constructs the widget tree while parsing the XML file.
Compile Time Form Processing
You create user interface components with Qt Designer and use Qt's integrated build tools, qmake and uic, to generate code for them when the application is built. The generated code contains the form's user interface object. It is a C++ struct that contains:
- Pointers to the form's widgets, layouts, layout items, button groups, and actions.
- A member function called
setupUi()
to build the widget tree on the parent widget. - A member function called
retranslateUi()
that handles the translation of the string properties of the form. For more information, see Reacting to Language Changes.
The generated code can be included in your application and used directly from it. Alternatively, you can use it to extend subclasses of standard widgets.
A compile time processed form can be used in your application with one of the following approaches:
- The Direct Approach: you construct a widget to use as a placeholder for the component, and set up the user interface inside it.
- The Single Inheritance Approach: you subclass the form's base class (QWidget or QDialog, for example), and include a private instance of the form's user interface object.
- The Multiple Inheritance Approach: you subclass both the form's base class and the form's user interface object. This allows the widgets defined in the form to be used directly from within the scope of the subclass.
To demonstrate, we create a simple Calculator Form application. It is based on the original Calculator Form example.
The application consists of one source file, main.cpp
and a UI file.
The calculatorform.ui
file designed with Qt Designer is shown below:
We will use qmake
to build the executable, so we need to write a .pro
file:
The special feature of this file is the FORMS
declaration that tells qmake
which files to process with uic
. In this case, the calculatorform.ui
file is used to create a ui_calculatorform.h
file that can be used by any file listed in the SOURCES
declaration.
Note: You can use Qt Creator to create the Calculator Form project. It automatically generates the main.cpp, UI, and .pro files, which you can then modify.
The Direct Approach
To use the direct approach, we include the ui_calculatorform.h
file directly in main.cpp
:
The main
function creates the calculator widget by constructing a standard QWidget that we use to host the user interface described by the calculatorform.ui
file.
In this case, the Ui::CalculatorForm
is an interface description object from the ui_calculatorform.h
file that sets up all the dialog's widgets and the connections between its signals and slots.
The direct approach provides a quick and easy way to use simple, self-contained components in your applications. However, componens created with Qt Designer often require close integration with the rest of the application code. For instance, the CalculatorForm
code provided above will compile and run, but the QSpinBox objects will not interact with the QLabel as we need a custom slot to carry out the add operation and display the result in the QLabel. To achieve this, we need to use the single inheritance approach.
The Single Inheritance Approach
To use the single inheritance approach, we subclass a standard Qt widget and include a private instance of the form's user interface object. This can take the form of:
- A member variable
- A pointer member variable
Using a Member Variable
In this approach, we subclass a Qt widget and set up the user interface from within the constructor. Components used in this way expose the widgets and layouts used in the form to the Qt widget subclass, and provide a standard system for making signal and slot connections between the user interface and other objects in your application. The generated Ui::CalculatorForm
structure is a member of the class.
This approach is used in the Calculator Form example.
To ensure that we can use the user interface, we need to include the header file that uic
generates before referring to Ui::CalculatorForm
:
This means that the .pro
file must be updated to include calculatorform.h
:
The subclass is defined in the following way:
The important feature of the class is the private ui
object which provides the code for setting up and managing the user interface.
The constructor for the subclass constructs and configures all the widgets and layouts for the dialog just by calling the ui
object's setupUi()
function. Once this has been done, it is possible to modify the user interface as needed.
We can connect signals and slots in user interface widgets in the usual way by adding the on_<object name> - prefix. For more information, see widgets-and-dialogs-with-auto-connect.
The advantages of this approach are its simple use of inheritance to provide a QWidget-based interface, and its encapsulation of the user interface widget variables within the ui
data member. We can use this method to define a number of user interfaces within the same widget, each of which is contained within its own namespace, and overlay (or compose) them. This approach can be used to create individual tabs from existing forms, for example.
Using a Pointer Member Variable
Alternatively, the Ui::CalculatorForm
structure can be made a pointer member of the class. The header then looks as follows: Sterling heights mi news.
The corresponding source file looks as follows:
The advantage of this approach is that the user interface object can be forward-declared, which means that we do not have to include the generated ui_calculatorform.h
file in the header. The form can then be changed without recompiling the dependent source files. This is particularly important if the class is subject to binary compatibility restrictions.
We generally recommend this approach for libraries and large applications. For more information, see Creating Shared Libraries.
The Multiple Inheritance Approach
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.
This approach is used in the Multiple Inheritance example.
We need to include the header file that uic
generates from the calculatorform.ui
file, as follows:
The class is defined in a similar way to the one used in the single inheritance approach, except that this time we inherit from bothQWidget and Ui::CalculatorForm
, as follows:
We inherit Ui::CalculatorForm
privately to ensure that the user interface objects are private in our subclass. We can also inherit it with the public
or protected
keywords in the same way that we could have made ui
public or protected in the previous case.
The constructor for the subclass performs many of the same tasks as the constructor used in the single inheritance example:
In this case, the widgets used in the user interface can be accessed in the same say as a widget created in code by hand. We no longer require the ui
prefix to access them.
Reacting to Language Changes
Qt notifies applications if the user interface language changes by sending an event of the type QEvent::LanguageChange. To call the member function retranslateUi()
of the user interface object, we reimplement QWidget::changeEvent()
in the form class, as follows:
Run Time Form Processing
Alternatively, forms can be processed at run time, producing dynamically- generated user interfaces. This can be done using the QtUiTools module that provides the QUiLoader class to handle forms created with Qt Designer.
The UiTools Approach
A resource file containing a UI file is required to process forms at run time. Also, the application needs to be configured to use the QtUiTools module. This is done by including the following declaration in a qmake
project file, ensuring that the application is compiled and linked appropriately.
The QUiLoader class provides a form loader object to construct the user interface. This user interface can be retrieved from any QIODevice, e.g., a QFile object, to obtain a form stored in a project's resource file. The QUiLoader::load() function constructs the form widget using the user interface description contained in the file.
The QtUiTools module classes can be included using the following directive:
The QUiLoader::load() function is invoked as shown in this code from the Text Finder example:
In a class that uses QtUiTools to build its user interface at run time, we can locate objects in the form using QObject::findChild(). For example, in the following code, we locate some components based on their object names and widget types:
Processing forms at run-time gives the developer the freedom to change a program's user interface, just by changing the UI file. This is useful when customizing programs to suit various user needs, such as extra large icons or a different colour scheme for accessibility support.
Automatic Connections
The signals and slots connections defined for compile time or run time forms can either be set up manually or automatically, using QMetaObject's ability to make connections between signals and suitably-named slots.
Generally, in a QDialog, if we want to process the information entered by the user before accepting it, we need to connect the clicked() signal from the OK button to a custom slot in our dialog. We will first show an example of the dialog in which the slot is connected by hand then compare it with a dialog that uses automatic connection.
A Dialog Without Auto-Connect
We define the dialog in the same way as before, but now include a slot in addition to the constructor:
The checkValues()
slot will be used to validate the values provided by the user.
In the dialog's constructor we set up the widgets as before, and connect the Cancel button's clicked() signal to the dialog's reject() slot. We also disable the autoDefault property in both buttons to ensure that the dialog does not interfere with the way that the line edit handles return key events:
We connect the OK button's clicked() signal to the dialog's checkValues() slot which we implement as follows:
This custom slot does the minimum necessary to ensure that the data entered by the user is valid - it only accepts the input if a name was given for the image.
Widgets and Dialogs with Auto-Connect
Although it is easy to implement a custom slot in the dialog and connect it in the constructor, we could instead use QMetaObject's auto-connection facilities to connect the OK button's clicked() signal to a slot in our subclass. uic
automatically generates code in the dialog's setupUi()
function to do this, so we only need to declare and implement a slot with a name that follows a standard convention:
Using this convention, we can define and implement a slot that responds to mouse clicks on the OK button:
Another example of automatic signal and slot connection would be the Text Finder with its on_findButton_clicked()
slot.
We use QMetaObject's system to enable signal and slot connections:
This enables us to implement the slot, as shown below:
Automatic connection of signals and slots provides both a standard naming convention and an explicit interface for widget designers to work to. By providing source code that implements a given interface, user interface designers can check that their designs actually work without having to write code themselves.
© 2020 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
- 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
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:
Qt Connect Signal To Signal
Another example using QHttpServer : http://pastebin.com/pfbTMqUm
Error reporting
Tested with GCC.
Fortunately, IDEs like Qt Creator simplifies the function naming
Qt Signal Slot Connect
Missing Q_OBJECT in class definition
Type mismatch
Open questions
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:
Signal And Slot
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.