Qt Signal Slot Different Class

PrevNextTable of Contents

It would be possible to have the slots to which the resized and moved signals are connected check the new position or size of the circle and respond accordingly, but it's more convenient and requires less knowledge of circles by the slot functions if the signal that is. Miso is short for mi cro s ignals and sl o ts and, as the name suggests, it is an implementation of the well-known language construct largely popularized by Qt: The signals and slots mechanism Wikipedia.As the Wikipedia article suggests, the signal-slot construct is a short, concise and pain-free implementation of the Observer pattern, ie. It provides the possibility for objects (called. Signals and slots is a language construct introduced in Qt for communication between objects which makes it easy to implement the observer pattern while avoiding boilerplate code.The concept is that GUI widgets can send signals containing event information which can be received by other widgets / controls using special functions known as slots. This is similar to C/C function pointers, but.

  • Qt signals and slots in different classes. Ask Question Asked 8 years, 5 months ago. Active 4 years, 7 months ago. Viewed 21k times 5. I have a class X with a slot, and a class Y with a signal. I'm setting up the connection from class X, and created a public method in class Y to emit the signal from class X (I'm not sure this step was.
  • Each PyQt widget, which is derived from QObject class, is designed to emit ‘ signal ’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘ slot ’. The slot can be any callable Python function.

The most important features of Qt are signals and slots.

Signals tell you that something has just happened. Signals are emitted (sent) when the user works with the computer. For example, when the user clicks the mouse or presses keys on a keyboard a signal is emitted. Signals can also be emitted when something happens inside the computer—when the clock ticks, for example.

Slots are the functions that respond to certain signals. It is important that your program responds to signals. Otherwise, it might look as if your program hangs. KDE programs don't—or shouldn't—hang!

Signals and slots are very object independent. Slots that handle a signal can be put in any object in your program. The object that sends the signal doesn't have to know anything about the slot or the object where the slot can be found. For example, you may have one window that contains a button and one window that contains a text box. You can let the text box respond to button clicks.

Slot

Signals and slots are primarily used for events handling, but you can use it for easy communication between objects too. When two windows need to communicate with each other, you can use signals and slots. Communication this way is much easier than doing it with pointers.

Event handling is solved by callbacks in many other toolkits. A callback is a pointer to a function. The widgets contain callbacks, pointers to functions, for each event. When an event occurs, the appropriate function is called. It is simple in theory, but it is hard in practice. The callbacks are not type safe, which means that it is easy to make mistakes. Callbacks also can't take any number of parameters of any type like signals and slots do.

3.3.1. Creating a Slot

Creating a slot is easy. Any class that inherits from QObject can have slots.

First you must enable signals and slots. In the class definition, add the word Q_OBJECT. This is a keyword, which the moc understands.

The slot is just a member function in your class, but you must declare it in a slots section. Slots can be public, private, or protected.

The following example shows a class with a slot:

The slot in the preceding class definition is called mySlot. The keyword before slots defines the access mode. The slot mySlot above is public.

You write the implementation for the slot as if it was a common member function. The following example shows you what a slot implementation may look like:

3.3.2. Emitting a Signal

When you want to tell Qt that an event has occurred, you emit a signal. When that happens, Qt executes all slots that are connected to the signal.

Before a signal can be emitted, it must be defined. The class that emits a signal must contain the signal definition. Signals are defined in a signals section in your class. The following class definition defines a signal:

Signals are emitted with the command emit. The signal may be emitted like so:

The example above is only a simple demonstration that shows you how it works.

3.3.3. Connecting a Slot to a Signal

To make a slot respond to a certain signal, you must connect them to each other. You can connect several slots to one signal.

It is very simple to connect a slot to a signal. The command connect does this. The syntax is simple:

The parameter startobject contains a pointer to the object that the signal comes from.

The parameter signal specifies what signal to handle. The signal must be emitted by the startobject.

The object which responds to a signal is specified in the parameter targetobject.

The slot which responds to the signal is specified in the parameter slot. The slot must be in the object specified by targetobject.

The following class demonstrates that several slots can be connected to the same signal, and one slot can be connected to several signals:

Example 3.4. buttons.h: Class Definition for the Class MyWindow

The listing below contains the class implementation:

Example 3.5. buttons.cc: Class Implementation for the Class MyWindow Declared in Listing 3.4

3.3.4. Signals and Slots with Parameters

During communication, it is sometimes useful to say more than 'Hey!' That is all that the preceding signals say.

If you need to say more, the simplest way is to use parameters in your signals and slots.

For example, you may have two windows both containing a button and a text box. When the user types in text and clicks the button in one window, the caption for the other window will change to whatever was typed in.

The solution is to use slots and signals with parameters. Give both the signal and slot a parameter that contains the new window caption. When you emit the signal you set this parameter.

The following example code shows how parameters work. The signal and slot are both in the same class, but of course that is not necessary:

The class constructor may connect the slot to the signal, like this:

The slot and the signal must have compatible parameters. In the preceding example, they each have one integer as a parameter.

It is easy to emit a signal with a parameter. The following function emits the signal changed(int i):

3.3.5. Slots in Temporary Classes

When a signal is emitted, the slots connected to it are activated.

Take a look at the following class constructor:

A button is created. The clicked() signal is connected to temp->slotTemp(). When you delete temp, the slot slotTemp() is also deleted. If the user clicks the button, an error will occur. Always consider this when you delete Qt objects.

PrevNextTable of Contents

Home > Articles > Programming > C/C++

  1. Subclassing QDialog
Page 1 of 6Next >
This chapter will teach you how to create dialog boxes using Qt.

Qt Signal Slot Different Classical

This chapter is from the book
C++ GUI Programming with Qt4, 2nd Edition
Signal

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.

Qt signal slot different classification

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

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:

Qt Signal Slot Different Class

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.

Qt Signal Slot Different Classic

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 Signal Slot Parameter

Visual C++'s output starts like this:

Qt Signals And Slots Tutorial

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.

Qt Connect Signal Slot Different Class

Related Resources

  • Book $31.99
  • eBook (Watermarked) $25.59

Qt Connect Signal Slot

  • eBook (Watermarked) $28.79