It also knows the type of the signal arguments so it can do the proper type conversion. We use ListLeft to only pass the same number as argument as the slot, which allows connecting a signal with many arguments to a slot with less arguments. QObject::connectImpl is the private internal function that will perform the connection. In this article, we will explore the mechanisms powering the Qt queued connections. Summary from Part 1. In the first part, we saw that signals are just simple functions, whose body is generated by moc. They are just calling QMetaObject::activate, with an array of pointers to arguments on the stack. Here is the code of a signal, as generated.
Classes- Annotated- Tree- Functions- Home- StructureQte |
Signals and slots are used for communication between objects. Thesignal/slot mechanism is a central feature of Qt and probably thepart that differs most from other toolkits.
- Abstract: A fundamental property of the Qt framework is the so called signals and slot mechanism. It is a generic event mechanism which is easy to use. By providing an interface of provided events.
- Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type. They are completely type safe.
- A slot is a function that is called in reponse to a particular signal. Qt's widgets have many pre-defined slots, but it is common practice to add your own slots so that you can handle the signals that you are interested in. The signals and slots mechanism is type safe: the signature of a signal must match the signature of the receiving slot.
In most GUI toolkits widgets have a callback for each action they cantrigger. This callback is a pointer to a function. In Qt, signals andslots have taken over from these messy function pointers.
Signals and slots can take any number of arguments of any type. They arecompletely typesafe: no more callback core dumps!
All classes that inherit from QObject or one of its subclasses(e.g. QWidget) can contain signals and slots. Signals are emitted byobjects when they change their state in a way that may be interestingto the outside world. This is all the object does to communicate. Itdoes not know if anything is receiving the signal at the other end.This is true information encapsulation, and ensures that the objectcan be used as a software component.
Slots can be used for receiving signals, but they are normal memberfunctions. A slot does not know if it has any signal(s) connected toit. Again, the object does not know about the communication mechanism andcan be used as a true software component.
You can connect as many signals as you want to a single slot, and asignal can be connected to as many slots as you desire. It is evenpossible to connect a signal directly to another signal. (This willemit the second signal immediately whenever the first is emitted.)
Together, signals and slots make up a powerful component programmingmechanism.
A Small Example
A minimal C++ class declaration might read:
A small Qt class might read:
This class has the same internal state, and public methods to access thestate, but in addition it has support for component programming usingsignals and slots: This class can tell the outside world that its statehas changed by emitting a signal, valueChanged()
, and it hasa slot which other objects may send signals to.
All classes that contain signals and/or slots must mention Q_OBJECT intheir declaration.
Slots are implemented by the application programmer (that's you).Here is a possible implementation of Foo::setValue():
The line emit valueChanged(v)
emits the signalvalueChanged
from the object. As you can see, you emit asignal by using emit signal(arguments)
.
Here is one way to connect two of these objects together:
Calling a.setValue(79)
will make a
emit asignal, which b
will receive,i.e. b.setValue(79)
is invoked. b
will in turnemit the same signal, which nobody receives, since no slot has beenconnected to it, so it disappears into hyperspace.
Note that the setValue()
function sets the value and emitsthe signal only if v != val
. This prevents infinite loopingin the case of cyclic connections (e.g. if b.valueChanged()
were connected to a.setValue()
).
Final cut steakhouse hollywood casino st louis. This example illustrates that objects can work together without knowingeach other, as long as there is someone around to set up a connectionbetween them initially.
The preprocessor changes or removes the signals
,slots
and emit
keywords so the compiler won'tsee anything it can't digest.
Run the moc on class definitions that containssignals or slots. This produces a C++ source file which should be compiledand linked with the other object files for the application.
Signals
Signals are emitted by an object when its internal state has changedin some way that might be interesting to the object's client or owner.Only the class that defines a signal and its subclasses can emit thesignal.
A list box, for instance, emits both highlighted()
andactivated()
signals. Most object will probably only beinterested in activated()
but some may want to know aboutwhich item in the list box is currently highlighted. If the signal isinteresting to two different objects you just connect the signal toslots in both objects.
When a signal is emitted, the slots connected to it are executedimmediately, just like a normal function call. The signal/slotmechanism is totally independent of any GUI event loop. Theemit
will return when all slots have returned.
If several slots are connected to one signal, the slots will beexecuted one after the other, in an arbitrary order, when the signalis emitted.
Signals are automatically generated by the moc and must not be implementedin the .cpp file. They can never have return types (i.e. use void).
A word about arguments: Our experience shows that signals and slotsare more reusable if they do not use special types. If QScrollBar::valueChanged() were to use a special type such as thehypothetical QRangeControl::Range, it could only be connected to slotsdesigned specifically for QRangeControl. Something as simple as theprogram in Tutorial 5 would be impossible.
Slots
A slot is called when a signal connected to it is emitted. Slots arenormal C++ functions and can be called normally; their only specialfeature is that signals can be connected to them. A slot's argumentscannot have default values, and as for signals, it is generally a badidea to use custom types for slot arguments.
Since slots are normal member functions with just a little extraspice, they have access rights like everyone else. A slot's accessright determines who can connect to it:
A public slots:
section contains slots that anyone canconnect signals to. This is very useful for component programming:You create objects that know nothing about each other, connect theirsignals and slots so information is passed correctly, and, like amodel railway, turn it on and leave it running.
Qt Signal Slot Parameter
A protected slots:
section contains slots that this classand its subclasses may connect signals to. This is intended forslots that are part of the class' implementation rather than itsinterface towards the rest of the world.
A private slots:
section contains slots that only theclass itself may connect signals to. This is intended for verytightly connected classes, where even subclasses aren't trusted to getthe connections right.
Of course, you can also define slots to be virtual. We have foundthis to be very useful.
Signals and slots are fairly efficient. Of course there's some loss ofspeed compared to 'real' callbacks due to the increased flexibility, butthe loss is fairly small, we measured it to approximately 10 microsecondson a i586-133 running Linux (less than 1 microsecond when no slot has beenconnected) , so the simplicity and flexibility the mechanism affords iswell worth it.
Meta Object Information
The meta object compiler (moc) parses the class declaration in a C++file and generates C++ code that initializes the meta object. The metaobject contains names of all signal and slot members, as well aspointers to these functions.
The meta object contains additional information such as the object's class name. You can also check if an objectinherits a specific class, for example:
A Real Example
Here is a simple commented example (code fragments from qlcdnumber.h ).
QLCDNumber inherits QObject, which has most of the signal/slotknowledge, via QFrame and QWidget, and #include's the relevantdeclarations.
Q_OBJECT is expanded by the preprocessor to declare several memberfunctions that are implemented by the moc; if you get compiler errorsalong the lines of 'virtual function QButton::className not defined'you have probably forgotten to run the moc or toinclude the moc output in the link command.
It's not obviously relevant to the moc, but if you inherit QWidget youalmost certainly want to have parent and namearguments to your constructors, and pass them to the parentconstructor.
Some destructors and member functions are omitted here, the mocignores member functions.
QLCDNumber emits a signal when it is asked to show an impossiblevalue.
'But I don't care about overflow,' or 'But I know the number won'toverflow.' Very well, then you don't connect the signal to any slot,and everything will be fine.
'But I want to call two different error functions when the numberoverflows.' Then you connect the signal to two different slots. Qtwill call both (in arbitrary order).
A slot is a receiving function, used to get information about statechanges in other widgets. QLCDNumber uses it, as you can see, to setthe displayed number. Since display()
is part of theclass' interface with the rest of the program, the slot is public.
Several of the example program connect the newValue signal of aQScrollBar to the display slot, so the LCD number continuously showsthe value of the scroll bar.
Note that display() is overloaded; Qt will select the appropriate versionwhen you connect a signal to the slot.With callbacks, you'd have to findfive different names and keep track of the types yourself.
Some more irrelevant member functions have been omitted from thisexample.
Moc output
This is really internal to Qt, but for the curious, here is the meatof the resulting mlcdnum.cpp:
That last line is because QLCDNumber inherits QFrame. The next part,which sets up the table/signal structures, has been deleted forbrevity.
One function is generated for each signal, and at present it almost alwaysis a single call to the internal Qt function activate_signal(), whichfinds the appropriate slot or slots and passes on the call. It is notrecommended to call activate_signal() directly.
Copyright © 2005 Trolltech | Trademarks |
Home > Articles > Programming > C/C++
␡- Subclassing QDialog
This chapter is from the book
This chapter is from the book
Qt Signal Slot Performance
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
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.
Qt Signal Slot Example
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 (, , 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 , 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 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 and using forward declarations for QCheckBox, QLabel, QLineEdit, and QPushButton, we could simply have included . 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
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.
Qt Signal Slot Example
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 (, , 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 , 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 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 and using forward declarations for QCheckBox, QLabel, QLineEdit, and QPushButton, we could simply have included . 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.
Qt Signals And Slots Tutorial
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:
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().
Qt Signal Slot Mechanism
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
- eBook (Watermarked) $25.59
- eBook (Watermarked) $28.79