Introduce QObject::isSignalConnected(QMetaMethod)
[profile/ivi/qtbase.git] / src / corelib / doc / snippets / code / src_corelib_kernel_qobject.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 **   * Redistributions of source code must retain the above copyright
15 **     notice, this list of conditions and the following disclaimer.
16 **   * Redistributions in binary form must reproduce the above copyright
17 **     notice, this list of conditions and the following disclaimer in
18 **     the documentation and/or other materials provided with the
19 **     distribution.
20 **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
21 **     the names of its contributors may be used to endorse or promote
22 **     products derived from this software without specific prior written
23 **     permission.
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41 //! [0]
42 QLineEdit *lineEdit = static_cast<QLineEdit *>(
43         qt_find_obj_child(myWidget, "QLineEdit", "my line edit"));
44 if (lineEdit)
45     lineEdit->setText("Default");
46 //! [0]
47
48
49 //! [1]
50 QObject *obj = new QPushButton;
51 obj->metaObject()->className();             // returns "QPushButton"
52
53 QPushButton::staticMetaObject.className();  // returns "QPushButton"
54 //! [1]
55
56
57 //! [2]
58 QPushButton::staticMetaObject.className();  // returns "QPushButton"
59
60 QObject *obj = new QPushButton;
61 obj->metaObject()->className();             // returns "QPushButton"
62 //! [2]
63
64
65 //! [3]
66 QObject *obj = new QTimer;          // QTimer inherits QObject
67
68 QTimer *timer = qobject_cast<QTimer *>(obj);
69 // timer == (QObject *)obj
70
71 QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
72 // button == 0
73 //! [3]
74
75
76 //! [4]
77 QTimer *timer = new QTimer;         // QTimer inherits QObject
78 timer->inherits("QTimer");          // returns true
79 timer->inherits("QObject");         // returns true
80 timer->inherits("QAbstractButton"); // returns false
81
82 // QVBoxLayout inherits QObject and QLayoutItem
83 QVBoxLayout *layout = new QVBoxLayout;
84 layout->inherits("QObject");        // returns true
85 layout->inherits("QLayoutItem");    // returns true (even though QLayoutItem is not a QObject)
86 //! [4]
87
88
89 //! [5]
90 qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
91        qPrintable(objectName()), newPrecision);
92 //! [5]
93
94
95 //! [6]
96 class MainWindow : public QMainWindow
97 {
98 public:
99     MainWindow();
100
101 protected:
102     bool eventFilter(QObject *obj, QEvent *ev);
103
104 private:
105     QTextEdit *textEdit;
106 };
107
108 MainWindow::MainWindow()
109 {
110     textEdit = new QTextEdit;
111     setCentralWidget(textEdit);
112
113     textEdit->installEventFilter(this);
114 }
115
116 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
117 {
118     if (obj == textEdit) {
119         if (event->type() == QEvent::KeyPress) {
120             QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
121             qDebug() << "Ate key press" << keyEvent->key();
122             return true;
123         } else {
124             return false;
125         }
126     } else {
127         // pass the event on to the parent class
128         return QMainWindow::eventFilter(obj, event);
129     }
130 }
131 //! [6]
132
133
134 //! [7]
135 myObject->moveToThread(QApplication::instance()->thread());
136 //! [7]
137
138
139 //! [8]
140 class MyObject : public QObject
141 {
142     Q_OBJECT
143
144 public:
145     MyObject(QObject *parent = 0);
146
147 protected:
148     void timerEvent(QTimerEvent *event);
149 };
150
151 MyObject::MyObject(QObject *parent)
152     : QObject(parent)
153 {
154     startTimer(50);     // 50-millisecond timer
155     startTimer(1000);   // 1-second timer
156     startTimer(60000);  // 1-minute timer
157 }
158
159 void MyObject::timerEvent(QTimerEvent *event)
160 {
161     qDebug() << "Timer ID:" << event->timerId();
162 }
163 //! [8]
164
165
166 //! [9]
167 QList<QObject *> list = window()->queryList("QAbstractButton"));
168 foreach (QObject *obj, list)
169     static_cast<QAbstractButton *>(obj)->setEnabled(false);
170 //! [9]
171
172
173 //! [10]
174 QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
175 //! [10]
176
177
178 //! [11]
179 QListWidget *list = parentWidget->findChild<QListWidget *>();
180 //! [11]
181
182
183 //! [12]
184 QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname");
185 //! [12]
186
187
188 //! [13]
189 QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>();
190 //! [13]
191
192
193 //! [14]
194 monitoredObj->installEventFilter(filterObj);
195 //! [14]
196
197
198 //! [15]
199 class KeyPressEater : public QObject
200 {
201     Q_OBJECT
202     ...
203
204 protected:
205     bool eventFilter(QObject *obj, QEvent *event);
206 };
207
208 bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
209 {
210     if (event->type() == QEvent::KeyPress) {
211         QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
212         qDebug("Ate key press %d", keyEvent->key());
213         return true;
214     } else {
215         // standard event processing
216         return QObject::eventFilter(obj, event);
217     }
218 }
219 //! [15]
220
221
222 //! [16]
223 KeyPressEater *keyPressEater = new KeyPressEater(this);
224 QPushButton *pushButton = new QPushButton(this);
225 QListView *listView = new QListView(this);
226
227 pushButton->installEventFilter(keyPressEater);
228 listView->installEventFilter(keyPressEater);
229 //! [16]
230
231
232 //! [17]
233 MyWindow::MyWindow()
234 {
235     QLabel *senderLabel = new QLabel(tr("Name:"));
236     QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
237 //! [17]
238 }
239
240
241 //! [18]
242 int n = messages.count();
243 showMessage(tr("%n message(s) saved", "", n));
244 //! [18]
245
246
247 //! [19]
248 n == 1 ? tr("%n message saved") : tr("%n messages saved")
249 //! [19]
250
251
252 //! [20]
253 label->setText(tr("F\374r \310lise"));
254 //! [20]
255
256
257 //! [21]
258 if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
259     QByteArray data;
260     get_the_value(&data);       // expensive operation
261     emit valueChanged(data);
262 }
263 //! [21]
264
265
266 //! [22]
267 QLabel *label = new QLabel;
268 QScrollBar *scrollBar = new QScrollBar;
269 QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
270                  label,  SLOT(setNum(int)));
271 //! [22]
272
273
274 //! [23]
275 // WRONG
276 QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
277                  label, SLOT(setNum(int value)));
278 //! [23]
279
280
281 //! [24]
282 class MyWidget : public QWidget
283 {
284     Q_OBJECT
285
286 public:
287     MyWidget();
288
289 signals:
290     void buttonClicked();
291
292 private:
293     QPushButton *myButton;
294 };
295
296 MyWidget::MyWidget()
297 {
298     myButton = new QPushButton(this);
299     connect(myButton, SIGNAL(clicked()),
300             this, SIGNAL(buttonClicked()));
301 }
302 //! [24]
303
304
305 //! [25]
306 QObject::connect: Cannot queue arguments of type 'MyType'
307 (Make sure 'MyType' is registered using qRegisterMetaType().)
308 //! [25]
309
310
311 //! [26]
312 disconnect(myObject, 0, 0, 0);
313 //! [26]
314
315
316 //! [27]
317 myObject->disconnect();
318 //! [27]
319
320
321 //! [28]
322 disconnect(myObject, SIGNAL(mySignal()), 0, 0);
323 //! [28]
324
325
326 //! [29]
327 myObject->disconnect(SIGNAL(mySignal()));
328 //! [29]
329
330
331 //! [30]
332 disconnect(myObject, 0, myReceiver, 0);
333 //! [30]
334
335
336 //! [31]
337 myObject->disconnect(myReceiver);
338 //! [31]
339
340
341 //! [32]
342 if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
343     // signal is valueChanged
344 }
345 //! [32]
346
347
348 //! [33]
349 void on_<object name>_<signal name>(<signal parameters>);
350 //! [33]
351
352
353 //! [34]
354 void on_button1_clicked();
355 //! [34]
356
357
358 //! [35]
359 class MyClass : public QObject
360 {
361     Q_OBJECT
362     Q_CLASSINFO("Author", "Pierre Gendron")
363     Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
364
365 public:
366     ...
367 };
368 //! [35]
369
370
371 //! [36]
372 Q_PROPERTY(type name
373            READ getFunction
374            [WRITE setFunction]
375            [RESET resetFunction]
376            [NOTIFY notifySignal]
377            [DESIGNABLE bool]
378            [SCRIPTABLE bool]
379            [STORED bool]
380            [USER bool]
381            [CONSTANT]
382            [FINAL])
383 //! [36]
384
385
386 //! [37]
387 Q_PROPERTY(QString title READ title WRITE setTitle USER true)
388 //! [37]
389
390
391 //! [38]
392 class MyClass : public QObject
393 {
394     Q_OBJECT
395     Q_ENUMS(Priority)
396
397 public:
398     MyClass(QObject *parent = 0);
399     ~MyClass();
400
401     enum Priority { High, Low, VeryHigh, VeryLow };
402     void setPriority(Priority priority);
403     Priority priority() const;
404 };
405 //! [38]
406
407
408 //! [39a]
409 class QLibrary : public QObject
410 {
411     ...
412     Q_FLAGS(LoadHint LoadHints)
413     ...
414 //! [39a]
415
416 //! [39b]
417     ...
418 public:
419     enum LoadHint {
420         ResolveAllSymbolsHint = 0x01,
421         ExportExternalSymbolsHint = 0x02,
422         LoadArchiveMemberHint = 0x04
423     };
424     Q_DECLARE_FLAGS(LoadHints, LoadHint)
425     ...
426 //! [39b]
427
428
429 //! [40]
430 //: This name refers to a host name.
431 hostNameLabel->setText(tr("Name:"));
432
433 /*: This text refers to a C++ code example. */
434 QString example = tr("Example");
435 //! [40]
436
437 //! [41]
438 QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildOnly);
439 //! [41]
440
441
442 //! [42]
443 QListWidget *list = parentWidget->findChild<QListWidget *>(QString(), Qt::FindDirectChildOnly);
444 //! [42]
445
446
447 //! [43]
448 QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildOnly);
449 //! [43]
450
451 //! [44]
452 QLabel *label = new QLabel;
453 QLineEdit *lineEdit = new QLineEdit;
454 QObject::connect(lineEdit, &QLineEdit::textChanged,
455                  label,  &QLabel::setText);
456 //! [44]
457
458 //! [45]
459 void someFunction();
460 QPushButton *button = new QPushButton;
461 QObject::connect(button, &QPushButton::clicked, someFunction);
462 //! [45]
463
464 //! [46]
465 QByteArray page = ...;
466 QTcpSocket *socket = new QTcpSocket;
467 socket->connectToHost("qt-project.org", 80);
468 QObject::connect(socket, &QTcpSocket::connected, [=] () {
469         socket->write("GET " + page + "\r\n");
470     });
471 //! [46]
472
473 //! [47]
474 disconnect(myObject, &MyObject::mySignal(), 0, 0);
475 //! [47]
476
477 //! [48]
478 QObject::disconnect(lineEdit, &QLineEdit::textChanged,
479                  label,  &QLabel::setText);
480 //! [48]
481
482 //! [49]
483 if (isSignalConnected(QMethaMethod::fromSignal(&MyObject::valueChanged))) {
484     QByteArray data;
485     data = get_the_value();       // expensive operation
486     emit valueChanged(data);
487 }
488 //! [49]
489
490 //! [meta data]
491 //: This is a comment for the translator.
492 //= qtn_foo_bar
493 //~ loc-layout_id foo_dialog
494 //~ loc-blank False
495 //~ magic-stuff This might mean something magic.
496 QString text = MyMagicClass::tr("Sim sala bim.");
497 //! [meta data]
498
499 //! [explicit tr context]
500 QString text = QScrollBar::tr("Page up");
501 //! [explicit tr context]