Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_corelib_kernel_qobject.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4#include <QtWidgets>
5#include <QTimer>
6#include <QKeyEvent>
7#include <QTextEdit>
8#include <QVBoxLayout>
9
10QString objectName() { return ""; }
11
12void examples(int newPrecision)
13{
14 {
15 //! [1]
16 QObject *obj = new QPushButton;
17 obj->metaObject()->className(); // returns "QPushButton"
18
19 QPushButton::staticMetaObject.className(); // returns "QPushButton"
20 //! [1]
21 }
22
23 {
24 //! [2]
25 QPushButton::staticMetaObject.className(); // returns "QPushButton"
26
27 QObject *obj = new QPushButton;
28 obj->metaObject()->className(); // returns "QPushButton"
29 //! [2]
30 }
31
32 {
33 //! [3]
34 QObject *obj = new QTimer; // QTimer inherits QObject
35
36 QTimer *timer = qobject_cast<QTimer *>(obj);
37 // timer == (QObject *)obj
38
39 QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
40 // button == nullptr
41 //! [3]
42 }
43
44 {
45 //! [4]
46 QTimer *timer = new QTimer; // QTimer inherits QObject
47 timer->inherits("QTimer"); // returns true
48 timer->inherits("QObject"); // returns true
49 timer->inherits("QAbstractButton"); // returns false
50
51 // QVBoxLayout inherits QObject and QLayoutItem
52 QVBoxLayout *layout = new QVBoxLayout;
53 layout->inherits("QObject"); // returns true
54 layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
55 //! [4]
56 }
57
58 {
59 //! [5]
60 qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
61 qPrintable(objectName()), newPrecision);
62 //! [5]
63 }
64}
65
66//! [6]
67class MainWindow : public QMainWindow
68{
69public:
71
72protected:
73 bool eventFilter(QObject *obj, QEvent *ev) override;
74
75private:
76 QTextEdit *textEdit;
77};
78
80{
81 textEdit = new QTextEdit;
82 setCentralWidget(textEdit);
83
84 textEdit->installEventFilter(this);
85}
86
87bool MainWindow::eventFilter(QObject *obj, QEvent *event)
88{
89 if (obj == textEdit) {
90 if (event->type() == QEvent::KeyPress) {
91 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
92 qDebug() << "Ate key press" << keyEvent->key();
93 return true;
94 } else {
95 return false;
96 }
97 } else {
98 // pass the event on to the parent class
99 return QMainWindow::eventFilter(obj, event);
100 }
101}
102//! [6]
103
104void move_example(QObject *myObject)
105{
106 //! [7]
107 myObject->moveToThread(QApplication::instance()->thread());
108 //! [7]
109}
110
111//! [8]
112class MyObject : public QObject
113{
115
116public:
118
121
122protected:
123 void timerEvent(QTimerEvent *event) override;
124};
125
126MyObject::MyObject(QObject *parent)
127 : QObject(parent)
128{
129 using namespace std::chrono_literals;
130
131 startTimer(50ms);
132 startTimer(5s);
133 startTimer(10min);
134 startTimer(1h);
135}
136
137void MyObject::timerEvent(QTimerEvent *event)
138{
139 qDebug() << "Timer ID:" << event->id();
140}
141//! [8]
142
143void qpushbutton_examples(QWidget *parentWidget, QObject *monitoredObj, QObject *filterObj)
144{
145 {
146 //! [10]
147 QPushButton *button = parentWidget->findChild<QPushButton *>("button1");
148 //! [10]
149 }
150
151 {
152 //! [11]
153 QListWidget *list = parentWidget->findChild<QListWidget *>();
154 //! [11]
155 }
156
157 {
158 //! [12]
159 QList<QWidget *> widgets = parentWidget->findChildren<QWidget *>("widgetname");
160 //! [12]
161 }
162
163 {
164 //! [13]
165 QList<QPushButton *> allPButtons = parentWidget->findChildren<QPushButton *>();
166 //! [13]
167 }
168
169 {
170 //! [14]
171 monitoredObj->installEventFilter(filterObj);
172 //! [14]
173 }
174}
175
176//! [15]
177class KeyPressEater : public QObject
178{
180public:
182//...
183
184protected:
186};
187
188bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
189{
190 if (event->type() == QEvent::KeyPress) {
191 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
192 qDebug("Ate key press %d", keyEvent->key());
193 return true;
194 } else {
195 // standard event processing
196 return QObject::eventFilter(obj, event);
197 }
198}
199//! [15]
200
201class MyWindow : public QWidget
202{
204public:
207};
209{
210 //! [16]
211 KeyPressEater *keyPressEater = new KeyPressEater(this);
212 QPushButton *pushButton = new QPushButton(this);
213 QListView *listView = new QListView(this);
214
215 pushButton->installEventFilter(keyPressEater);
216 listView->installEventFilter(keyPressEater);
217 //! [16]
218}
219
220//! [17]
221MyWindow::MyWindow()
222{
223 QLabel *senderLabel = new QLabel(tr("Name:"));
224 QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));
225//! [17]
226}
227
228int receivers(const char *signal)
229{ return 0; }
230
231void get_the_value(QByteArray *data);
232
233void valueChanged(const QByteArray &data);
234
236{
237 //! [21]
238 if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
239 QByteArray data;
240 get_the_value(&data); // expensive operation
241 emit valueChanged(data);
242 }
243 //! [21]
244
245
246 //! [22]
247 QLabel *label = new QLabel;
248 QScrollBar *scrollBar = new QScrollBar;
249 QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
250 label, SLOT(setNum(int)));
251 //! [22]
252
253
254 //! [23]
255 // WRONG
256 QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
257 label, SLOT(setNum(int value)));
258 //! [23]
259}
260
261
262//! [24]
263class MyWidget : public QWidget
264{
266
267public:
269
270signals:
272
273private:
274 QPushButton *myButton;
275};
276
277MyWidget::MyWidget()
278{
279 myButton = new QPushButton(this);
280 connect(myButton, SIGNAL(clicked()),
281 this, SIGNAL(buttonClicked()));
282}
283//! [24]
284
285#if 0
286//! [25]
287QObject::connect: Cannot queue arguments of type 'MyType'
288(Make sure 'MyType' is registered using qRegisterMetaType().)
289//! [25]
290#endif
291
292
293
294void snippets_26_to_32(QObject *myObject, QObject *myReceiver, const QMetaMethod &signal)
295{
296 //! [26]
297 QObject::disconnect(myObject, nullptr, nullptr, nullptr);
298 //! [26]
299
300
301 //! [27]
302 myObject->disconnect();
303 //! [27]
304
305
306 //! [28]
307 QObject::disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);
308 //! [28]
309
310
311 //! [29]
312 myObject->disconnect(SIGNAL(mySignal()));
313 //! [29]
314
315
316 //! [30]
317 QObject::disconnect(myObject, nullptr, myReceiver, nullptr);
318 //! [30]
319
320
321 //! [31]
322 myObject->disconnect(myReceiver);
323 //! [31]
324
325
326 //! [32]
327 if (signal == QMetaMethod::fromSignal(&MyObject::valueChanged)) {
328 // signal is valueChanged
329 }
330 //! [32]
331}
332
333#if 0
334//! [33]
335void on_<object name>_<signal name>(<signal parameters>);
336//! [33]
337#endif
338
339//! [34]
341//! [34]
342
343namespace MyClassExample1
344{
345 //! [35]
346 class MyClass : public QObject
347 {
348 Q_OBJECT
349 Q_CLASSINFO("Author", "Pierre Gendron")
350 Q_CLASSINFO("URL", "http://www.my-organization.qc.ca")
351
352 public:
353 //...
354 };
355 //! [35]
356
357 //! [37]
358 Q_PROPERTY(QString title READ title WRITE setTitle USER true)
359 //! [37]
360}
361
362namespace MyClassExample2
363{
364 //! [38]
365 class MyClass : public QObject
366 {
367 Q_OBJECT
368
369 public:
370 MyClass(QObject *parent = nullptr);
371 ~MyClass();
372
373 enum Priority { High, Low, VeryHigh, VeryLow };
374 Q_ENUM(Priority)
375 void setPriority(Priority priority);
376 Priority priority() const;
377 };
378 //! [38]
379}
380
381void snippets_41_44(QWidget *parentWidget)
382{
383 //! [41]
384 QPushButton *button = parentWidget->findChild<QPushButton *>("button1", Qt::FindDirectChildrenOnly);
385 //! [41]
386
387
388 //! [42]
389 QListWidget *list = parentWidget->findChild<QListWidget *>(Qt::FindDirectChildrenOnly);
390 //! [42]
391
392 {
393 QWidget parentWidget;
394 //! [43]
395 QList<QPushButton *> childButtons = parentWidget.findChildren<QPushButton *>(Qt::FindDirectChildrenOnly);
396 //! [43]
397 }
398 //! [44]
399 QLabel *label = new QLabel;
400 QLineEdit *lineEdit = new QLineEdit;
401 QObject::connect(lineEdit, &QLineEdit::textChanged,
402 label, &QLabel::setText);
403 //! [44]
404}
405
406//! [45]
407void someFunction();
408//...
410{
411 QPushButton *button = new QPushButton;
412 QObject::connect(button, &QPushButton::clicked, someFunction);
413}
414//! [45]
415
416
417#if __has_include(<QTcpSocket>)
418#include <QTcpSocket>
419
420namespace TcpSocketExample
421{
422 class MyObject : public QObject
423 {
424 Q_OBJECT
425
426 public:
427 MyObject(QObject *parent = nullptr);
428
429 void snippets_46_to_48_51( MyObject *myObject, QLineEdit *lineEdit, QLabel *label)
430 {
431 //! [46]
432 QByteArray page = "...";
433 QTcpSocket *socket = new QTcpSocket;
434 socket->connectToHost("qt-project.org", 80);
435 QObject::connect(socket, &QTcpSocket::connected, [=] () {
436 socket->write("GET " + page + "\r\n");
437 });
438 //! [46]
439
440 //! [47]
441 QObject::disconnect(myObject, &MyObject::mySignal, nullptr, nullptr);
442 //! [47]
443
444 //! [48]
445 QObject::disconnect(lineEdit, &QLineEdit::textChanged,
446 label, &QLabel::setText);
447 //! [48]
448
449 //! [49]
450 static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
451 if (QObject::isSignalConnected(valueChangedSignal)) {
452 QByteArray data;
453 data = get_the_value(); // expensive operation
454 emit valueChanged(data);
455 }
456 //! [49]
457
458 {
459 //! [51]
460 QByteArray page = "...";
461 QTcpSocket *socket = new QTcpSocket;
462 socket->connectToHost("qt-project.org", 80);
463 QObject::connect(socket, &QTcpSocket::connected, this, [=] () {
464 socket->write("GET " + page + "\r\n");
465 }, Qt::AutoConnection);
466 //! [51]
467 }
468 }
469
470 QByteArray get_the_value();
471
472 //! [50]
473 //...
474 void someOtherFunction()
475 {
476 QPushButton *button = new QPushButton;
477 QObject::connect(button, &QPushButton::clicked, this, someFunction, Qt::QueuedConnection);
478 }
479 //! [50]
480
481 Q_SIGNALS:
482 void valueChanged(QByteArray &data);
483 void mySignal();
484
485 protected:
486 void timerEvent(QTimerEvent *event) override;
487 };
488 //! [50_someFunction]
489 void someFunction();
490 //! [50_someFunction]
491}
492#endif // __has_include(<QTcpSocket>)
493
494void doThings() {}
495void doThings2() {}
496
497//! [52]
498class MyClass : public QWidget
499{
500 Q_OBJECT
501
502public:
503 MyClass(QWidget *parent = nullptr);
504 ~MyClass();
505
506 bool event(QEvent* ev) override
507 {
508 if (ev->type() == QEvent::PolishRequest) {
509 // overwrite handling of PolishRequest if any
510 doThings();
511 return true;
512 } else if (ev->type() == QEvent::Show) {
513 // complement handling of Show if any
514 doThings2();
515 QWidget::event(ev);
516 return true;
517 }
518 // Make sure the rest of events are handled
519 return QWidget::event(ev);
520 }
521};
522//! [52]
523
525{
526
527 //! [53]
528 {
529 const QSignalBlocker blocker(someQObject);
530 // no signals here
531 }
532 //! [53]
533
534 //! [54]
535 const bool wasBlocked = someQObject->blockSignals(true);
536 // no signals here
537 someQObject->blockSignals(wasBlocked);
538 //! [54]
539
540 using namespace std::chrono_literals;
541
542 {
543 //! [invalid-timer-id]
544 QObject *obj;
545 //...
546 const auto id = Qt::TimerId {obj->startTimer(100ms)};
547 if (id != Qt::TimerId::Invalid)
548 {
549 // The timer has been started successfully
550 }
551 //! [invalid-timer-id]
552 }
553}
bool eventFilter(QObject *obj, QEvent *ev) override
Filters events if this object has been installed as an event filter for the watched object.
void timerEvent(QTimerEvent *event) override
This event handler can be reimplemented in a subclass to receive timer events for the object.
#define __has_include(x)
void on_button1_clicked()
[34]
void examples(int newPrecision)
void blocker_and_invalid_timer_id_examples(QObject *someQObject)
[52]
void someOtherFunction()
QString objectName()
void move_example(QObject *myObject)
[6]
void qpushbutton_examples(QWidget *parentWidget, QObject *monitoredObj, QObject *filterObj)
[8]
void doThings()
[45]
void connect_examples()
void snippets_26_to_32(QObject *myObject, QObject *myReceiver, const QMetaMethod &signal)
[24]
void valueChanged(const QByteArray &data)
void get_the_value(QByteArray *data)
int receivers(const char *signal)