Move the module qdoc files from qtdoc and split up doc/src.
[profile/ivi/qtbase.git] / doc / src / core / objectmodel / signalsandslots.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the documentation of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:FDL$
10 ** GNU Free Documentation License
11 ** Alternatively, this file may be used under the terms of the GNU Free
12 ** Documentation License version 1.3 as published by the Free Software
13 ** Foundation and appearing in the file included in the packaging of
14 ** this file.
15 **
16 ** Other Usage
17 ** Alternatively, this file may be used in accordance with the terms
18 ** and conditions contained in a signed written agreement between you
19 ** and Nokia.
20 **
21 **
22 **
23 **
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29     \page signalsandslots.html
30     \title Signals & Slots
31     \ingroup qt-basic-concepts
32     \brief An overview of Qt's signals and slots inter-object
33     communication mechanism.
34
35     Signals and slots are used for communication between objects. The
36     signals and slots mechanism is a central feature of Qt and
37     probably the part that differs most from the features provided by
38     other frameworks.
39
40     \tableofcontents
41
42     \section1 Introduction
43
44     In GUI programming, when we change one widget, we often want
45     another widget to be notified. More generally, we want objects of
46     any kind to be able to communicate with one another. For example,
47     if a user clicks a \gui{Close} button, we probably want the
48     window's \l{QWidget::close()}{close()} function to be called.
49
50     Older toolkits achieve this kind of communication using
51     callbacks. A callback is a pointer to a function, so if you want
52     a processing function to notify you about some event you pass a
53     pointer to another function (the callback) to the processing
54     function. The processing function then calls the callback when
55     appropriate. Callbacks have two fundamental flaws: Firstly, they
56     are not type-safe. We can never be certain that the processing
57     function will call the callback with the correct arguments.
58     Secondly, the callback is strongly coupled to the processing
59     function since the processing function must know which callback
60     to call.
61
62     \section1 Signals and Slots
63
64     In Qt, we have an alternative to the callback technique: We use
65     signals and slots. A signal is emitted when a particular event
66     occurs. Qt's widgets have many predefined signals, but we can
67     always subclass widgets to add our own signals to them. A slot
68     is a function that is called in response to a particular signal.
69     Qt's widgets have many pre-defined slots, but it is common
70     practice to subclass widgets and add your own slots so that you
71     can handle the signals that you are interested in.
72
73     \img abstract-connections.png
74     \omit
75     \caption An abstract view of some signals and slots connections
76     \endomit
77
78     The signals and slots mechanism is type safe: The signature of a
79     signal must match the signature of the receiving slot. (In fact a
80     slot may have a shorter signature than the signal it receives
81     because it can ignore extra arguments.) Since the signatures are
82     compatible, the compiler can help us detect type mismatches.
83     Signals and slots are loosely coupled: A class which emits a
84     signal neither knows nor cares which slots receive the signal.
85     Qt's signals and slots mechanism ensures that if you connect a
86     signal to a slot, the slot will be called with the signal's
87     parameters at the right time. Signals and slots can take any
88     number of arguments of any type. They are completely type safe.
89
90     All classes that inherit from QObject or one of its subclasses
91     (e.g., QWidget) can contain signals and slots. Signals are emitted by
92     objects when they change their state in a way that may be interesting
93     to other objects. This is all the object does to communicate. It
94     does not know or care whether anything is receiving the signals it
95     emits. This is true information encapsulation, and ensures that the
96     object can be used as a software component.
97
98     Slots can be used for receiving signals, but they are also normal
99     member functions. Just as an object does not know if anything receives
100     its signals, a slot does not know if it has any signals connected to
101     it. This ensures that truly independent components can be created with
102     Qt.
103
104     You can connect as many signals as you want to a single slot, and a
105     signal can be connected to as many slots as you need. It is even
106     possible to connect a signal directly to another signal. (This will
107     emit the second signal immediately whenever the first is emitted.)
108
109     Together, signals and slots make up a powerful component programming
110     mechanism.
111
112     \section1 A Small Example
113
114     A minimal C++ class declaration might read:
115
116     \snippet doc/src/snippets/signalsandslots/signalsandslots.h 0
117
118     A small QObject-based class might read:
119
120     \snippet doc/src/snippets/signalsandslots/signalsandslots.h 1
121     \codeline
122     \snippet doc/src/snippets/signalsandslots/signalsandslots.h 2
123     \snippet doc/src/snippets/signalsandslots/signalsandslots.h 3
124
125     The QObject-based version has the same internal state, and provides
126     public methods to access the state, but in addition it has support
127     for component programming using signals and slots. This class can
128     tell the outside world that its state has changed by emitting a
129     signal, \c{valueChanged()}, and it has a slot which other objects
130     can send signals to.
131
132     All classes that contain signals or slots must mention
133     Q_OBJECT at the top of their declaration. They must also derive
134     (directly or indirectly) from QObject.
135
136     Slots are implemented by the application programmer.
137     Here is a possible implementation of the \c{Counter::setValue()}
138     slot:
139
140     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 0
141
142     The \c{emit} line emits the signal \c valueChanged() from the
143     object, with the new value as argument.
144
145     In the following code snippet, we create two \c Counter objects
146     and connect the first object's \c valueChanged() signal to the
147     second object's \c setValue() slot using QObject::connect():
148
149     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 1
150     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 2
151     \codeline
152     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 3
153     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 4
154
155     Calling \c{a.setValue(12)} makes \c{a} emit a
156     \c{valueChanged(12)} signal, which \c{b} will receive in its
157     \c{setValue()} slot, i.e. \c{b.setValue(12)} is called. Then
158     \c{b} emits the same \c{valueChanged()} signal, but since no slot
159     has been connected to \c{b}'s \c{valueChanged()} signal, the
160     signal is ignored.
161
162     Note that the \c{setValue()} function sets the value and emits
163     the signal only if \c{value != m_value}. This prevents infinite
164     looping in the case of cyclic connections (e.g., if
165     \c{b.valueChanged()} were connected to \c{a.setValue()}).
166
167     By default, for every connection you make, a signal is emitted;
168     two signals are emitted for duplicate connections. You can break
169     all of these connections with a single disconnect() call.
170     If you pass the Qt::UniqueConnection \a type, the connection will only
171     be made if it is not a duplicate. If there is already a duplicate
172     (exact same signal to the exact same slot on the same objects),
173     the connection will fail and connect will return false
174
175     This example illustrates that objects can work together without needing to
176     know any information about each other. To enable this, the objects only
177     need to be connected together, and this can be achieved with some simple
178     QObject::connect() function calls, or with \c{uic}'s
179     \l{Using a Designer UI File in Your Application#Automatic Connections}
180     {automatic connections} feature.
181
182     \section1 Building the Example
183
184     The C++ preprocessor changes or removes the \c{signals},
185     \c{slots}, and \c{emit} keywords so that the compiler is
186     presented with standard C++.
187
188     By running the \l moc on class definitions that contain signals
189     or slots, a C++ source file is produced which should be compiled
190     and linked with the other object files for the application. If
191     you use \l qmake, the makefile rules to automatically invoke \c
192     moc will be added to your project's makefile.
193
194     \section1 Signals
195
196     Signals are emitted by an object when its internal state has changed
197     in some way that might be interesting to the object's client or owner.
198     Only the class that defines a signal and its subclasses can emit the
199     signal.
200
201     When a signal is emitted, the slots connected to it are usually
202     executed immediately, just like a normal function call. When this
203     happens, the signals and slots mechanism is totally independent of
204     any GUI event loop. Execution of the code following the \c emit
205     statement will occur once all slots have returned. The situation is
206     slightly different when using \l{Qt::ConnectionType}{queued
207     connections}; in such a case, the code following the \c emit keyword
208     will continue immediately, and the slots will be executed later.
209
210     If several slots are connected to one signal, the slots will be
211     executed one after the other, in the order they have been connected,
212     when the signal is emitted.
213
214     Signals are automatically generated by the \l moc and must not be
215     implemented in the \c .cpp file. They can never have return types
216     (i.e. use \c void).
217
218     A note about arguments: Our experience shows that signals and slots
219     are more reusable if they do not use special types. If
220     QScrollBar::valueChanged() were to use a special type such as the
221     hypothetical QScrollBar::Range, it could only be connected to
222     slots designed specifically for QScrollBar. Connecting different
223     input widgets together would be impossible.
224
225     \section1 Slots
226
227     A slot is called when a signal connected to it is emitted. Slots are
228     normal C++ functions and can be called normally; their only special
229     feature is that signals can be connected to them.
230
231     Since slots are normal member functions, they follow the normal C++
232     rules when called directly. However, as slots, they can be invoked
233     by any component, regardless of its access level, via a signal-slot
234     connection. This means that a signal emitted from an instance of an
235     arbitrary class can cause a private slot to be invoked in an instance
236     of an unrelated class.
237
238     You can also define slots to be virtual, which we have found quite
239     useful in practice.
240
241     Compared to callbacks, signals and slots are slightly slower
242     because of the increased flexibility they provide, although the
243     difference for real applications is insignificant. In general,
244     emitting a signal that is connected to some slots, is
245     approximately ten times slower than calling the receivers
246     directly, with non-virtual function calls. This is the overhead
247     required to locate the connection object, to safely iterate over
248     all connections (i.e. checking that subsequent receivers have not
249     been destroyed during the emission), and to marshall any
250     parameters in a generic fashion. While ten non-virtual function
251     calls may sound like a lot, it's much less overhead than any \c
252     new or \c delete operation, for example. As soon as you perform a
253     string, vector or list operation that behind the scene requires
254     \c new or \c delete, the signals and slots overhead is only
255     responsible for a very small proportion of the complete function
256     call costs.
257
258     The same is true whenever you do a system call in a slot; or
259     indirectly call more than ten functions. On an i586-500, you can
260     emit around 2,000,000 signals per second connected to one
261     receiver, or around 1,200,000 per second connected to two
262     receivers. The simplicity and flexibility of the signals and
263     slots mechanism is well worth the overhead, which your users
264     won't even notice.
265
266     Note that other libraries that define variables called \c signals
267     or \c slots may cause compiler warnings and errors when compiled
268     alongside a Qt-based application. To solve this problem, \c
269     #undef the offending preprocessor symbol.
270
271     \section1 Meta-Object Information
272
273     The meta-object compiler (\l moc) parses the class declaration in
274     a C++ file and generates C++ code that initializes the
275     meta-object. The meta-object contains the names of all the signal
276     and slot members, as well as pointers to these functions.
277
278     The meta-object contains additional information such as the
279     object's \link QObject::className() class name\endlink. You can
280     also check if an object \link QObject::inherits()
281     inherits\endlink a specific class, for example:
282
283     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 5
284     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 6
285
286     The meta-object information is also used by qobject_cast<T>(), which
287     is similar to QObject::inherits() but is less error-prone:
288
289     \snippet doc/src/snippets/signalsandslots/signalsandslots.cpp 7
290
291     See \l{Meta-Object System} for more information.
292
293     \section1 A Real Example
294
295     Here is a simple commented example of a widget.
296
297     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 0
298     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 1
299     \codeline
300     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 2
301     \codeline
302     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 3
303     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 4
304     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 5
305
306     \c LcdNumber inherits QObject, which has most of the signal-slot
307     knowledge, via QFrame and QWidget. It is somewhat similar to the
308     built-in QLCDNumber widget.
309
310     The Q_OBJECT macro is expanded by the preprocessor to declare
311     several member functions that are implemented by the \c{moc}; if
312     you get compiler errors along the lines of "undefined reference
313     to vtable for \c{LcdNumber}", you have probably forgotten to
314     \l{moc}{run the moc} or to include the moc output in the link
315     command.
316
317     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 6
318     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 7
319
320     It's not obviously relevant to the moc, but if you inherit
321     QWidget you almost certainly want to have the \c parent argument
322     in your constructor and pass it to the base class's constructor.
323
324     Some destructors and member functions are omitted here; the \c
325     moc ignores member functions.
326
327     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 8
328     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 9
329
330     \c LcdNumber emits a signal when it is asked to show an impossible
331     value.
332
333     If you don't care about overflow, or you know that overflow
334     cannot occur, you can ignore the \c overflow() signal, i.e. don't
335     connect it to any slot.
336
337     If on the other hand you want to call two different error
338     functions when the number overflows, simply connect the signal to
339     two different slots. Qt will call both (in the order they were connected).
340
341     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 10
342     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 11
343     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 12
344     \codeline
345     \snippet doc/src/snippets/signalsandslots/lcdnumber.h 13
346
347     A slot is a receiving function used to get information about
348     state changes in other widgets. \c LcdNumber uses it, as the code
349     above indicates, to set the displayed number. Since \c{display()}
350     is part of the class's interface with the rest of the program,
351     the slot is public.
352
353     Several of the example programs connect the
354     \l{QScrollBar::valueChanged()}{valueChanged()} signal of a
355     QScrollBar to the \c display() slot, so the LCD number
356     continuously shows the value of the scroll bar.
357
358     Note that \c display() is overloaded; Qt will select the
359     appropriate version when you connect a signal to the slot. With
360     callbacks, you'd have to find five different names and keep track
361     of the types yourself.
362
363     Some irrelevant member functions have been omitted from this
364     example.
365
366     \section1 Signals And Slots With Default Arguments
367
368     The signatures of signals and slots may contain arguments, and the
369     arguments can have default values. Consider QObject::destroyed():
370
371     \code
372     void destroyed(QObject* = 0); 
373     \endcode
374
375     When a QObject is deleted, it emits this QObject::destroyed()
376     signal. We want to catch this signal, wherever we might have a
377     dangling reference to the deleted QObject, so we can clean it up.
378     A suitable slot signature might be:
379
380     \code
381     void objectDestroyed(QObject* obj = 0);
382     \endcode
383
384     To connect the signal to the slot, we use QObject::connect() and
385     the \c{SIGNAL()} and \c{SLOT()} macros. The rule about whether to
386     include arguments or not in the \c{SIGNAL()} and \c{SLOT()}
387     macros, if the arguments have default values, is that the
388     signature passed to the \c{SIGNAL()} macro must \e not have fewer
389     arguments than the signature passed to the \c{SLOT()} macro.
390
391     All of these would work:
392     \code
393     connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed(Qbject*)));
394     connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed()));
395     connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed()));
396     \endcode
397     But this one won't work:
398     \code
399     connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed(QObject*)));
400     \endcode
401
402     ...because the slot will be expecting a QObject that the signal
403     will not send. This connection will report a runtime error.
404
405     \section1 Advanced Signals and Slots Usage
406
407     For cases where you may require information on the sender of the
408     signal, Qt provides the QObject::sender() function, which returns
409     a pointer to the object that sent the signal.
410
411     The QSignalMapper class is provided for situations where many
412     signals are connected to the same slot and the slot needs to
413     handle each signal differently.
414
415     Suppose you have three push buttons that determine which file you
416     will open: "Tax File", "Accounts File", or "Report File". 
417
418     In order to open the correct file, you use QSignalMapper::setMapping() to
419     map all the clicked() signals to a QSignalMapper object. Then you connect
420     the file's QPushButton::clicked() signal to the QSignalMapper::map() slot.
421
422     \snippet doc/src/snippets/signalmapper/filereader.cpp 0
423
424     Then, you connect the \l{QSignalMapper::}{mapped()} signal to
425     \c{readFile()} where a different file will be opened, depending on
426     which push button is pressed.
427
428     \snippet doc/src/snippets/signalmapper/filereader.cpp 1
429
430     \note The following code will compile and run, but due to signature normalization, the code will be slower.
431
432     \snippet doc/src/snippets/signalmapper/filereader.cpp 2
433
434     \sa {Meta-Object System}, {Qt's Property System}
435
436     \target 3rd Party Signals and Slots
437     \section2 Using Qt with 3rd Party Signals and Slots
438
439     It is possible to use Qt with a 3rd party signal/slot mechanism.
440     You can even use both mechanisms in the same project. Just add the
441     following line to your qmake project (.pro) file.
442
443     \snippet doc/src/snippets/code/doc_src_containers.cpp 22
444
445     It tells Qt not to define the moc keywords \c{signals}, \c{slots},
446     and \c{emit}, because these names will be used by a 3rd party
447     library, e.g. Boost. Then to continue using Qt signals and slots
448     with the \c{no_keywords} flag, simply replace all uses of the Qt
449     moc keywords in your sources with the corresponding Qt macros
450     Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), and Q_EMIT.
451 */