Qt Connect Slot With Arguments

Posted on  by 

I connect the signal to a method in the usual way. To use the argument, I merely need to specify the argument in the method definition. What often confuses me is that I don't need to specify arguments in the connect statement. The example below emits a signal didSomething and passes two arguments, 'important' and 'information' to the update.

  1. Qt Connect Slot To Slot
  2. Qt Connect Multiple Signals To One Slot
  3. Qt Connect
Qt Connect Slot With Arguments

One of the key features of Qt is its use of signals and slots to communicatebetween objects. Their use encourages the development of reusable components.

A signal is emitted when something of potential interest happens. A slot is aPython callable. If a signal is connected to a slot then the slot is calledwhen the signal is emitted. If a signal isn’t connected then nothing happens.The code (or component) that emits the signal does not know or care if thesignal is being used.

The signal/slot mechanism has the following features.

  • A signal may be connected to many slots.

  • A signal may also be connected to another signal.

  • Signal arguments may be any Python type.

  • A slot may be connected to many signals.

  • Connections may be direct (ie. synchronous) or queued (ie. asynchronous).

  • Connections may be made across threads.

  • Signals may be disconnected.

Unbound and Bound Signals¶

A signal (specifically an unbound signal) is a class attribute. When a signalis referenced as an attribute of an instance of the class then PyQt5automatically binds the instance to the signal in order to create a boundsignal. This is the same mechanism that Python itself uses to create boundmethods from class functions.

A bound signal has connect(), disconnect() and emit() methods thatimplement the associated functionality. It also has a signal attributethat is the signature of the signal that would be returned by Qt’s SIGNAL()macro.

A signal may be overloaded, ie. a signal with a particular name may supportmore than one signature. A signal may be indexed with a signature in order toselect the one required. A signature is a sequence of types. A type is eithera Python type object or a string that is the name of a C++ type. The name of aC++ type is automatically normalised so that, for example, QVariant can beused instead of the non-normalised constQVariant&.

If a signal is overloaded then it will have a default that will be used if noindex is given.

When a signal is emitted then any arguments are converted to C++ types ifpossible. If an argument doesn’t have a corresponding C++ type then it iswrapped in a special C++ type that allows it to be passed around Qt’s meta-typesystem while ensuring that its reference count is properly maintained.

Defining New Signals with pyqtSignal¶

PyQt5 automatically defines signals for all Qt’s built-in signals. New signalscan be defined as class attributes using thepyqtSignal factory.

PyQt5.QtCore.pyqtSignal(types[, name[, revision=0[, arguments=[]]]])

Create one or more overloaded unbound signals as a class attribute.

Parameters
  • types – the types that define the C++ signature of the signal. Each type maybe a Python type object or a string that is the name of a C++ type.Alternatively each may be a sequence of type arguments. In this caseeach sequence defines the signature of a different signal overload.The first overload will be the default.

  • name – the name of the signal. If it is omitted then the name of the classattribute is used. This may only be given as a keyword argument.

  • revision – the revision of the signal that is exported to QML. This may only begiven as a keyword argument.

  • arguments – the sequence of the names of the signal’s arguments that is exported toQML. This may only be given as a keyword argument.

Return type

an unbound signal

The following example shows the definition of a number of new signals:

New signals should only be defined in sub-classes ofQObject. They must be part of the class definitionand cannot be dynamically added as class attributes after the class has beendefined.

New signals defined in this way will be automatically added to the class’sQMetaObject. This means that they will appear in QtDesigner and can be introspected using theQMetaObject API.

Overloaded signals should be used with care when an argument has a Python typethat has no corresponding C++ type. PyQt5 uses the same internal C++ class torepresent such objects and so it is possible to have overloaded signals withdifferent Python signatures that are implemented with identical C++ signatureswith unexpected results. The following is an example of this:

Connecting, Disconnecting and Emitting Signals¶

Signals are connected to slots using the connect() method of a boundsignal.

connect(slot[, type=PyQt5.QtCore.Qt.AutoConnection[, no_receiver_check=False]]) → PyQt5.QtCore.QMetaObject.Connection¶

Connect a signal to a slot. An exception will be raised if the connectionfailed.

Parameters
  • slot – the slot to connect to, either a Python callable or another boundsignal.

  • type – the type of the connection to make.

  • no_receiver_check – suppress the check that the underlying C++ receiver instance stillexists and deliver the signal anyway.

Returns

a Connection object which can bepassed to disconnect(). This is the only way to disconnect aconnection to a lambda function.

Signals are disconnected from slots using the disconnect() method of abound signal.

disconnect([slot])

Disconnect one or more slots from a signal. An exception will be raised ifthe slot is not connected to the signal or if the signal has no connectionsat all.

Parameters

slot – the optional slot to disconnect from, either aConnection object returned byconnect(), a Python callable or another bound signal. If it isomitted then all slots connected to the signal are disconnected.

Signals are emitted from using the emit() method of a bound signal.

emit(*args)

Emit a signal.

Parameters

args – the optional sequence of arguments to pass to any connected slots.

The following code demonstrates the definition, connection and emit of asignal without arguments:

The following code demonstrates the connection of overloaded signals:

Connecting Signals Using Keyword Arguments¶

It is also possible to connect signals by passing a slot as a keyword argumentcorresponding to the name of the signal when creating an object, or using thepyqtConfigure() method. For example the followingthree fragments are equivalent:

The pyqtSlot() Decorator¶

Although PyQt5 allows any Python callable to be used as a slot when connectingsignals, it is sometimes necessary to explicitly mark a Python method as beinga Qt slot and to provide a C++ signature for it. PyQt5 provides thepyqtSlot() function decorator to do this.

PyQt5.QtCore.pyqtSlot(types[, name[, result[, revision=0]]])

Decorate a Python method to create a Qt slot.

Parameters
  • types – the types that define the C++ signature of the slot. Each type may bea Python type object or a string that is the name of a C++ type.

  • name – the name of the slot that will be seen by C++. If omitted the name ofthe Python method being decorated will be used. This may only be givenas a keyword argument.

  • revision – the revision of the slot that is exported to QML. This may only begiven as a keyword argument.

  • result – the type of the result and may be a Python type object or a string thatspecifies a C++ type. This may only be given as a keyword argument.

Connecting a signal to a decorated Python method also has the advantage ofreducing the amount of memory used and is slightly faster.

For example:

It is also possible to chain the decorators in order to define a Python methodseveral times with different signatures. For example:

The PyQt_PyObject Signal Argument Type¶

It is possible to pass any Python object as a signal argument by specifyingPyQt_PyObject as the type of the argument in the signature. For example:

This would normally be used for passing objects where the actual Python typeisn’t known. It can also be used to pass an integer, for example, so that thenormal conversions from a Python object to a C++ integer and back again are notrequired.

The reference count of the object being passed is maintained automatically.There is no need for the emitter of a signal to keep a reference to the objectafter the call to finished.emit(), even if a connection is queued.

Connecting Slots By Name¶

PyQt5 supports the connectSlotsByName() functionthat is most commonly used by pyuic5 generated Python code toautomatically connect signals to slots that conform to a simple namingconvention. However, where a class has overloaded Qt signals (ie. with thesame name but with different arguments) PyQt5 needs additional information inorder to automatically connect the correct signal.

For example the QSpinBox class has the followingsignals:

When the value of the spin box changes both of these signals will be emitted.If you have implemented a slot called on_spinbox_valueChanged (whichassumes that you have given the QSpinBox instancethe name spinbox) then it will be connected to both variations of thesignal. Therefore, when the user changes the value, your slot will be calledtwice - once with an integer argument, and once with a string argument.

The pyqtSlot() decorator can be used to specify which ofthe signals should be connected to the slot.

For example, if you were only interested in the integer variant of the signalthen your slot definition would look like the following:

If you wanted to handle both variants of the signal, but with different Pythonmethods, then your slot definitions might look like the following:

Home > Articles > Programming > C/C++

  1. Subclassing QDialog
Page 1 of 6Next >
This chapter will teach you how to create dialog boxes using Qt.
This chapter is from the book
C++ GUI Programming with Qt4, 2nd Edition

This chapter is from the book

This chapter is from the book

2. Creating Dialogs

  • Subclassing QDialog
  • Signals and Slots in Depth
  • Rapid Dialog Design
  • Shape-Changing Dialogs
  • Dynamic Dialogs
  • Built-in Widget and Dialog Classes

This chapter will teach you how to create dialog boxes using Qt. Dialog boxes present users with options and choices, and allow them to set the options to their preferred values and to make their choices. They are called dialog boxes, or simply 'dialogs', because they provide a means by which users and applications can 'talk to' each other.

Most GUI applications consist of a main window with a menu bar and toolbar, along with dozens of dialogs that complement the main window. It is also possible to create dialog applications that respond directly to the user's choices by performing the appropriate actions (e.g., a calculator application).

We will create our first dialog purely by writing code to show how it is done. Then we will see how to build dialogs using Qt Designer, Qt's visual design tool. Using Qt Designer is a lot faster than hand-coding and makes it easy to test different designs and to change designs later.

Subclassing QDialog

Qt Connect Slot To Slot

Our first example is a Find dialog written entirely in C++. It is shown in Figure 2.1. We will implement the dialog as a class in its own right. By doing so, we make it an independent, self-contained component, with its own signals and slots.

Figure 2.1 The Find dialog

The source code is spread across two files: finddialog.h and finddialog.cpp. We will start with finddialog.h.

Lines 1 and 2 (and 27) protect the header file against multiple inclusions.

Line 3 includes the definition of QDialog, the base class for dialogs in Qt. QDialog is derived from QWidget.

Lines 4 to 7 are forward declarations of the Qt classes that we will use to implement the dialog. A forward declaration tells the C++ compiler that a class exists, without giving all the detail that a class definition (usually located in a header file of its own) provides. We will say more about this shortly.

Next, we define FindDialog as a subclass of QDialog:

The Q_OBJECT macro at the beginning of the class definition is necessary for all classes that define signals or slots.

The FindDialog constructor is typical of Qt widget classes. The parent parameter specifies the parent widget. The default is a null pointer, meaning that the dialog has no parent.

The signals section declares two signals that the dialog emits when the user clicks the Find button. If the Search backward option is enabled, the dialog emits findPrevious(); otherwise, it emits findNext().

The signals keyword is actually a macro. The C++ preprocessor converts it into standard C++ before the compiler sees it. Qt::CaseSensitivity is an enum type that can take the values Qt::CaseSensitive and Qt::CaseInsensitive.

In the class's private section, we declare two slots. To implement the slots, we will need to access most of the dialog's child widgets, so we keep pointers to them as well. The slots keyword is, like signals, a macro that expands into a construct that the C++ compiler can digest.

For the private variables, we used forward declarations of their classes. This was possible because they are all pointers and we don't access them in the header file, so the compiler doesn't need the full class definitions. We could have included the relevant header files (<QCheckBox>, <QLabel>, etc.), but using forward declarations when it is possible makes compiling somewhat faster.

We will now look at finddialog.cpp, which contains the implementation of the FindDialog class.

First, we include <QtGui>, a header file that contains the definition of Qt's GUI classes. Qt consists of several modules, each of which lives in its own library. The most important modules are QtCore, QtGui, QtNetwork, QtOpenGL, QtScript, QtSql, QtSvg, and QtXml. The <QtGui> header file contains the definition of all the classes that are part of the QtCore and QtGui modules. Including this header saves us the bother of including every class individually.

In finddialog.h, instead of including <QDialog> and using forward declarations for QCheckBox, QLabel, QLineEdit, and QPushButton, we could simply have included <QtGui>. However, it is generally bad style to include such a big header file from another header file, especially in larger applications.

On line 4, we pass on the parent parameter to the base class constructor. Then we create the child widgets. The tr() function calls around the string literals mark them for translation to other languages. The function is declared in QObject and every subclass that contains the Q_OBJECT macro. It's a good habit to surround user-visible strings with tr(), even if you don't have immediate plans for translating your applications to other languages. We cover translating Qt applications in Chapter 18.

In the string literals, we use ampersands ('&') to indicate shortcut keys. For example, line 11 creates a Find button, which the user can activate by pressing Alt+F on platforms that support shortcut keys. Ampersands can also be used to control focus: On line 6 we create a label with a shortcut key (Alt+W), and on line 8 we set the label's buddy to be the line editor. A buddy is a widget that accepts the focus when the label's shortcut key is pressed. So when the user presses Alt+W (the label's shortcut), the focus goes to the line editor (the label's buddy).

On line 12, we make the Find button the dialog's default button by calling setDefault(true). The default button is the button that is pressed when the user hits Enter. On line 13, we disable the Find button. When a widget is disabled, it is usually shown grayed out and will not respond to user interaction.

The private slot enableFindButton(const QString &) is called whenever the text in the line editor changes. The private slot findClicked() is called when the user clicks the Find button. The dialog closes itself when the user clicks Close. The close() slot is inherited from QWidget, and its default behavior is to hide the widget from view (without deleting it). We will look at the code for the enableFindButton() and findClicked() slots later on.

Since QObject is one of FindDialog's ancestors, we can omit the QObject:: prefix in front of the connect() calls.

Next, we lay out the child widgets using layout managers. Layouts can contain both widgets and other layouts. By nesting QHBoxLayouts, QVBoxLayouts, and QGridLayouts in various combinations, it is possible to build very sophisticated dialogs.

For the Find dialog, we use two QHBoxLayouts and two QVBoxLayouts, as shown in Figure 2.2. The outer layout is the main layout; it is installed on the FindDialog on line 35 and is responsible for the dialog's entire area. The other three layouts are sub-layouts. The little 'spring' at the bottom right of Figure 2.2 is a spacer item (or 'stretch'). It uses up the empty space below the Find and Close buttons, ensuring that these buttons occupy the top of their layout.

One subtle aspect of the layout manager classes is that they are not widgets. Instead, they are derived from QLayout, which in turn is derived from QObject. In the figure, widgets are represented by solid outlines and layouts are represented by dashed outlines to highlight the difference between them. In a running application, layouts are invisible.

When the sublayouts are added to the parent layout (lines 25, 33, and 34), the sublayouts are automatically reparented. Then, when the main layout is installed on the dialog (line 35), it becomes a child of the dialog, and all the widgets in the layouts are reparented to become children of the dialog. The resulting parent–child hierarchy is depicted in Figure 2.3.

Figure 2.3 The Find dialog's parent–child relationships

Finally, we set the title to be shown in the dialog's title bar and we set the window to have a fixed height, since there aren't any widgets in the dialog that can meaningfully occupy any extra vertical space. The QWidget::sizeHint() function returns a widget's 'ideal' size.

This completes the review of FindDialog's constructor. Since we used new to create the dialog's widgets and layouts, it would seem that we need to write a destructor that calls delete on each widget and layout we created. But this isn't necessary, since Qt automatically deletes child objects when the parent is destroyed, and the child widgets and layouts are all descendants of the FindDialog.

Now we will look at the dialog's slots:

The findClicked() slot is called when the user clicks the Find button. It emits the findPrevious() or the findNext() signal, depending on the Search backward option. The emit keyword is specific to Qt; like other Qt extensions it is converted into standard C++ by the C++ preprocessor.

The enableFindButton() slot is called whenever the user changes the text in the line editor. It enables the button if there is some text in the editor, and disables it otherwise.

These two slots complete the dialog. We can now create a main.cpp file to test our FindDialog widget:

To compile the program, run qmake as usual. Since the FindDialog class definition contains the Q_OBJECT macro, the makefile generated by qmake will include special rules to run moc, Qt's meta-object compiler. (We cover Qt's meta-object system in the next section.)

For moc to work correctly, we must put the class definition in a header file, separate from the implementation file. The code generated by moc includes this header file and adds some C++ boilerplate code of its own.

Classes that use the Q_OBJECT macro must have moc run on them. This isn't a problem because qmake automatically adds the necessary rules to the makefile. But if you forget to regenerate your makefile using qmake and moc isn't run, the linker will complain that some functions are declared but not implemented. The messages can be fairly obscure. GCC produces error messages like this one:

Qt Connect Multiple Signals To One Slot

Visual C++'s output starts like this:

If this ever happens to you, run qmake again to update the makefile, then rebuild the application.

Now run the program. If shortcut keys are shown on your platform, verify that the shortcut keys Alt+W, Alt+C, Alt+B, and Alt+F trigger the correct behavior. Press Tab to navigate through the widgets with the keyboard. The default tab order is the order in which the widgets were created. This can be changed using QWidget::setTabOrder().

Providing a sensible tab order and keyboard shortcuts ensures that users who don't want to (or cannot) use a mouse are able to make full use of the application. Full keyboard control is also appreciated by fast typists.

In Chapter 3, we will use the Find dialog inside a real application, and we will connect the findPrevious() and findNext() signals to some slots.

Related Resources

  • Book $31.99
  • Book $35.99

Qt Connect

  • Book $43.99

Coments are closed