source: trunk/doc/src/signalsandslots.qdoc@ 348

Last change on this file since 348 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

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