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
qobject.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// Copyright (C) 2013 Olivier Goffart <ogoffart@woboq.com>
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:significant reason:default
6
7#include <QtCore/qtconfigmacros.h>
8
9#ifdef QT_NO_DISCONNECT_CONST_CONNECTION
10# undef QT_NO_DISCONNECT_CONST_CONNECTION
11#endif
12
13#include "qobject.h"
14#include "qobject_p.h"
15#include "qobject_p_p.h"
16#include "qmetaobject_p.h"
17
18#include <QtCore/private/qtclasshelper_p.h>
19#include <QtCore/qspan.h>
24#include "qcoreevent_p.h"
26#include "qvariant.h"
27#include "qmetaobject.h"
28#if QT_CONFIG(regularexpression)
29# include <qregularexpression.h>
30#endif
31#include <qthread.h>
32#include <private/qthread_p.h>
33#include <qdebug.h>
34#include <qvarlengtharray.h>
35#include <qscopeguard.h>
36#include <qset.h>
37#if QT_CONFIG(thread)
38#include <private/qlatch_p.h>
39#endif
40
41#include <private/qorderedmutexlocker_p.h>
42#include <private/qhooks_p.h>
43#include <qtcore_tracepoints_p.h>
44
45#include <new>
46#include <mutex>
47#include <memory>
48#include <optional>
49#include <iterator>
50
51#include <ctype.h>
52#include <limits.h>
53
55
56Q_TRACE_POINT(qtcore, QObject_ctor, QObject *object);
58Q_TRACE_POINT(qtcore, QMetaObject_activate_entry, QObject *sender, int signalIndex);
60Q_TRACE_POINT(qtcore, QMetaObject_activate_slot_entry, QObject *receiver, int slotIndex);
66
68
69Q_STATIC_LOGGING_CATEGORY(lcConnectSlotsByName, "qt.core.qmetaobject.connectslotsbyname")
70Q_STATIC_LOGGING_CATEGORY(lcConnect, "qt.core.qobject.connect")
71
72Q_CORE_EXPORT QBasicAtomicPointer<QSignalSpyCallbackSet> qt_signal_spy_callback_set = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
73
75{
76 qt_signal_spy_callback_set.storeRelease(callback_set);
77}
78
79QDynamicMetaObjectData::~QDynamicMetaObjectData()
80{
81}
82
83QAbstractDynamicMetaObject::~QAbstractDynamicMetaObject()
84{
85}
86
87static int *queuedConnectionTypes(const QMetaMethod &method)
88{
89 const auto parameterCount = method.parameterCount();
90 int *typeIds = new int[parameterCount + 1];
91 Q_CHECK_PTR(typeIds);
92 for (int i = 0; i < parameterCount; ++i) {
93 const QMetaType metaType = method.parameterMetaType(i);
94 if (metaType.flags() & QMetaType::IsPointer)
95 typeIds[i] = QMetaType::VoidStar;
96 else
97 typeIds[i] = metaType.id();
98 if (!typeIds[i] && method.parameterTypeName(i).endsWith('*'))
99 typeIds[i] = QMetaType::VoidStar;
100 if (!typeIds[i]) {
101 const QByteArray typeName = method.parameterTypeName(i);
102 qCWarning(lcConnect,
103 "QObject::connect: Cannot queue arguments of type '%s'\n"
104 "(Make sure '%s' is registered using qRegisterMetaType().)",
105 typeName.constData(), typeName.constData());
106 delete[] typeIds;
107 return nullptr;
108 }
109 }
110 typeIds[parameterCount] = 0;
111
112 return typeIds;
113}
115// ### Future work: replace with an array of QMetaType or QtPrivate::QMetaTypeInterface *
116static int *queuedConnectionTypes(QSpan<const QArgumentType> argumentTypes)
117{
118 const int argc = int(argumentTypes.size());
119 auto types = std::make_unique<int[]>(argc + 1);
120 for (int i = 0; i < argc; ++i) {
121 const QArgumentType &type = argumentTypes[i];
122 if (type.metaType().isValid())
123 types[i] = type.metaType().id();
124 else if (type.name().endsWith('*'))
125 types[i] = QMetaType::VoidStar;
126 else
127 types[i] = QMetaType::fromName(type.name()).rawId();
128
129 if (!types[i]) {
130 qCWarning(lcConnect,
131 "QObject::connect: Cannot queue arguments of type '%s'\n"
132 "(Make sure '%s' is registered using qRegisterMetaType().)",
133 type.name().constData(), type.name().constData());
134 return nullptr;
135 }
136 }
137 types[argc] = 0;
138
139 return types.release();
140}
141
142Q_CONSTINIT static QBasicMutex _q_ObjectMutexPool[131];
143
144/**
145 * \internal
146 * mutex to be locked when accessing the connection lists or the senders list
147 */
148static inline QBasicMutex *signalSlotLock(const QObject *o)
149{
150 return &_q_ObjectMutexPool[quintptr(o) % std::size(_q_ObjectMutexPool)];
151}
152
153/**
154 * \internal
155 * Tells \a sender that the connection for \a signalIndex is gone, because its receiver is being
156 * destroyed.
157 *
158 * The caller holds the receiver's signalSlotLock, which \a sender's destructor must also take to
159 * tear down this (still-present) connection. So \a sender cannot get past ~QObject(), and reading
160 * its QObjectPrivate here is safe. That lock does not, however, hold back \a sender's
161 * further-derived destructors: those run before ~QObject() takes any lock, and rewrite the vptr as
162 * they go. Resolving the signal and calling disconnectNotify() are therefore virtual calls that
163 * may only be made from the thread that owns \a sender. Post them to that thread otherwise, unless
164 * it can no longer deliver events (e.g. it has finished), where the event would leak.
165 */
166static void disconnectNotifySender(QObject *sender, int signalIndex, Qt::HANDLE currentThreadId)
167{
168 QObjectPrivate *senderPriv = QObjectPrivate::get(sender);
169 QThreadData *senderThread = senderPriv->threadData.loadRelaxed();
170 if (senderThread->threadId.loadRelaxed() == currentThreadId)
171 senderPriv->disconnectNotify(QMetaObjectPrivate::signal(sender->metaObject(), signalIndex));
172 else if (senderThread->hasEventDispatcher())
173 QCoreApplication::postEvent(sender, new QDisconnectNotifyEvent(signalIndex));
174}
175
176void (*QAbstractDeclarativeData::destroyed)(QAbstractDeclarativeData *, QObject *) = nullptr;
177void (*QAbstractDeclarativeData::signalEmitted)(QAbstractDeclarativeData *, QObject *, int, void **) = nullptr;
178int (*QAbstractDeclarativeData::receivers)(QAbstractDeclarativeData *, const QObject *, int) = nullptr;
179bool (*QAbstractDeclarativeData::isSignalConnected)(QAbstractDeclarativeData *, const QObject *, int) = nullptr;
180void (*QAbstractDeclarativeData::setWidgetParent)(QObject *, QObject *) = nullptr;
181
182/*!
183 \fn QObjectData::QObjectData()
184 \internal
185 */
186
187
188QObjectData::~QObjectData() {}
189
190const QMetaObject *QObjectData::dynamicMetaObject() const
191{
192 // ### keep in sync with removed_api.cpp version
193 return metaObject->toDynamicMetaObject(q_ptr);
194}
195
196QObjectPrivate::QObjectPrivate(decltype(QObjectPrivateVersion))
197 : threadData(nullptr), currentChildBeingDeleted(nullptr)
198{
199 // QObjectData initialization
200 q_ptr = nullptr;
201 parent = nullptr; // no parent yet. It is set by setParent()
202 isWidget = false; // assume not a widget object
203 blockSig = false; // not blocking signals
204 wasDeleted = false; // double-delete catcher
205 isDeletingChildren = false; // set by deleteChildren()
206 sendChildEvents = true; // if we should send ChildAdded and ChildRemoved events to parent
207 receiveChildEvents = true;
208 postedEvents.storeRelaxed(0);
209 extraData = nullptr;
210 metaObject = nullptr;
211 isWindow = false;
212 deleteLaterCalled = false;
213 isQuickItem = false;
214 willBeWidget = false;
215 wasWidget = false;
216 receiveParentEvents = false; // If object wants ParentAboutToChange and ParentChange
217}
218
219QObjectPrivate::~QObjectPrivate()
220{
221 auto thisThreadData = threadData.loadRelaxed();
222 if (extraData && !extraData->runningTimers.isEmpty()) {
223 if (thisThreadData->threadId.loadRelaxed() == QThread::currentThreadId()) {
224 // unregister pending timers
225 if (thisThreadData->hasEventDispatcher())
226 thisThreadData->eventDispatcher.loadRelaxed()->unregisterTimers(q_ptr);
227
228 // release the timer ids back to the pool
229 for (auto id : std::as_const(extraData->runningTimers))
230 QAbstractEventDispatcherPrivate::releaseTimerId(id);
231 } else {
232 qWarning("QObject::~QObject: Timers cannot be stopped from another thread");
233 }
234 }
235
236 if (postedEvents.loadRelaxed())
237 QCoreApplication::removePostedEvents(q_ptr, 0);
238
239 thisThreadData->deref();
240
241 if (metaObject)
242 metaObject->objectDestroyed(q_ptr);
243
244 delete extraData;
245}
246
247/*!
248 \internal
249 For a given metaobject, compute the signal offset, and the method offset (including signals)
250*/
251static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int *methodOffset)
252{
253 *signalOffset = *methodOffset = 0;
254 const QMetaObject *m = metaobject->d.superdata;
255 while (m) {
256 const QMetaObjectPrivate *d = QMetaObjectPrivate::get(m);
257 *methodOffset += d->methodCount;
258 Q_ASSERT(d->revision >= 4);
259 *signalOffset += d->signalCount;
260 m = m->d.superdata;
261 }
262}
263
264// Used by QAccessibleWidget
265QObjectList QObjectPrivate::receiverList(const char *signal) const
266{
267 QObjectList returnValue;
268 int signal_index = signalIndex(signal);
269 ConnectionData *cd = connections.loadAcquire();
270 if (signal_index < 0 || !cd)
271 return returnValue;
272 if (signal_index < cd->signalVectorCount()) {
273 const QObjectPrivate::Connection *c = cd->signalVector.loadRelaxed()->at(signal_index).first.loadRelaxed();
274
275 while (c) {
276 QObject *r = c->receiver.loadRelaxed();
277 if (r)
278 returnValue << r;
279 c = c->nextConnectionList.loadRelaxed();
280 }
281 }
282 return returnValue;
283}
284
285/*!
286 \internal
287 The signalSlotLock() of the sender must be locked while calling this function
288*/
289inline void QObjectPrivate::ensureConnectionData()
290{
291 if (connections.loadRelaxed())
292 return;
293 ConnectionData *cd = new ConnectionData;
294 cd->ref.ref();
295 connections.storeRelease(cd);
296}
297
298/*!
299 \internal
300 Add the connection \a c to the list of connections of the sender's object
301 for the specified \a signal
302
303 The signalSlotLock() of the sender and receiver must be locked while calling
304 this function
305
306 Will also add the connection in the sender's list of the receiver.
307 */
308inline void QObjectPrivate::addConnection(int signal, Connection *c)
309{
310 Q_ASSERT(c->sender == q_ptr);
311 ensureConnectionData();
312 ConnectionData *cd = connections.loadRelaxed();
313 cd->resizeSignalVector(signal + 1);
314
315 ConnectionList &connectionList = cd->connectionsForSignal(signal);
316 Connection *lastConnection = connectionList.last.loadRelaxed();
317 if (lastConnection) {
318 Q_ASSERT(lastConnection->receiver.loadRelaxed());
319 lastConnection->nextConnectionList.storeRelease(c);
320 } else {
321 connectionList.first.storeRelease(c);
322 }
323 c->id.storeRelease(++cd->currentConnectionId);
324 c->prevConnectionList = lastConnection;
325 connectionList.last.storeRelaxed(c);
326
327 QObjectPrivate *rd = QObjectPrivate::get(c->receiver.loadRelaxed());
328 rd->ensureConnectionData();
329
330 c->prev = &(rd->connections.loadRelaxed()->senders);
331 c->next = *c->prev;
332 *c->prev = c;
333 if (c->next)
334 c->next->prev = &c->next;
335}
336
337void QObjectPrivate::ConnectionData::removeConnection(QObjectPrivate::Connection *c)
338{
339 Q_ASSERT(c->receiver.loadRelaxed());
340 ConnectionList &connections = signalVector.loadRelaxed()->at(c->signal_index);
341 c->receiver.storeRelaxed(nullptr);
342 QThreadData *td = c->receiverThreadData.loadRelaxed();
343 if (td)
344 td->deref();
345 c->receiverThreadData.storeRelaxed(nullptr);
346
347#ifndef QT_NO_DEBUG
348 bool found = false;
349 for (Connection *cc = connections.first.loadRelaxed(); cc; cc = cc->nextConnectionList.loadRelaxed()) {
350 if (cc == c) {
351 found = true;
352 break;
353 }
354 }
355 Q_ASSERT(found);
356#endif
357
358 // remove from the senders linked list
359 *c->prev = c->next;
360 if (c->next)
361 c->next->prev = c->prev;
362 c->prev = nullptr;
363
364 Connection *n = c->nextConnectionList.loadRelaxed();
365 if (connections.first.loadRelaxed() == c)
366 connections.first.storeRelaxed(n);
367 if (connections.last.loadRelaxed() == c)
368 connections.last.storeRelaxed(c->prevConnectionList);
369 Q_ASSERT(signalVector.loadRelaxed()->at(c->signal_index).first.loadRelaxed() != c);
370 Q_ASSERT(signalVector.loadRelaxed()->at(c->signal_index).last.loadRelaxed() != c);
371
372 // keep c->nextConnectionList intact, as it might still get accessed by activate
373 if (n)
374 n->prevConnectionList = c->prevConnectionList;
375 if (c->prevConnectionList)
376 c->prevConnectionList->nextConnectionList.storeRelaxed(n);
377 c->prevConnectionList = nullptr;
378
379 Q_ASSERT(c != static_cast<Connection *>(orphaned.load(std::memory_order_relaxed)));
380 // add c to orphanedConnections
381 TaggedSignalVector o = nullptr;
382 /* No ABA issue here: When adding a node, we only care about the list head, it doesn't
383 * matter if the tail changes.
384 */
385 o = orphaned.load(std::memory_order_acquire);
386 do {
387 c->nextInOrphanList = o;
388 } while (!orphaned.compare_exchange_strong(o, TaggedSignalVector(c), std::memory_order_release));
389
390#ifndef QT_NO_DEBUG
391 found = false;
392 for (Connection *cc = connections.first.loadRelaxed(); cc; cc = cc->nextConnectionList.loadRelaxed()) {
393 if (cc == c) {
394 found = true;
395 break;
396 }
397 }
398 Q_ASSERT(!found);
399#endif
400
401}
402
403void QObjectPrivate::ConnectionData::cleanOrphanedConnectionsImpl(QObject *sender, LockPolicy lockPolicy)
404{
405 QBasicMutex *senderMutex = signalSlotLock(sender);
406 TaggedSignalVector c = nullptr;
407 {
408 std::unique_lock<QBasicMutex> lock(*senderMutex, std::defer_lock_t{});
409 if (lockPolicy == NeedToLock)
410 lock.lock();
411 if (ref.loadAcquire() > 1)
412 return;
413
414 // Since ref == 1, no activate() is in process since we locked the mutex. That implies,
415 // that nothing can reference the orphaned connection objects anymore and they can
416 // be safely deleted
417 c = orphaned.exchange(nullptr, std::memory_order_relaxed);
418 }
419 if (c) {
420 // Deleting c might run arbitrary user code, so we must not hold the lock
421 if (lockPolicy == AlreadyLockedAndTemporarilyReleasingLock) {
422 senderMutex->unlock();
423 deleteOrphaned(c);
424 senderMutex->lock();
425 } else {
426 deleteOrphaned(c);
427 }
428 }
429}
430
431inline void QObjectPrivate::ConnectionData::deleteOrphaned(TaggedSignalVector o)
432{
433 while (o) {
434 TaggedSignalVector next = nullptr;
435 if (SignalVector *v = static_cast<SignalVector *>(o)) {
436 next = v->nextInOrphanList;
437 free(v);
438 } else {
439 QObjectPrivate::Connection *c = static_cast<Connection *>(o);
440 next = c->nextInOrphanList;
441 Q_ASSERT(!c->receiver.loadRelaxed());
442 Q_ASSERT(!c->prev);
443 c->freeSlotObject();
444 c->deref();
445 }
446 o = next;
447 }
448}
449
450/*! \internal
451
452 Returns \c true if the signal with index \a signal_index from object \a sender is connected.
453
454 \a signal_index must be the index returned by QObjectPrivate::signalIndex;
455*/
456bool QObjectPrivate::isSignalConnected(uint signalIndex, bool checkDeclarative) const
457{
458 if (checkDeclarative && isDeclarativeSignalConnected(signalIndex))
459 return true;
460
461 ConnectionData *cd = connections.loadAcquire();
462 if (!cd)
463 return false;
464 SignalVector *signalVector = cd->signalVector.loadRelaxed();
465 if (!signalVector)
466 return false;
467
468 if (signalVector->at(-1).first.loadRelaxed())
469 return true;
470
471 if (signalIndex < uint(cd->signalVectorCount())) {
472 const QObjectPrivate::Connection *c = signalVector->at(signalIndex).first.loadRelaxed();
473 while (c) {
474 if (c->receiver.loadRelaxed())
475 return true;
476 c = c->nextConnectionList.loadRelaxed();
477 }
478 }
479 return false;
480}
481
482bool QObjectPrivate::maybeSignalConnected(uint signalIndex) const
483{
484 ConnectionData *cd = connections.loadAcquire();
485 if (!cd)
486 return false;
487 SignalVector *signalVector = cd->signalVector.loadAcquire();
488 if (!signalVector)
489 return false;
490
491 if (signalVector->at(-1).first.loadAcquire())
492 return true;
493
494 if (signalIndex < uint(cd->signalVectorCount())) {
495 const QObjectPrivate::Connection *c = signalVector->at(signalIndex).first.loadAcquire();
496 return c != nullptr;
497 }
498 return false;
499}
500
501void QObjectPrivate::reinitBindingStorageAfterThreadMove()
502{
503 bindingStorage.reinitAfterThreadMove();
504 for (int i = 0; i < children.size(); ++i)
505 children[i]->d_func()->reinitBindingStorageAfterThreadMove();
506}
507
508/*!
509 \internal
510 */
511QAbstractMetaCallEvent::~QAbstractMetaCallEvent()
512{
513#if QT_CONFIG(thread)
514 if (latch)
515 latch->countDown();
516#endif
517}
518
519/*!
520 \internal
521
522 Used for blocking queued connections, just passes \a args through without
523 allocating any memory.
524 */
525QMetaCallEvent::QMetaCallEvent(ushort method_offset, ushort method_relative,
526 QObjectPrivate::StaticMetaCallFunction callFunction,
527 const QObject *sender, int signalId,
528 void **args, QLatch *latch)
529 : QAbstractMetaCallEvent(sender, signalId, latch),
530 d{nullptr, args, callFunction, 0, method_offset, method_relative}
531{
532}
533
534/*!
535 \internal
536
537 Used for blocking queued connections, just passes \a args through without
538 allocating any memory.
539 */
540QMetaCallEvent::QMetaCallEvent(QtPrivate::QSlotObjectBase *slotO,
541 const QObject *sender, int signalId,
542 void **args, QLatch *latch)
543 : QAbstractMetaCallEvent(sender, signalId, latch),
544 d{QtPrivate::SlotObjUniquePtr{slotO}, args, nullptr, 0, 0, ushort(-1)}
545{
546 if (d.slotObj_)
547 d.slotObj_->ref();
548}
549
550/*!
551 \internal
552
553 Used for blocking queued connections, just passes \a args through without
554 allocating any memory.
555 */
556QMetaCallEvent::QMetaCallEvent(QtPrivate::SlotObjUniquePtr slotO,
557 const QObject *sender, int signalId,
558 void **args, QLatch *latch)
559 : QAbstractMetaCallEvent(sender, signalId, latch),
560 d{std::move(slotO), args, nullptr, 0, 0, ushort(-1)}
561{
562}
563
564/*!
565 \internal
566 */
567QMetaCallEvent::QMetaCallEvent(const QObject *sender, int signalId, Data &&data)
568 : QAbstractMetaCallEvent(sender, signalId),
569 d(std::move(data))
570{
571}
572
573/*!
574 \internal
575 */
576void QMetaCallEvent::placeMetaCall(QObject *object)
577{
578 if (d.slotObj_) {
579 d.slotObj_->call(object, d.args_);
580 } else if (d.callFunction_ && d.method_offset_ <= object->metaObject()->methodOffset()) {
581 d.callFunction_(object, QMetaObject::InvokeMetaMethod, d.method_relative_, d.args_);
582 } else {
583 QMetaObject::metacall(object, QMetaObject::InvokeMetaMethod,
584 d.method_offset_ + d.method_relative_, d.args_);
585 }
586}
587
588/*!
589 \internal
590
591 Constructs a QQueuedMetaCallEvent by copying the argument values using their meta-types.
592 */
593QQueuedMetaCallEvent::QQueuedMetaCallEvent(ushort method_offset, ushort method_relative,
594 QObjectPrivate::StaticMetaCallFunction callFunction,
595 const QObject *sender, int signalId, int argCount,
596 const QtPrivate::QMetaTypeInterface * const *argTypes,
597 const void * const *argValues)
598 : QMetaCallEvent(sender, signalId, {nullptr, nullptr, callFunction, argCount,
599 method_offset, method_relative}),
600 prealloc_()
601{
602 copyArgValues(argCount, argTypes, argValues);
603}
604
605/*!
606 \internal
607
608 Constructs a QQueuedMetaCallEvent by copying the argument values using their meta-types.
609 */
610QQueuedMetaCallEvent::QQueuedMetaCallEvent(QtPrivate::QSlotObjectBase *slotObj,
611 const QObject *sender, int signalId, int argCount,
612 const QtPrivate::QMetaTypeInterface * const *argTypes,
613 const void * const *argValues)
614 : QMetaCallEvent(sender, signalId, {QtPrivate::SlotObjUniquePtr(slotObj), nullptr, nullptr, argCount,
615 0, ushort(-1)}),
616 prealloc_()
617{
618 if (d.slotObj_)
619 d.slotObj_->ref();
620 copyArgValues(argCount, argTypes, argValues);
621}
622
623/*!
624 \internal
625
626 Constructs a QQueuedMetaCallEvent by copying the argument values using their meta-types.
627 */
628QQueuedMetaCallEvent::QQueuedMetaCallEvent(QtPrivate::SlotObjUniquePtr slotObj,
629 const QObject *sender, int signalId, int argCount,
630 const QtPrivate::QMetaTypeInterface * const *argTypes,
631 const void * const *argValues)
632 : QMetaCallEvent(sender, signalId, {std::move(slotObj), nullptr, nullptr, argCount,
633 0, ushort(-1)}),
634 prealloc_()
635{
636 copyArgValues(argCount, argTypes, argValues);
637}
638
639/*!
640 \internal
641 */
642QQueuedMetaCallEvent::~QQueuedMetaCallEvent()
643{
644 const QMetaType *t = reinterpret_cast<QMetaType *>(d.args_ + d.nargs_);
645 int inplaceIndex = 0;
646 for (int i = 0; i < d.nargs_; ++i) {
647 if (t[i].isValid() && d.args_[i]) {
648 if (typeFitsInPlace(t[i]) && inplaceIndex < InplaceValuesCapacity) {
649 // Only destruct
650 void *where = &valuesPrealloc_[inplaceIndex++].storage;
651 t[i].destruct(where);
652 } else {
653 // Destruct and deallocate
654 t[i].destroy(d.args_[i]);
655 }
656 }
657 }
658 if (d.nargs_) {
659 if (static_cast<void *>(d.args_) != prealloc_)
660 QtPrivate::sizedFree(d.args_, d.nargs_, PtrAndTypeSize);
661 }
662}
663
664/*!
665 \internal
666 */
667inline void QQueuedMetaCallEvent::allocArgs()
668{
669 if (!d.nargs_)
670 return;
671
672 void *const memory = d.nargs_ * PtrAndTypeSize > sizeof(prealloc_) ?
673 calloc(d.nargs_, PtrAndTypeSize) : prealloc_;
674
675 Q_CHECK_PTR(memory);
676 d.args_ = static_cast<void **>(memory);
677}
678
679/*!
680 \internal
681 */
682inline void QQueuedMetaCallEvent::copyArgValues(int argCount, const QtPrivate::QMetaTypeInterface * const *argTypes,
683 const void * const *argValues)
684{
685 allocArgs();
686 void **args = d.args_;
687 QMetaType *types = reinterpret_cast<QMetaType *>(d.args_ + d.nargs_);
688 int inplaceIndex = 0;
689
690 if (argCount) {
691 types[0] = QMetaType(); // return type
692 args[0] = nullptr; // return value pointer
693 }
694 // no return value
695
696 for (int n = 1; n < argCount; ++n) {
697 types[n] = QMetaType(argTypes[n]);
698 if (typeFitsInPlace(types[n]) && inplaceIndex < InplaceValuesCapacity) {
699 // Copy-construct in place
700 void *where = &valuesPrealloc_[inplaceIndex++].storage;
701 types[n].construct(where, argValues[n]);
702 args[n] = where;
703 } else {
704 // Allocate and copy-construct
705 args[n] = types[n].create(argValues[n]);
706 }
707 }
708}
709
710/*!
711 \internal
712 */
713inline bool QQueuedMetaCallEvent::typeFitsInPlace(const QMetaType type)
714{
715 return (q20::cmp_less_equal(type.sizeOf(), sizeof(ArgValueStorage)) &&
716 q20::cmp_less_equal(type.alignOf(), alignof(ArgValueStorage)));
717}
718
719/*!
720 \class QSignalBlocker
721 \brief Exception-safe wrapper around QObject::blockSignals().
722 \since 5.3
723 \ingroup objectmodel
724 \inmodule QtCore
725
726 \reentrant
727
728 QSignalBlocker can be used wherever you would otherwise use a
729 pair of calls to QObject::blockSignals(). It blocks signals in its
730 constructor and in the destructor it resets the state to what
731 it was before the constructor ran.
732
733 \snippet code/src_corelib_kernel_qobject.cpp 53
734 is thus equivalent to
735 \snippet code/src_corelib_kernel_qobject.cpp 54
736
737 except the code using QSignalBlocker is safe in the face of
738 exceptions.
739
740 \sa QMutexLocker, QEventLoopLocker
741*/
742
743/*!
744 \fn QSignalBlocker::QSignalBlocker(QObject *object)
745
746 Constructor. Calls \a{object}->blockSignals(true).
747*/
748
749/*!
750 \fn QSignalBlocker::QSignalBlocker(QObject &object)
751 \overload
752
753 Calls \a{object}.blockSignals(true).
754*/
755
756/*!
757 \fn QSignalBlocker::QSignalBlocker(QSignalBlocker &&other)
758
759 Move-constructs a signal blocker from \a other. \a other will have
760 a no-op destructor, while responsibility for restoring the
761 QObject::signalsBlocked() state is transferred to the new object.
762*/
763
764/*!
765 \fn QSignalBlocker &QSignalBlocker::operator=(QSignalBlocker &&other)
766
767 Move-assigns this signal blocker from \a other. \a other will have
768 a no-op destructor, while responsibility for restoring the
769 QObject::signalsBlocked() state is transferred to this object.
770
771 The object's signals this signal blocker was blocking prior to
772 being moved to, if any, are unblocked \e except in the case where
773 both instances block the same object's signals and \c *this is
774 unblocked while \a other is not, at the time of the move.
775*/
776
777/*!
778 \fn QSignalBlocker::~QSignalBlocker()
779
780 Destructor. Restores the QObject::signalsBlocked() state to what it
781 was before the constructor ran, unless unblock() has been called
782 without a following reblock(), in which case it does nothing.
783*/
784
785/*!
786 \fn void QSignalBlocker::reblock()
787
788 Re-blocks signals after a previous unblock().
789
790 The numbers of reblock() and unblock() calls are not counted, so
791 every reblock() undoes any number of unblock() calls.
792*/
793
794/*!
795 \fn void QSignalBlocker::unblock()
796
797 Temporarily restores the QObject::signalsBlocked() state to what
798 it was before this QSignalBlocker's constructor ran. To undo, use
799 reblock().
800
801 The numbers of reblock() and unblock() calls are not counted, so
802 every unblock() undoes any number of reblock() calls.
803*/
804
805/*!
806 \fn void QSignalBlocker::dismiss()
807 \since 6.7
808 Dismisses the QSignalBlocker. It will no longer access the QObject
809 passed to its constructor. unblock(), reblock(), as well as
810 ~QSignalBlocker() will have no effect.
811*/
812
813/*!
814 \class QObject
815 \inmodule QtCore
816 \brief The QObject class is the base class of all Qt objects.
817
818 \ingroup objectmodel
819
820 \reentrant
821
822 QObject is the heart of the Qt \l{Object Model}. The central
823 feature in this model is a very powerful mechanism for seamless
824 object communication called \l{signals and slots}. You can
825 connect a signal to a slot with connect() and destroy the
826 connection with disconnect(). To avoid never ending notification
827 loops you can temporarily block signals with blockSignals(). The
828 protected functions connectNotify() and disconnectNotify() make
829 it possible to track connections.
830
831 QObjects organize themselves in \l {Object Trees & Ownership}
832 {object trees}. When you create a QObject with another object as
833 parent, the object will automatically add itself to the parent's
834 children() list. The parent takes ownership of the object; i.e.,
835 it will automatically delete its children in its destructor. You
836 can look for an object by name and optionally type using
837 findChild() or findChildren().
838
839 Every object has an objectName() and its class name can be found
840 via the corresponding metaObject() (see QMetaObject::className()).
841 You can determine whether the object's class inherits another
842 class in the QObject inheritance hierarchy by using the
843 inherits() function.
844
845 When an object is deleted, it emits a destroyed() signal. You can
846 catch this signal to avoid dangling references to QObjects.
847
848 QObjects can receive events through event() and filter the events
849 of other objects. See installEventFilter() and eventFilter() for
850 details. A convenience handler, childEvent(), can be reimplemented
851 to catch child events.
852
853 Last but not least, QObject provides the basic timer support in
854 Qt; see QChronoTimer for high-level support for timers.
855
856 Notice that the Q_OBJECT macro is mandatory for any object that
857 implements signals, slots or properties. You also need to run the
858 \l{moc}{Meta Object Compiler} on the source file. We strongly
859 recommend the use of this macro in all subclasses of QObject
860 regardless of whether or not they actually use signals, slots and
861 properties, since failure to do so may lead certain functions to
862 exhibit strange behavior.
863
864 All Qt widgets inherit QObject. The convenience function
865 isWidgetType() returns whether an object is actually a widget. It
866 is much faster than
867 \l{qobject_cast()}{qobject_cast}<QWidget *>(\e{obj}) or
868 \e{obj}->\l{inherits()}{inherits}("QWidget").
869
870 Some QObject functions, e.g. children(), return a QObjectList.
871 QObjectList is a typedef for QList<QObject *>.
872
873 \section1 Thread Affinity
874
875 A QObject instance is said to have a \e{thread affinity}, or that
876 it \e{lives} in a certain thread. When a QObject receives a
877 \l{Qt::QueuedConnection}{queued signal} or a \l{The Event
878 System#Sending Events}{posted event}, the slot or event handler
879 will run in the thread that the object lives in.
880
881 \note If a QObject has no thread affinity (that is, if thread()
882 returns zero), or if it lives in a thread that has no running event
883 loop, then it cannot receive queued signals or posted events.
884
885 By default, a QObject lives in the thread in which it is created.
886 An object's thread affinity can be queried using thread() and
887 changed using moveToThread().
888
889 All QObjects must live in the same thread as their parent. Consequently:
890
891 \list
892 \li setParent() will fail if the two QObjects involved live in
893 different threads.
894 \li When a QObject is moved to another thread, all its children
895 will be automatically moved too.
896 \li moveToThread() will fail if the QObject has a parent.
897 \li If QObjects are created within QThread::run(), they cannot
898 become children of the QThread object because the QThread does
899 not live in the thread that calls QThread::run().
900 \endlist
901
902 \note A QObject's member variables \e{do not} automatically become
903 its children. The parent-child relationship must be set by either
904 passing a pointer to the child's \l{QObject()}{constructor}, or by
905 calling setParent(). Without this step, the object's member variables
906 will remain in the old thread when moveToThread() is called.
907
908 \target No copy constructor
909 \section1 No Copy Constructor or Assignment Operator
910
911 QObject has neither a copy constructor nor an assignment operator.
912 This is by design. Actually, they are declared, but in a
913 \c{private} section with the macro Q_DISABLE_COPY(). In fact, all
914 Qt classes derived from QObject (direct or indirect) use this
915 macro to declare their copy constructor and assignment operator to
916 be private. The reasoning is found in the discussion on
917 \l{Identity vs Value} {Identity vs Value} on the Qt \l{Object
918 Model} page.
919
920 The main consequence is that you should use pointers to QObject
921 (or to your QObject subclass) where you might otherwise be tempted
922 to use your QObject subclass as a value. For example, without a
923 copy constructor, you can't use a subclass of QObject as the value
924 to be stored in one of the container classes. You must store
925 pointers.
926
927 \section1 Auto-Connection
928
929 Qt's meta-object system provides a mechanism to automatically connect
930 signals and slots between QObject subclasses and their children. As long
931 as objects are defined with suitable object names, and slots follow a
932 simple naming convention, this connection can be performed at run-time
933 by the QMetaObject::connectSlotsByName() function.
934
935 \l uic generates code that invokes this function to enable
936 auto-connection to be performed between widgets on forms created
937 with \e{\QD}. More information about using auto-connection with \e{\QD} is
938 given in the \l{Using a Qt Widgets Designer UI File in Your Application} section of
939 the \l{Qt Widgets Designer Manual}{\QD} manual.
940
941 \section1 Dynamic Properties
942
943 Dynamic properties can be added to and removed from QObject
944 instances at run-time. Dynamic properties do not need to be declared at
945 compile-time, yet they provide the same advantages as static properties
946 and are manipulated using the same API - using property() to read them
947 and setProperty() to write them.
948
949 Dynamic properties are supported by
950 \l{Qt Widgets Designer's Widget Editing Mode#The Property Editor}{\QD},
951 and both standard Qt widgets and user-created forms can be given dynamic
952 properties.
953
954 \section1 Internationalization (I18n)
955
956 All QObject subclasses support Qt's translation features, making it possible
957 to translate an application's user interface into different languages.
958
959 To make user-visible text translatable, it must be wrapped in calls to
960 the tr() function. This is explained in detail in the
961 \l{Writing Source Code for Translation} document.
962
963 \sa QMetaObject, QPointer, QObjectCleanupHandler, Q_DISABLE_COPY()
964 \sa {Object Trees & Ownership}
965*/
966
967/*****************************************************************************
968 QObject member functions
969 *****************************************************************************/
970
971// check the constructor's parent thread argument
972static bool check_parent_thread(QObject *parent,
973 QThreadData *parentThreadData,
974 QThreadData *currentThreadData)
975{
976 if (parent && parentThreadData != currentThreadData) {
977 QThread *parentThread = parentThreadData->thread.loadAcquire();
978 QThread *currentThread = currentThreadData->thread.loadAcquire();
979 qWarning("QObject: Cannot create children for a parent that is in a different thread.\n"
980 "(Parent is %s(%p), parent's thread is %s(%p), current thread is %s(%p)",
981 parent->metaObject()->className(),
982 parent,
983 parentThread ? parentThread->metaObject()->className() : "QThread",
984 parentThread,
985 currentThread ? currentThread->metaObject()->className() : "QThread",
986 currentThread);
987 return false;
988 }
989 return true;
990}
991
992/*!
993 Constructs an object with parent object \a parent.
994
995 The parent of an object may be viewed as the object's owner. For
996 instance, a \l{QDialog}{dialog box} is the parent of the \uicontrol{OK}
997 and \uicontrol{Cancel} buttons it contains.
998
999 The destructor of a parent object destroys all child objects.
1000
1001 Setting \a parent to \nullptr constructs an object with no parent. If the
1002 object is a widget, it will become a top-level window.
1003
1004 \sa parent(), findChild(), findChildren()
1005*/
1006
1007QObject::QObject(QObject *parent)
1008 : QObject(*new QObjectPrivate, parent)
1009{
1010}
1011
1012/*!
1013 \internal
1014 */
1015QObject::QObject(QObjectPrivate &dd, QObject *parent)
1016 : d_ptr(&dd)
1017{
1018 Q_ASSERT_X(this != parent, Q_FUNC_INFO, "Cannot parent a QObject to itself");
1019
1020 Q_D(QObject);
1021 d_ptr->q_ptr = this;
1022 QThreadData *parentThreadData = parent ? parent->d_func()->threadData.loadRelaxed() : nullptr;
1023 QThreadData *threadData;
1024 if (parent && !parentThreadData->thread.loadRelaxed()) {
1025 threadData = parentThreadData;
1026 } else {
1027 threadData = QThreadData::current();
1028 if (!check_parent_thread(parent, parentThreadData, threadData))
1029 parent = nullptr;
1030 }
1031 threadData->ref();
1032 d->threadData.storeRelaxed(threadData);
1033
1034 if (parent) {
1035 // Protect against setParent() throwing (we send an event to the parent).
1036 auto scopeDeref = qScopeGuard([threadData] { threadData->deref(); });
1037 if (d->willBeWidget) {
1038 d->parent = parent;
1039 d->parent->d_func()->children.append(this);
1040 // no events sent here, this is done at the end of the QWidget constructor
1041 } else {
1042 setParent(parent);
1043 }
1044 scopeDeref.dismiss();
1045 }
1046
1047 // Neither the hook nor the trace should throw or otherwise halt this
1048 // object's creation. It's a bug in them if they do.
1049 if (Q_UNLIKELY(qtHookData[QHooks::AddQObject]))
1050 reinterpret_cast<QHooks::AddQObjectCallback>(qtHookData[QHooks::AddQObject])(this);
1051 Q_TRACE(QObject_ctor, this);
1052}
1053
1054void QObjectPrivate::clearBindingStorage()
1055{
1056 bindingStorage.clear();
1057}
1058
1059/*!
1060 Destroys the object, deleting all its child objects.
1061
1062 All signals to and from the object are automatically disconnected, and
1063 any pending posted events for the object are removed from the event
1064 queue. However, it is often safer to use deleteLater() rather than
1065 deleting a QObject subclass directly.
1066
1067 \warning All child objects are deleted. If any of these objects
1068 are on the stack or global, sooner or later your program will
1069 crash. We do not recommend holding pointers to child objects from
1070 outside the parent. If you still do, the destroyed() signal gives
1071 you an opportunity to detect when an object is destroyed.
1072
1073 \warning Deleting a QObject while it is handling an event
1074 delivered to it can cause a crash. You must not delete the QObject
1075 directly if it exists in a different thread than the one currently
1076 executing. Use deleteLater() instead, which will cause the event
1077 loop to delete the object after all pending events have been
1078 delivered to it.
1079
1080 \sa deleteLater()
1081*/
1082
1083QObject::~QObject()
1084{
1085 Q_D(QObject);
1086 d->wasDeleted = true;
1087 d->blockSig = 0; // unblock signals so we always emit destroyed()
1088
1089 if (!d->bindingStorage.isValid()) {
1090 // this might be the case after an incomplete thread-move
1091 // remove this object from the pending list in that case
1092 if (QThread *ownThread = thread()) {
1093 auto *privThread = static_cast<QThreadPrivate *>(
1094 QObjectPrivate::get(ownThread));
1095 privThread->removeObjectWithPendingBindingStatusChange(this);
1096 }
1097 }
1098
1099 // If we reached this point, we need to clear the binding data
1100 // as the corresponding properties are no longer useful
1101 d->clearBindingStorage();
1102
1103 QtSharedPointer::ExternalRefCountData *sharedRefcount = d->sharedRefcount.loadRelaxed();
1104 if (sharedRefcount) {
1105 if (sharedRefcount->strongref.loadRelaxed() > 0) {
1106 qWarning("QObject: shared QObject was deleted directly. The program is malformed and may crash.");
1107 // but continue deleting, it's too late to stop anyway
1108 }
1109
1110 // indicate to all QWeakPointers that this QObject has now been deleted
1111 sharedRefcount->strongref.storeRelaxed(0);
1112 if (!sharedRefcount->weakref.deref())
1113 delete sharedRefcount;
1114 }
1115
1116 if (!d->wasWidget && d->isSignalConnected(0)) {
1117 emit destroyed(this);
1118 }
1119
1120 if (!d->isDeletingChildren && d->declarativeData && QAbstractDeclarativeData::destroyed)
1121 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1122
1123 QObjectPrivate::ConnectionData *cd = d->connections.loadAcquire();
1124 if (cd) {
1125 if (cd->currentSender) {
1126 cd->currentSender->receiverDeleted();
1127 cd->currentSender = nullptr;
1128 }
1129
1130 QBasicMutex *signalSlotMutex = signalSlotLock(this);
1131 QMutexLocker locker(signalSlotMutex);
1132
1133 // disconnect all receivers
1134 int receiverCount = cd->signalVectorCount();
1135 for (int signal = -1; signal < receiverCount; ++signal) {
1136 QObjectPrivate::ConnectionList &connectionList = cd->connectionsForSignal(signal);
1137
1138 while (QObjectPrivate::Connection *c = connectionList.first.loadRelaxed()) {
1139 Q_ASSERT(c->receiver.loadAcquire());
1140
1141 QBasicMutex *m = signalSlotLock(c->receiver.loadRelaxed());
1142 bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
1143 if (c == connectionList.first.loadAcquire() && c->receiver.loadAcquire()) {
1144 cd->removeConnection(c);
1145 Q_ASSERT(connectionList.first.loadRelaxed() != c);
1146 }
1147 if (needToUnlock)
1148 m->unlock();
1149 }
1150 }
1151
1152 /* Disconnect all senders:
1153 */
1154 const Qt::HANDLE currentThreadId = QThread::currentThreadId();
1155 while (QObjectPrivate::Connection *node = cd->senders) {
1156 Q_ASSERT(node->receiver.loadAcquire());
1157 QObject *sender = node->sender;
1158 // Notify sender before removing the connection from its list. If sender is being
1159 // destroyed too, this makes its destructor block on the receiver's lock (which we
1160 // hold) and not finish until we release it, so sender stays alive while
1161 // disconnectNotifySender() touches it.
1162 disconnectNotifySender(sender, node->signal_index, currentThreadId);
1163 QBasicMutex *m = signalSlotLock(sender);
1164 bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
1165 //the node has maybe been removed while the mutex was unlocked in relock?
1166 if (node != cd->senders) {
1167 // We hold the wrong mutex
1168 Q_ASSERT(needToUnlock);
1169 m->unlock();
1170 continue;
1171 }
1172
1173 QObjectPrivate::ConnectionData *senderData = sender->d_func()->connections.loadRelaxed();
1174 Q_ASSERT(senderData);
1175
1176 QtPrivate::QSlotObjectBase *slotObj = nullptr;
1177 if (node->isSlotObject) {
1178 slotObj = node->slotObj;
1179 node->isSlotObject = false;
1180 }
1181
1182 senderData->removeConnection(node);
1183 /*
1184 When we unlock, another thread has the chance to delete/modify sender data.
1185 Thus we need to call cleanOrphanedConnections before unlocking. We use the
1186 variant of the function which assumes that the lock is already held to avoid
1187 a deadlock.
1188 We need to hold m, the sender lock. Considering that we might execute arbitrary user
1189 code, we should already release the signalSlotMutex here – unless they are the same.
1190 */
1191 const bool locksAreTheSame = signalSlotMutex == m;
1192 if (!locksAreTheSame)
1193 locker.unlock();
1194 senderData->cleanOrphanedConnections(
1195 sender,
1196 QObjectPrivate::ConnectionData::AlreadyLockedAndTemporarilyReleasingLock
1197 );
1198 if (needToUnlock)
1199 m->unlock();
1200
1201 if (locksAreTheSame) // otherwise already unlocked
1202 locker.unlock();
1203 if (slotObj)
1204 slotObj->destroyIfLastRef();
1205 locker.relock();
1206 }
1207
1208 // invalidate all connections on the object and make sure
1209 // activate() will skip them
1210 cd->currentConnectionId.storeRelaxed(0);
1211 }
1212 if (cd && !cd->ref.deref())
1213 delete cd;
1214 d->connections.storeRelaxed(nullptr);
1215
1216 if (!d->children.isEmpty())
1217 d->deleteChildren();
1218
1219 if (Q_UNLIKELY(qtHookData[QHooks::RemoveQObject]))
1220 reinterpret_cast<QHooks::RemoveQObjectCallback>(qtHookData[QHooks::RemoveQObject])(this);
1221
1222 Q_TRACE(QObject_dtor, this);
1223
1224 if (d->parent) // remove it from parent object
1225 d->setParent_helper(nullptr);
1226}
1227
1228inline QObjectPrivate::Connection::~Connection()
1229{
1230 if (ownArgumentTypes) {
1231 const int *v = argumentTypes.loadRelaxed();
1232 if (v != &DIRECT_CONNECTION_ONLY)
1233 delete[] v;
1234 }
1235 if (isSlotObject)
1236 slotObj->destroyIfLastRef();
1237}
1238
1239
1240/*!
1241 \fn const QMetaObject *QObject::metaObject() const
1242
1243 Returns a pointer to the meta-object of this object.
1244
1245 A meta-object contains information about a class that inherits
1246 QObject, e.g. class name, superclass name, properties, signals and
1247 slots. Every QObject subclass that contains the Q_OBJECT macro will have a
1248 meta-object.
1249
1250 The meta-object information is required by the signal/slot
1251 connection mechanism and the property system. The inherits()
1252 function also makes use of the meta-object.
1253
1254 If you have no pointer to an actual object instance but still
1255 want to access the meta-object of a class, you can use \l
1256 staticMetaObject.
1257
1258 Example:
1259
1260 \snippet code/src_corelib_kernel_qobject.cpp 1
1261
1262 \sa staticMetaObject
1263*/
1264
1265/*!
1266 \variable QObject::staticMetaObject
1267
1268 This variable stores the meta-object for the class.
1269
1270 A meta-object contains information about a class that inherits
1271 QObject, e.g. class name, superclass name, properties, signals and
1272 slots. Every class that contains the Q_OBJECT macro will also have
1273 a meta-object.
1274
1275 The meta-object information is required by the signal/slot
1276 connection mechanism and the property system. The inherits()
1277 function also makes use of the meta-object.
1278
1279 If you have a pointer to an object, you can use metaObject() to
1280 retrieve the meta-object associated with that object.
1281
1282 Example:
1283
1284 \snippet code/src_corelib_kernel_qobject.cpp 2
1285
1286 \sa metaObject()
1287*/
1288
1289/*!
1290 \fn template <class T> T qobject_cast(QObject *object)
1291 \fn template <class T> T qobject_cast(const QObject *object)
1292 \relates QObject
1293
1294 Returns the given \a object cast to type T if the object is of type
1295 T (or of a subclass); otherwise returns \nullptr. If \a object is
1296 \nullptr then it will also return \nullptr.
1297
1298 The class T must inherit (directly or indirectly) QObject and be
1299 declared with the \l Q_OBJECT macro.
1300
1301 A class is considered to inherit itself.
1302
1303 Example:
1304
1305 \snippet code/src_corelib_kernel_qobject.cpp 3
1306
1307 The qobject_cast() function behaves similarly to the standard C++
1308 \c dynamic_cast(), with the advantages that it doesn't require
1309 RTTI support and it works across dynamic library boundaries.
1310
1311 qobject_cast() can also be used in conjunction with interfaces.
1312
1313 \warning If T isn't declared with the Q_OBJECT macro, this
1314 function's return value is undefined.
1315
1316 \sa QObject::inherits()
1317*/
1318
1319/*!
1320 \fn bool QObject::inherits(const char *className) const
1321
1322 Returns \c true if this object is an instance of a class that
1323 inherits \a className or a QObject subclass that inherits \a
1324 className; otherwise returns \c false.
1325
1326 A class is considered to inherit itself.
1327
1328 Example:
1329
1330 \snippet code/src_corelib_kernel_qobject.cpp 4
1331
1332 If you need to determine whether an object is an instance of a particular
1333 class for the purpose of casting it, consider using qobject_cast<Type *>(object)
1334 instead.
1335
1336 \sa metaObject(), qobject_cast()
1337*/
1338
1339/*!
1340 \property QObject::objectName
1341
1342 \brief the name of this object
1343
1344 You can find an object by name (and type) using findChild().
1345 You can find a set of objects with findChildren().
1346
1347 \snippet code/src_corelib_kernel_qobject.cpp 5
1348
1349 By default, this property contains an empty string.
1350
1351 \sa metaObject(), QMetaObject::className()
1352*/
1353
1354QString QObject::objectName() const
1355{
1356 Q_D(const QObject);
1357#if QT_CONFIG(thread)
1358 if (QThread::currentThreadId() != d->threadData.loadRelaxed()->threadId.loadRelaxed()) // Unsafe code path
1359 return d->extraData ? d->extraData->objectName.valueBypassingBindings() : QString();
1360#endif
1361 if (!d->extraData && QtPrivate::isAnyBindingEvaluating()) {
1362 QObjectPrivate *dd = const_cast<QObjectPrivate *>(d);
1363 // extraData is mutable, so this should be safe
1364 dd->extraData = new QObjectPrivate::ExtraData(dd);
1365 }
1366 return d->extraData ? d->extraData->objectName : QString();
1367}
1368
1369/*!
1370 \internal
1371 Only use if you know nothing can be bound yet. Usually used for
1372 internal objects that do get names.
1373*/
1374void QObjectPrivate::setObjectNameWithoutBindings(const QString &name)
1375{
1376 ensureExtraData();
1377 extraData->objectName.setValueBypassingBindings(name);
1378}
1379
1380/*!
1381 \fn void QObject::setObjectName(const QString &name)
1382 Sets the object's name to \a name.
1383*/
1384void QObject::doSetObjectName(const QString &name)
1385{
1386 Q_D(QObject);
1387
1388 d->ensureExtraData();
1389
1390 d->extraData->objectName.removeBindingUnlessInWrapper();
1391
1392 if (d->extraData->objectName.valueBypassingBindings() != name) {
1393 d->extraData->objectName.setValueBypassingBindings(name);
1394 d->extraData->objectName.notify(); // also emits a signal
1395 }
1396}
1397
1398/*!
1399 \overload
1400 \since 6.4
1401*/
1402void QObject::setObjectName(QAnyStringView name)
1403{
1404 Q_D(QObject);
1405
1406 d->ensureExtraData();
1407
1408 d->extraData->objectName.removeBindingUnlessInWrapper();
1409
1410 if (d->extraData->objectName.valueBypassingBindings() != name) {
1411 d->extraData->objectName.setValueBypassingBindings(name.toString());
1412 d->extraData->objectName.notify(); // also emits a signal
1413 }
1414}
1415
1416QBindable<QString> QObject::bindableObjectName()
1417{
1418 Q_D(QObject);
1419
1420 d->ensureExtraData();
1421
1422 return QBindable<QString>(&d->extraData->objectName);
1423}
1424
1425/*! \fn void QObject::objectNameChanged(const QString &objectName)
1426
1427 This signal is emitted after the object's name has been changed. The new object name is passed as \a objectName.
1428
1429 \sa QObject::objectName
1430*/
1431
1432/*!
1433 \fn bool QObject::isWidgetType() const
1434
1435 Returns \c true if the object is a widget; otherwise returns \c false.
1436
1437 Calling this function is equivalent to calling
1438 \c{inherits("QWidget")}, except that it is much faster.
1439*/
1440
1441/*!
1442 \fn bool QObject::isWindowType() const
1443
1444 Returns \c true if the object is a window; otherwise returns \c false.
1445
1446 Calling this function is equivalent to calling
1447 \c{inherits("QWindow")}, except that it is much faster.
1448*/
1449
1450/*!
1451 \fn bool QObject::isQuickItemType() const
1452
1453 Returns \c true if the object is a QQuickItem; otherwise returns \c false.
1454
1455 Calling this function is equivalent to calling
1456 \c{inherits("QQuickItem")}, except that it is much faster.
1457
1458 \since 6.4
1459*/
1460
1461/*!
1462 Returns whether the object has been created by the QML engine or
1463 ownership has been explicitly set via QJSEngine::setObjectOwnership().
1464 \since 6.11
1465*/
1466bool QObject::isQmlExposed() const noexcept
1467{
1468 Q_D(const QObject);
1469 return !d->isDeletingChildren && d->declarativeData;
1470}
1471
1472/*!
1473 This virtual function receives events to an object and should
1474 return true if the event \a e was recognized and processed.
1475
1476 The event() function can be reimplemented to customize the
1477 behavior of an object.
1478
1479 Make sure you call the parent event class implementation
1480 for all the events you did not handle.
1481
1482 Example:
1483
1484 \snippet code/src_corelib_kernel_qobject.cpp 52
1485
1486 \sa installEventFilter(), timerEvent(), QCoreApplication::sendEvent(),
1487 QCoreApplication::postEvent()
1488*/
1489
1490bool QObject::event(QEvent *e)
1491{
1492 switch (e->type()) {
1493 case QEvent::Timer:
1494 timerEvent((QTimerEvent *)e);
1495 break;
1496
1497 case QEvent::ChildAdded:
1498 case QEvent::ChildPolished:
1499 case QEvent::ChildRemoved:
1500 childEvent((QChildEvent *)e);
1501 break;
1502
1503 case QEvent::DeferredDelete:
1504 delete this;
1505 break;
1506
1507 case QEvent::DisconnectNotify: {
1508 // Posted by disconnectNotifySender(), now that we are in our own thread
1509 const QMetaObject *mo = metaObject();
1510 const int signalIndex = static_cast<QDisconnectNotifyEvent *>(e)->signalIndex();
1511 disconnectNotify(QMetaObjectPrivate::signal(mo, signalIndex));
1512 break;
1513 }
1514
1515 case QEvent::MetaCall:
1516 {
1517 QAbstractMetaCallEvent *mce = static_cast<QAbstractMetaCallEvent*>(e);
1518
1519 QObjectPrivate::ConnectionData *connections = d_func()->connections.loadAcquire();
1520 if (!connections) {
1521 QMutexLocker locker(signalSlotLock(this));
1522 d_func()->ensureConnectionData();
1523 connections = d_func()->connections.loadRelaxed();
1524 }
1525 QObjectPrivate::Sender sender(this, const_cast<QObject*>(mce->sender()), mce->signalId(), connections);
1526
1527 mce->placeMetaCall(this);
1528 break;
1529 }
1530
1531 case QEvent::ThreadChange: {
1532 Q_D(QObject);
1533 QThreadData *threadData = d->threadData.loadRelaxed();
1534 QAbstractEventDispatcher *eventDispatcher = threadData->eventDispatcher.loadRelaxed();
1535 if (eventDispatcher) {
1536 QList<QAbstractEventDispatcher::TimerInfoV2> timers = eventDispatcher->timersForObject(this);
1537 if (!timers.isEmpty()) {
1538 const bool res = eventDispatcher->unregisterTimers(this);
1539 // do not to release our timer ids back to the pool (since the timer ids are moving to a new thread).
1540 Q_ASSERT_X(res, Q_FUNC_INFO,
1541 "QAbstractEventDispatcher::unregisterTimers() returned false,"
1542 " but there are timers associated with this object.");
1543 auto reRegisterTimers = [this, timers = std::move(timers)]() {
1544 QAbstractEventDispatcher *eventDispatcher =
1545 d_func()->threadData.loadRelaxed()->eventDispatcher.loadRelaxed();
1546 for (const auto &ti : timers)
1547 eventDispatcher->registerTimer(ti.timerId, ti.interval, ti.timerType, this);
1548 };
1549 QMetaObject::invokeMethod(this, std::move(reRegisterTimers), Qt::QueuedConnection);
1550 }
1551 }
1552 break;
1553 }
1554
1555 default:
1556 if (e->type() >= QEvent::User) {
1557 customEvent(e);
1558 break;
1559 }
1560 return false;
1561 }
1562 return true;
1563}
1564
1565/*!
1566 \fn void QObject::timerEvent(QTimerEvent *event)
1567
1568 This event handler can be reimplemented in a subclass to receive
1569 timer events for the object.
1570
1571 QChronoTimer provides higher-level interfaces to the timer functionality,
1572 and also more general information about timers. The timer event is passed
1573 in the \a event parameter.
1574
1575 \sa startTimer(), killTimer(), event()
1576*/
1577
1578void QObject::timerEvent(QTimerEvent *)
1579{
1580}
1581
1582
1583/*!
1584 This event handler can be reimplemented in a subclass to receive
1585 child events. The event is passed in the \a event parameter.
1586
1587 QEvent::ChildAdded and QEvent::ChildRemoved events are sent to
1588 objects when children are added or removed. In both cases you can
1589 only rely on the child being a QObject, or if isWidgetType()
1590 returns \c true, a QWidget. (This is because, in the
1591 \l{QEvent::ChildAdded}{ChildAdded} case, the child is not yet
1592 fully constructed, and in the \l{QEvent::ChildRemoved}{ChildRemoved}
1593 case it might have been destructed already).
1594
1595 QEvent::ChildPolished events are sent to widgets when children
1596 are polished, or when polished children are added. If you receive
1597 a child polished event, the child's construction is usually
1598 completed. However, this is not guaranteed, and multiple polish
1599 events may be delivered during the execution of a widget's
1600 constructor.
1601
1602 For every child widget, you receive one
1603 \l{QEvent::ChildAdded}{ChildAdded} event, zero or more
1604 \l{QEvent::ChildPolished}{ChildPolished} events, and one
1605 \l{QEvent::ChildRemoved}{ChildRemoved} event.
1606
1607 The \l{QEvent::ChildPolished}{ChildPolished} event is omitted if
1608 a child is removed immediately after it is added. If a child is
1609 polished several times during construction and destruction, you
1610 may receive several child polished events for the same child,
1611 each time with a different virtual table.
1612
1613 \sa event()
1614*/
1615
1616void QObject::childEvent(QChildEvent * /* event */)
1617{
1618}
1619
1620
1621/*!
1622 This event handler can be reimplemented in a subclass to receive
1623 custom events. Custom events are user-defined events with a type
1624 value at least as large as the QEvent::User item of the
1625 QEvent::Type enum, and is typically a QEvent subclass. The event
1626 is passed in the \a event parameter.
1627
1628 \sa event(), QEvent
1629*/
1630void QObject::customEvent(QEvent * /* event */)
1631{
1632}
1633
1634
1635
1636/*!
1637 Filters events if this object has been installed as an event
1638 filter for the \a watched object.
1639
1640 In your reimplementation of this function, if you want to filter
1641 the \a event out, i.e. stop it being handled further, return
1642 true; otherwise return false.
1643
1644 Example:
1645 \snippet code/src_corelib_kernel_qobject.cpp 6
1646
1647 Notice in the example above that unhandled events are passed to
1648 the base class's eventFilter() function, since the base class
1649 might have reimplemented eventFilter() for its own internal
1650 purposes.
1651
1652 Some events, such as \l QEvent::ShortcutOverride must be explicitly
1653 accepted (by calling \l {QEvent::}{accept()} on them) in order to prevent
1654 propagation.
1655
1656 \warning If you delete the receiver object in this function, be
1657 sure to return true. Otherwise, Qt will forward the event to the
1658 deleted object and the program might crash.
1659
1660 \sa installEventFilter()
1661*/
1662
1663bool QObject::eventFilter(QObject * /* watched */, QEvent * /* event */)
1664{
1665 return false;
1666}
1667
1668/*!
1669 \fn bool QObject::signalsBlocked() const
1670
1671 Returns \c true if signals are blocked; otherwise returns \c false.
1672
1673 Signals are not blocked by default.
1674
1675 \sa blockSignals(), QSignalBlocker
1676*/
1677
1678/*!
1679 If \a block is true, signals emitted by this object are blocked
1680 (i.e., emitting a signal will not invoke anything connected to it).
1681 If \a block is false, no such blocking will occur.
1682
1683 The return value is the previous value of signalsBlocked().
1684
1685 Note that the destroyed() signal will be emitted even if the signals
1686 for this object have been blocked.
1687
1688 Signals emitted while being blocked are not buffered.
1689
1690 \sa signalsBlocked(), QSignalBlocker
1691*/
1692
1693bool QObject::blockSignals(bool block) noexcept
1694{
1695 Q_D(QObject);
1696 bool previous = d->blockSig;
1697 d->blockSig = block;
1698 return previous;
1699}
1700
1701/*!
1702 Returns the thread in which the object lives.
1703
1704 \sa moveToThread()
1705*/
1706QThread *QObject::thread() const
1707{
1708 return d_func()->threadData.loadRelaxed()->thread.loadAcquire();
1709}
1710
1711/*!
1712 Changes the thread affinity for this object and its children and
1713 returns \c true on success. The object cannot be moved if it has a
1714 parent. Event processing will continue in the \a targetThread.
1715
1716 To move an object to the main thread, use QApplication::instance()
1717 to retrieve a pointer to the current application, and then use
1718 QApplication::thread() to retrieve the thread in which the
1719 application lives. For example:
1720
1721 \snippet code/src_corelib_kernel_qobject.cpp 7
1722
1723 If \a targetThread is \nullptr, all event processing for this object
1724 and its children stops, as they are no longer associated with any
1725 thread.
1726
1727 Note that all active timers for the object will be reset. The
1728 timers are first stopped in the current thread and restarted (with
1729 the same interval) in the \a targetThread. As a result, constantly
1730 moving an object between threads can postpone timer events
1731 indefinitely.
1732
1733 A QEvent::ThreadChange event is sent to this object just before
1734 the thread affinity is changed. You can handle this event to
1735 perform any special processing. Note that any new events that are
1736 posted to this object will be handled in the \a targetThread,
1737 provided it is not \nullptr: when it is \nullptr, no event processing
1738 for this object or its children can happen, as they are no longer
1739 associated with any thread.
1740
1741 \warning This function is \e not thread-safe; the current thread
1742 must be same as the current thread affinity. In other words, this
1743 function can only "push" an object from the current thread to
1744 another thread, it cannot "pull" an object from any arbitrary
1745 thread to the current thread. There is one exception to this rule
1746 however: objects with no thread affinity can be "pulled" to the
1747 current thread.
1748
1749 In Qt versions prior to 6.7, this function had no return value (\c void).
1750
1751 \sa thread()
1752 */
1753bool QObject::moveToThread(QThread *targetThread QT6_IMPL_NEW_OVERLOAD_TAIL)
1754{
1755 Q_D(QObject);
1756
1757 if (d->threadData.loadRelaxed()->thread.loadAcquire() == targetThread) {
1758 // object is already in this thread
1759 return true;
1760 }
1761
1762 if (d->parent != nullptr) {
1763 qWarning("QObject::moveToThread: Cannot move objects with a parent");
1764 return false;
1765 }
1766 if (d->isWidget) {
1767 qWarning("QObject::moveToThread: Widgets cannot be moved to a new thread");
1768 return false;
1769 }
1770 if (!d->bindingStorage.isEmpty()) {
1771 qWarning("QObject::moveToThread: Can not move objects that contain bindings or are used in bindings to a new thread.");
1772 return false;
1773 }
1774
1775 QThreadData *currentData = QThreadData::current();
1776 QThreadData *targetData = targetThread ? QThreadData::get2(targetThread) : nullptr;
1777 QThreadData *thisThreadData = d->threadData.loadAcquire();
1778 if (!thisThreadData->thread.loadRelaxed() && currentData == targetData) {
1779 // one exception to the rule: we allow moving objects with no thread affinity to the current thread
1780 currentData = thisThreadData;
1781 } else if (thisThreadData != currentData) {
1782 qWarning("QObject::moveToThread: Current thread (%p) is not the object's thread (%p).\n"
1783 "Cannot move to target thread (%p)\n",
1784 currentData->thread.loadRelaxed(), thisThreadData->thread.loadRelaxed(), targetData ? targetData->thread.loadRelaxed() : nullptr);
1785
1786#ifdef Q_OS_DARWIN
1787 qWarning("You might be loading two sets of Qt binaries into the same process. "
1788 "Check that all plugins are compiled against the right Qt binaries. Export "
1789 "DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded.");
1790#endif
1791
1792 return false;
1793 }
1794
1795 // prepare to move
1796 d->moveToThread_helper();
1797
1798 if (!targetData)
1799 targetData = new QThreadData(0);
1800
1801 // make sure nobody adds/removes connections to this object while we're moving it
1802 QMutexLocker l(signalSlotLock(this));
1803
1804 QOrderedMutexLocker locker(&currentData->postEventList.mutex,
1805 &targetData->postEventList.mutex);
1806
1807 // keep currentData alive (since we've got it locked)
1808 currentData->ref();
1809
1810 // move the object
1811 auto threadPrivate = targetThread
1812 ? static_cast<QThreadPrivate *>(QThreadPrivate::get(targetThread))
1813 : nullptr;
1814 QBindingStatus *bindingStatus = threadPrivate
1815 ? threadPrivate->bindingStatus()
1816 : nullptr;
1817 if (threadPrivate && !bindingStatus) {
1818 bindingStatus = threadPrivate->addObjectWithPendingBindingStatusChange(this);
1819 }
1820 d_func()->setThreadData_helper(currentData, targetData, bindingStatus);
1821
1822 locker.unlock();
1823
1824 // now currentData can commit suicide if it wants to
1825 currentData->deref();
1826 return true;
1827}
1828
1829void QObjectPrivate::moveToThread_helper()
1830{
1831 Q_Q(QObject);
1832 QEvent e(QEvent::ThreadChange);
1833 QCoreApplication::sendEvent(q, &e);
1834 bindingStorage.clear();
1835 for (int i = 0; i < children.size(); ++i) {
1836 QObject *child = children.at(i);
1837 child->d_func()->moveToThread_helper();
1838 }
1839}
1840
1841void QObjectPrivate::setThreadData_helper(QThreadData *currentData, QThreadData *targetData, QBindingStatus *status)
1842{
1843 Q_Q(QObject);
1844
1845 if (status) {
1846 // the new thread is already running
1847 this->bindingStorage.bindingStatus = status;
1848 }
1849
1850 // move posted events
1851 qsizetype eventsMoved = 0;
1852 for (qsizetype i = 0; i < currentData->postEventList.size(); ++i) {
1853 const QPostEvent &pe = currentData->postEventList.at(i);
1854 if (!pe.event)
1855 continue;
1856 if (pe.receiver == q) {
1857 // move this post event to the targetList
1858 targetData->postEventList.addEvent(pe);
1859 const_cast<QPostEvent &>(pe).event = nullptr;
1860 ++eventsMoved;
1861 }
1862 }
1863 if (eventsMoved > 0 && targetData->hasEventDispatcher()) {
1864 targetData->canWait = false;
1865 targetData->eventDispatcher.loadRelaxed()->wakeUp();
1866 }
1867
1868 // the current emitting thread shouldn't restore currentSender after calling moveToThread()
1869 ConnectionData *cd = connections.loadAcquire();
1870 if (cd) {
1871 if (cd->currentSender) {
1872 cd->currentSender->receiverDeleted();
1873 cd->currentSender = nullptr;
1874 }
1875
1876 // adjust the receiverThreadId values in the Connections
1877 if (cd) {
1878 auto *c = cd->senders;
1879 while (c) {
1880 QObject *r = c->receiver.loadRelaxed();
1881 if (r) {
1882 Q_ASSERT(r == q);
1883 targetData->ref();
1884 QThreadData *old = c->receiverThreadData.loadRelaxed();
1885 if (old)
1886 old->deref();
1887 c->receiverThreadData.storeRelaxed(targetData);
1888 }
1889 c = c->next;
1890 }
1891 }
1892
1893 }
1894
1895 // set new thread data
1896 targetData->ref();
1897 threadData.loadRelaxed()->deref();
1898
1899 // synchronizes with loadAcquire e.g. in QCoreApplication::postEvent
1900 threadData.storeRelease(targetData);
1901
1902 for (int i = 0; i < children.size(); ++i) {
1903 QObject *child = children.at(i);
1904 child->d_func()->setThreadData_helper(currentData, targetData, status);
1905 }
1906}
1907
1908//
1909// The timer flag hasTimer is set when startTimer is called.
1910// It is not reset when killing the timer because more than
1911// one timer might be active.
1912//
1913
1914/*!
1915 \fn int QObject::startTimer(int interval, Qt::TimerType timerType)
1916
1917 This is an overloaded function that will start a timer of type
1918 \a timerType and a timeout of \a interval milliseconds. This is
1919 equivalent to calling:
1920 \code
1921 startTimer(std::chrono::milliseconds{interval}, timerType);
1922 \endcode
1923
1924 \include timers-common.qdocinc negative-intervals-not-allowed
1925
1926 \sa timerEvent(), killTimer(), QChronoTimer, QBasicTimer
1927*/
1928
1929int QObject::startTimer(int interval, Qt::TimerType timerType)
1930{
1931 // no overflow can happen here:
1932 // 2^31 ms * 1,000,000 always fits a 64-bit signed integer type
1933 return startTimer(std::chrono::milliseconds{interval}, timerType);
1934}
1935
1936/*!
1937 \since 5.9
1938 \overload
1939
1940 Starts a timer and returns a timer identifier, or returns zero if
1941 it could not start a timer.
1942
1943 A timer event will occur every \a interval until killTimer()
1944 is called. If \a interval is equal to \c{std::chrono::duration::zero()},
1945 then the timer event occurs once every time control returns to the event
1946 loop. The ordering between these timer events and other sources of events
1947 is unspecified.
1948
1949 \include timers-common.qdocinc negative-intervals-not-allowed
1950
1951 The virtual timerEvent() function is called with the QTimerEvent
1952 event parameter class when a timer event occurs. Reimplement this
1953 function to get timer events.
1954
1955 If multiple timers are running, the QTimerEvent::id() method can be
1956 used to find out which timer was activated.
1957
1958 Example:
1959
1960 \snippet code/src_corelib_kernel_qobject.cpp 8
1961
1962 Note that the accuracy of the timer depends on the underlying operating
1963 system and hardware.
1964
1965 The \a timerType argument allows you to customize the accuracy of
1966 the timer. See Qt::TimerType for information on the different timer types.
1967 Most platforms support an accuracy of 20 milliseconds; some provide more.
1968 If Qt is unable to deliver the requested number of timer events, it will
1969 silently discard some.
1970
1971 The QTimer and QChronoTimer classes provide a high-level programming
1972 interface with single-shot timers and timer signals instead of
1973 events. There is also a QBasicTimer class that is more lightweight than
1974 QChronoTimer but less clumsy than using timer IDs directly.
1975
1976 \note Starting from Qt 6.8 the type of \a interval
1977 is \c std::chrono::nanoseconds, prior to that it was \c
1978 std::chrono::milliseconds. This change is backwards compatible with
1979 older releases of Qt.
1980
1981 \note In Qt 6.8, QObject was changed to use Qt::TimerId to represent timer
1982 IDs. This method converts the TimerId to int for backwards compatibility
1983 reasons, however you can use Qt::TimerId to check the value returned by
1984 this method, for example:
1985 \snippet code/src_corelib_kernel_qobject.cpp invalid-timer-id
1986
1987 \sa timerEvent(), killTimer(), QChronoTimer, QBasicTimer
1988*/
1989int QObject::startTimer(std::chrono::nanoseconds interval, Qt::TimerType timerType)
1990{
1991 Q_D(QObject);
1992
1993 using namespace std::chrono_literals;
1994
1995 if (interval < 0ns) {
1996 qWarning("QObject::startTimer: negative intervals aren't allowed; the "
1997 "interval will be set to 1ms.");
1998 interval = 1ms;
1999 }
2000
2001 auto thisThreadData = d->threadData.loadRelaxed();
2002 if (Q_UNLIKELY(thisThreadData != QThreadData::current())) {
2003 qWarning("QObject::startTimer: Timers cannot be started from another thread");
2004 return 0;
2005 }
2006
2007 auto dispatcher = thisThreadData->eventDispatcher.loadRelaxed();
2008 if (Q_UNLIKELY(!dispatcher)) {
2009 qWarning("QObject::startTimer: current thread's event dispatcher has already been destroyed");
2010 return 0;
2011 }
2012
2013 Qt::TimerId timerId = dispatcher->registerTimer(interval, timerType, this);
2014 d->ensureExtraData();
2015 d->extraData->runningTimers.append(timerId);
2016 return int(timerId);
2017}
2018
2019/*!
2020 Kills the timer with timer identifier, \a id.
2021
2022 The timer identifier is returned by startTimer() when a timer
2023 event is started.
2024
2025 \sa timerEvent(), startTimer()
2026*/
2027
2028void QObject::killTimer(int id)
2029{
2030 killTimer(Qt::TimerId{id});
2031}
2032
2033/*!
2034 \since 6.8
2035 \overload
2036*/
2037void QObject::killTimer(Qt::TimerId id)
2038{
2039 Q_D(QObject);
2040 auto thisThreadData = d->threadData.loadRelaxed();
2041 if (thisThreadData->threadId.loadRelaxed() != QThread::currentThreadId()) {
2042 qWarning("QObject::killTimer: Timers cannot be stopped from another thread");
2043 return;
2044 }
2045 if (id > Qt::TimerId::Invalid) {
2046 qsizetype at = d->extraData ? d->extraData->runningTimers.indexOf(id) : -1;
2047 if (at == -1) {
2048 // timer isn't owned by this object
2049 qWarning("QObject::killTimer(): Error: timer id %d is not valid for object %p (%s, %ls), timer has not been killed",
2050 qToUnderlying(id),
2051 this,
2052 metaObject()->className(),
2053 qUtf16Printable(objectName()));
2054 return;
2055 }
2056
2057 if (thisThreadData->hasEventDispatcher())
2058 thisThreadData->eventDispatcher.loadRelaxed()->unregisterTimer(id);
2059
2060 d->extraData->runningTimers.remove(at);
2061 QAbstractEventDispatcherPrivate::releaseTimerId(id);
2062 }
2063}
2064
2065/*!
2066 \fn QObject *QObject::parent() const
2067
2068 Returns a pointer to the parent object.
2069
2070 \sa children()
2071*/
2072
2073/*!
2074 \fn const QObjectList &QObject::children() const
2075
2076 Returns a list of child objects.
2077 The QObjectList class is defined in the \c{<QObject>} header
2078 file as the following:
2079
2080 \quotefromfile kernel/qobject.h
2081 \skipto /typedef .*QObjectList/
2082 \printuntil QObjectList
2083
2084 The first child added is the \l{QList::first()}{first} object in
2085 the list and the last child added is the \l{QList::last()}{last}
2086 object in the list, i.e. new children are appended at the end.
2087
2088 Note that the list order changes when QWidget children are
2089 \l{QWidget::raise()}{raised} or \l{QWidget::lower()}{lowered}. A
2090 widget that is raised becomes the last object in the list, and a
2091 widget that is lowered becomes the first object in the list.
2092
2093 \sa findChild(), findChildren(), parent(), setParent()
2094*/
2095
2096
2097/*!
2098 \fn template<typename T> T *QObject::findChild(QAnyStringView name, Qt::FindChildOptions options) const
2099
2100 Returns the child of this object that can be cast into type T and
2101 that is called \a name, or \nullptr if there is no such object.
2102 A null \a name argument causes all objects to be matched. An empty,
2103 non-null \a name matches only objects whose \l objectName is empty.
2104 The search is performed recursively, unless \a options specifies the
2105 option FindDirectChildrenOnly.
2106
2107 If there is more than one child matching the search, the most-direct
2108 ancestor is returned. If there are several most-direct ancestors, the
2109 first child in children() will be returned. In that case, it's better
2110 to use findChildren() to get the complete list of all children.
2111
2112 This example returns a child \c{QPushButton} of \c{parentWidget}
2113 named \c{"button1"}, even if the button isn't a direct child of
2114 the parent:
2115
2116 \snippet code/src_corelib_kernel_qobject.cpp 10
2117
2118 This example returns a \c{QListWidget} child of \c{parentWidget}:
2119
2120 \snippet code/src_corelib_kernel_qobject.cpp 11
2121
2122 This example returns a child \c{QPushButton} of \c{parentWidget}
2123 (its direct parent) named \c{"button1"}:
2124
2125 \snippet code/src_corelib_kernel_qobject.cpp 41
2126
2127 This example returns a \c{QListWidget} child of \c{parentWidget},
2128 its direct parent:
2129
2130 \snippet code/src_corelib_kernel_qobject.cpp 42
2131
2132 \note In Qt versions prior to 6.7, this function took \a name as
2133 \c{QString}, not \c{QAnyStringView}.
2134
2135 \sa findChildren()
2136*/
2137
2138/*!
2139 \fn template<typename T> T *QObject::findChild(Qt::FindChildOptions options) const
2140 \overload
2141 \since 6.7
2142
2143 Returns the child of this object that can be cast into type T, or
2144 \nullptr if there is no such object.
2145 The search is performed recursively, unless \a options specifies the
2146 option FindDirectChildrenOnly.
2147
2148 If there is more than one child matching the search, the most-direct ancestor
2149 is returned. If there are several most-direct ancestors, the first child in
2150 children() will be returned. In that case, it's better to use findChildren()
2151 to get the complete list of all children.
2152
2153 \sa findChildren()
2154*/
2155
2156/*!
2157 \fn template<typename T> QList<T> QObject::findChildren(QAnyStringView name, Qt::FindChildOptions options) const
2158
2159 Returns all children of this object with the given \a name that can be
2160 cast to type T, or an empty list if there are no such objects.
2161 A null \a name argument causes all objects to be matched, an empty one
2162 only those whose objectName is empty.
2163 The search is performed recursively, unless \a options specifies the
2164 option FindDirectChildrenOnly.
2165
2166 The following example shows how to find a list of child \c{QWidget}s of
2167 the specified \c{parentWidget} named \c{widgetname}:
2168
2169 \snippet code/src_corelib_kernel_qobject.cpp 12
2170
2171 This example returns all \c{QPushButton}s that are children of \c{parentWidget}:
2172
2173 \snippet code/src_corelib_kernel_qobject.cpp 13
2174
2175 This example returns all \c{QPushButton}s that are immediate children of \c{parentWidget}:
2176
2177 \snippet code/src_corelib_kernel_qobject.cpp 43
2178
2179 \note In Qt versions prior to 6.7, this function took \a name as
2180 \c{QString}, not \c{QAnyStringView}.
2181
2182 \sa findChild()
2183*/
2184
2185/*!
2186 \fn template<typename T> QList<T> QObject::findChildren(Qt::FindChildOptions options) const
2187 \overload
2188 \since 6.3
2189
2190 Returns all children of this object that can be cast to type T, or
2191 an empty list if there are no such objects.
2192 The search is performed recursively, unless \a options specifies the
2193 option FindDirectChildrenOnly.
2194
2195 \sa findChild()
2196*/
2197
2198/*!
2199 \fn template<typename T> QList<T> QObject::findChildren(const QRegularExpression &re, Qt::FindChildOptions options) const
2200 \overload findChildren()
2201
2202 \since 5.0
2203
2204 Returns the children of this object that can be cast to type T
2205 and that have names matching the regular expression \a re,
2206 or an empty list if there are no such objects.
2207 The search is performed recursively, unless \a options specifies the
2208 option FindDirectChildrenOnly.
2209*/
2210
2211static bool matches_objectName_non_null(QObject *obj, QAnyStringView name)
2212{
2213 if (auto ext = QObjectPrivate::get(obj)->extraData)
2214 return ext ->objectName.valueBypassingBindings() == name;
2215 return name.isEmpty();
2216}
2217
2218/*!
2219 \internal
2220*/
2221void qt_qFindChildren_helper(const QObject *parent, QAnyStringView name,
2222 const QMetaObject &mo, QList<void*> *list, Qt::FindChildOptions options)
2223{
2224 Q_ASSERT(parent);
2225 Q_ASSERT(list);
2226 for (QObject *obj : parent->children()) {
2227 if (mo.cast(obj) && (name.isNull() || matches_objectName_non_null(obj, name)))
2228 list->append(obj);
2229 if (options & Qt::FindChildrenRecursively)
2230 qt_qFindChildren_helper(obj, name, mo, list, options);
2231 }
2232}
2233
2234#if QT_CONFIG(regularexpression)
2235/*!
2236 \internal
2237*/
2238void qt_qFindChildren_helper(const QObject *parent, const QRegularExpression &re,
2239 const QMetaObject &mo, QList<void*> *list, Qt::FindChildOptions options)
2240{
2241 Q_ASSERT(parent);
2242 Q_ASSERT(list);
2243 for (QObject *obj : parent->children()) {
2244 if (mo.cast(obj)) {
2245 QRegularExpressionMatch m = re.match(obj->objectName());
2246 if (m.hasMatch())
2247 list->append(obj);
2248 }
2249 if (options & Qt::FindChildrenRecursively)
2250 qt_qFindChildren_helper(obj, re, mo, list, options);
2251 }
2252}
2253#endif // QT_CONFIG(regularexpression)
2254
2255/*!
2256 \internal
2257*/
2258QObject *qt_qFindChild_helper(const QObject *parent, QAnyStringView name, const QMetaObject &mo, Qt::FindChildOptions options)
2259{
2260 Q_ASSERT(parent);
2261 for (QObject *obj : parent->children()) {
2262 if (mo.cast(obj) && (name.isNull() || matches_objectName_non_null(obj, name)))
2263 return obj;
2264 }
2265 if (options & Qt::FindChildrenRecursively) {
2266 for (QObject *child : parent->children()) {
2267 if (QObject *obj = qt_qFindChild_helper(child, name, mo, options))
2268 return obj;
2269 }
2270 }
2271 return nullptr;
2272}
2273
2274/*!
2275 Makes the object a child of \a parent.
2276
2277 \sa parent(), children()
2278*/
2279void QObject::setParent(QObject *parent)
2280{
2281 Q_D(QObject);
2282 Q_ASSERT(!d->isWidget);
2283 d->setParent_helper(parent);
2284}
2285
2286void QObjectPrivate::deleteChildren()
2287{
2288 Q_ASSERT_X(!isDeletingChildren, "QObjectPrivate::deleteChildren()", "isDeletingChildren already set, did this function recurse?");
2289 isDeletingChildren = true;
2290 // delete children objects
2291 // don't use qDeleteAll as the destructor of the child might
2292 // delete siblings
2293 for (int i = 0; i < children.size(); ++i) {
2294 currentChildBeingDeleted = children.at(i);
2295 children[i] = nullptr;
2296 delete currentChildBeingDeleted;
2297 }
2298 children.clear();
2299 currentChildBeingDeleted = nullptr;
2300 isDeletingChildren = false;
2301}
2302
2303void QObjectPrivate::setParent_helper(QObject *o)
2304{
2305 Q_Q(QObject);
2306 Q_ASSERT_X(q != o, Q_FUNC_INFO, "Cannot parent a QObject to itself");
2307#ifdef QT_DEBUG
2308 const auto checkForParentChildLoops = qScopeGuard([&](){
2309 int depth = 0;
2310 auto p = parent;
2311 while (p) {
2312 if (++depth == CheckForParentChildLoopsWarnDepth) {
2313 qWarning("QObject %p (class: '%s', object name: '%s') may have a loop in its parent-child chain; "
2314 "this is undefined behavior",
2315 q, q->metaObject()->className(), qPrintable(q->objectName()));
2316 }
2317 p = p->parent();
2318 }
2319 });
2320#endif
2321
2322 if (o == parent)
2323 return;
2324
2325 if (parent) {
2326 QObjectPrivate *parentD = parent->d_func();
2327 if (parentD->isDeletingChildren && wasDeleted
2328 && parentD->currentChildBeingDeleted == q) {
2329 // don't do anything since QObjectPrivate::deleteChildren() already
2330 // cleared our entry in parentD->children.
2331 } else {
2332 const qsizetype index = parentD->children.indexOf(q);
2333 if (index < 0) {
2334 // we're probably recursing into setParent() from a ChildRemoved event, don't do anything
2335 } else if (parentD->isDeletingChildren) {
2336 parentD->children[index] = nullptr;
2337 } else {
2338 parentD->children.removeAt(index);
2339 if (sendChildEvents && parentD->receiveChildEvents) {
2340 QChildEvent e(QEvent::ChildRemoved, q);
2341 QCoreApplication::sendEvent(parent, &e);
2342 }
2343 }
2344 }
2345 }
2346
2347 if (receiveParentEvents) {
2348 Q_ASSERT(!isWidget); // Handled in QWidget
2349 QEvent e(QEvent::ParentAboutToChange);
2350 QCoreApplication::sendEvent(q, &e);
2351 }
2352
2353 parent = o;
2354
2355 if (parent) {
2356 // object hierarchies are constrained to a single thread
2357 if (threadData.loadRelaxed() != parent->d_func()->threadData.loadRelaxed()) {
2358 qWarning("QObject::setParent: Cannot set parent, new parent is in a different thread");
2359 parent = nullptr;
2360 return;
2361 }
2362 parent->d_func()->children.append(q);
2363 if (sendChildEvents && parent->d_func()->receiveChildEvents) {
2364 if (!isWidget) {
2365 QChildEvent e(QEvent::ChildAdded, q);
2366 QCoreApplication::sendEvent(parent, &e);
2367 }
2368 }
2369 }
2370
2371 if (receiveParentEvents) {
2372 Q_ASSERT(!isWidget); // Handled in QWidget
2373 QEvent e(QEvent::ParentChange);
2374 QCoreApplication::sendEvent(q, &e);
2375 }
2376}
2377
2378/*!
2379 \fn void QObject::installEventFilter(QObject *filterObj)
2380
2381 Installs an event filter \a filterObj on this object. For example:
2382 \snippet code/src_corelib_kernel_qobject.cpp 14
2383
2384 An event filter is an object that receives all events that are
2385 sent to this object. The filter can either stop the event or
2386 forward it to this object. The event filter \a filterObj receives
2387 events via its eventFilter() function. The eventFilter() function
2388 must return true if the event should be filtered, (i.e. stopped);
2389 otherwise it must return false.
2390
2391 If multiple event filters are installed on a single object, the
2392 filter that was installed last is activated first.
2393
2394 If \a filterObj has already been installed for this object,
2395 this function moves it so it acts as if it was installed last.
2396
2397 Here's a \c KeyPressEater class that eats the key presses of its
2398 monitored objects:
2399
2400 \snippet code/src_corelib_kernel_qobject.cpp 15
2401
2402 And here's how to install it on two widgets:
2403
2404 \snippet code/src_corelib_kernel_qobject.cpp 16
2405
2406 The QShortcut class, for example, uses this technique to intercept
2407 shortcut key presses.
2408
2409 \warning If you delete the receiver object in your eventFilter()
2410 function, be sure to return true. If you return false, Qt sends
2411 the event to the deleted object and the program will crash.
2412
2413 Note that the filtering object must be in the same thread as this
2414 object. If \a filterObj is in a different thread, this function does
2415 nothing. If either \a filterObj or this object are moved to a different
2416 thread after calling this function, the event filter will not be
2417 called until both objects have the same thread affinity again (it
2418 is \e not removed).
2419
2420 \sa removeEventFilter(), eventFilter(), event()
2421*/
2422
2423void QObject::installEventFilter(QObject *obj)
2424{
2425 Q_D(QObject);
2426 if (!obj)
2427 return;
2428 if (d->threadData.loadRelaxed() != obj->d_func()->threadData.loadRelaxed()) {
2429 qWarning("QObject::installEventFilter(): Cannot filter events for objects in a different thread.");
2430 return;
2431 }
2432
2433 d->ensureExtraData();
2434
2435 // clean up unused items in the list along the way:
2436 auto isNullOrEquals = [](auto obj) { return [obj](const auto &p) { return !p || p == obj; }; };
2437 d->extraData->eventFilters.removeIf(isNullOrEquals(obj));
2438 d->extraData->eventFilters.prepend(obj);
2439}
2440
2441/*!
2442 Removes an event filter object \a obj from this object. The
2443 request is ignored if such an event filter has not been installed.
2444
2445 All event filters for this object are automatically removed when
2446 this object is destroyed.
2447
2448 It is always safe to remove an event filter, even during event
2449 filter activation (i.e. from the eventFilter() function).
2450
2451 \sa installEventFilter(), eventFilter(), event()
2452*/
2453
2454void QObject::removeEventFilter(QObject *obj)
2455{
2456 Q_D(QObject);
2457 if (d->extraData) {
2458 for (auto &filter : d->extraData->eventFilters) {
2459 if (filter == obj) {
2460 filter = nullptr;
2461 break;
2462 }
2463 }
2464 }
2465}
2466
2467/*!
2468 \fn void QObject::destroyed(QObject *obj)
2469
2470 This signal is emitted immediately before the object \a obj is
2471 destroyed, after any instances of QPointer have been notified,
2472 and cannot be blocked.
2473
2474 All the objects's children are destroyed immediately after this
2475 signal is emitted.
2476
2477 \sa deleteLater(), QPointer
2478*/
2479
2480/*!
2481 \threadsafe
2482
2483 Schedules this object for deletion.
2484
2485 The object will be deleted when control returns to the event
2486 loop. If the event loop is not running when this function is
2487 called (e.g. deleteLater() is called on an object before
2488 QCoreApplication::exec()), the object will be deleted once the
2489 event loop is started. If deleteLater() is called after the main event loop
2490 has stopped, the object will not be deleted.
2491 If deleteLater() is called on an object that lives in a
2492 thread with no running event loop, the object will be destroyed when the
2493 thread finishes.
2494
2495 A common pattern when using a worker \c QObject in a \c QThread
2496 is to connect the thread's \c finished() signal to the worker's
2497 \c deleteLater() slot to ensure it is safely deleted:
2498
2499 \code
2500 connect(thread, &QThread::finished, worker, &QObject::deleteLater);
2501 \endcode
2502
2503 Note that entering and leaving a new event loop (e.g., by opening a modal
2504 dialog) will \e not perform the deferred deletion; for the object to be
2505 deleted, the control must return to the event loop from which deleteLater()
2506 was called. This does not apply to objects deleted while a previous, nested
2507 event loop was still running: the Qt event loop will delete those objects
2508 as soon as the new nested event loop starts.
2509
2510 In situations where Qt is not driving the event dispatcher via e.g.
2511 QCoreApplication::exec() or QEventLoop::exec(), deferred deletes
2512 will not be processed automatically. To ensure deferred deletion in
2513 this scenario, the following workaround can be used:
2514
2515 \code
2516 const auto *eventDispatcher = QThread::currentThread()->eventDispatcher();
2517 QObject::connect(eventDispatcher, &QAbstractEventDispatcher::aboutToBlock,
2518 QThread::currentThread(), []{
2519 if (QThread::currentThread()->loopLevel() == 0)
2520 QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
2521 }
2522 );
2523 \endcode
2524
2525 \sa destroyed(), QPointer
2526*/
2527void QObject::deleteLater()
2528{
2529#ifdef QT_DEBUG
2530 if (qApp == this)
2531 qWarning("You are deferring the delete of QCoreApplication, this may not work as expected.");
2532#endif
2533
2534
2535 // De-bounce QDeferredDeleteEvents. Use the post event list mutex
2536 // to guard access to deleteLaterCalled, so we don't need a separate
2537 // mutex in QObjectData.
2538 auto eventListLocker = QCoreApplicationPrivate::lockThreadPostEventList(this);
2539 if (!eventListLocker.threadData)
2540 return;
2541
2542 // FIXME: The deleteLaterCalled flag is part of a bit field,
2543 // so we likely have data races here, even with the mutex above,
2544 // as long as we're not guarding every access to the bit field.
2545
2546 Q_D(QObject);
2547 if (d->deleteLaterCalled)
2548 return;
2549
2550 d->deleteLaterCalled = true;
2551
2552 int loopLevel = 0;
2553 int scopeLevel = 0;
2554
2555 auto *objectThreadData = eventListLocker.threadData;
2556 if (objectThreadData == QThreadData::current()) {
2557 // Remember the current running eventloop for deleteLater
2558 // calls in the object's own thread.
2559
2560 // Events sent by non-Qt event handlers (such as glib) may not
2561 // have the scopeLevel set correctly. The scope level makes sure that
2562 // code like this:
2563 // foo->deleteLater();
2564 // qApp->processEvents(); // without passing QEvent::DeferredDelete
2565 // will not cause "foo" to be deleted before returning to the event loop.
2566
2567 loopLevel = objectThreadData->loopLevel;
2568 scopeLevel = objectThreadData->scopeLevel;
2569
2570 // If the scope level is 0 while loopLevel != 0, we are called from a
2571 // non-conformant code path, and our best guess is that the scope level
2572 // should be 1. (Loop level 0 is special: it means that no event loops
2573 // are running.)
2574 if (scopeLevel == 0 && loopLevel != 0)
2575 scopeLevel = 1;
2576 }
2577
2578 eventListLocker.unlock();
2579 QCoreApplication::postEvent(this,
2580 new QDeferredDeleteEvent(loopLevel, scopeLevel));
2581}
2582
2583/*!
2584 \internal
2585
2586 Destroys \a object in the thread it belongs to, via deleteLater(), so that its
2587 vtable and members are not touched from the wrong thread. Falls back to deleting
2588 it right away when that thread cannot run the deferred delete: it is the current
2589 thread, or it has no event dispatcher (never started, or torn down at application
2590 exit). This is meant for objects deleted from a thread that is usually not their
2591 own, e.g. a worker handed to a thread pool.
2592
2593 The thread and the dispatcher are read from the object's QThreadData, which stays
2594 alive as long as the object does, rather than from QThread, which the owning thread
2595 may be destroying concurrently.
2596*/
2597void QObjectPrivate::deleteInOwnThread(QObject *object)
2598{
2599 QThreadData *objectData = QObjectPrivate::get(object)->threadData.loadRelaxed();
2600 if (objectData->hasEventDispatcher()
2601 && objectData->threadId.loadRelaxed() != QThread::currentThreadId()) {
2602 object->deleteLater();
2603 } else {
2604 delete object;
2605 }
2606}
2607
2608/*!
2609 \fn QString QObject::tr(const char *sourceText, const char *disambiguation, int n)
2610 \reentrant
2611
2612 Returns a translated version of \a sourceText, optionally based on a
2613 \a disambiguation string and value of \a n for strings containing plurals;
2614 otherwise returns QString::fromUtf8(\a sourceText) if no appropriate
2615 translated string is available.
2616
2617 Example:
2618 \snippet ../widgets/itemviews/spreadsheet/spreadsheet.cpp implicit tr context
2619 \dots
2620
2621 If the same \a sourceText is used in different roles within the
2622 same context, an additional identifying string may be passed in
2623 \a disambiguation (\nullptr by default).
2624
2625 Example:
2626
2627 \snippet code/src_corelib_kernel_qobject.cpp 17
2628 \dots
2629
2630 See \l{Writing Source Code for Translation} for a detailed description of
2631 Qt's translation mechanisms in general, and the
2632 \l{Writing Source Code for Translation#Disambiguate Identical Text}
2633 {Disambiguate Identical Text} section for information on disambiguation.
2634
2635 \warning This method is reentrant only if all translators are
2636 installed \e before calling this method. Installing or removing
2637 translators while performing translations is not supported. Doing
2638 so will probably result in crashes or other undesirable behavior.
2639
2640 \sa QCoreApplication::translate(), {Internationalization with Qt}
2641*/
2642
2643/*****************************************************************************
2644 Signals and slots
2645 *****************************************************************************/
2646
2647namespace {
2648// This class provides (per-thread) storage for qFlagLocation()
2649class FlaggedDebugSignatures
2650{
2651 uint idx = 0;
2652 std::array<const char *, 2> locations = {}; // one for the SIGNAL, one for the SLOT
2653
2654public:
2655 void store(const char* method) noexcept
2656 { locations[idx++ % locations.size()] = method; }
2657
2658 bool contains(const char *method) const noexcept
2659 { return std::find(locations.begin(), locations.end(), method) != locations.end(); }
2660};
2661
2662Q_CONSTINIT static thread_local FlaggedDebugSignatures flaggedSignatures = {};
2663} // unnamed namespace
2664
2665const char *qFlagLocation(const char *method)
2666{
2667 flaggedSignatures.store(method);
2668 return method;
2669}
2670
2671static int extract_code(const char *member)
2672{
2673 // extract code, ensure QMETHOD_CODE <= code <= QSIGNAL_CODE
2674 return (((int)(*member) - '0') & 0x3);
2675}
2676
2677static const char *extract_location(const char *member)
2678{
2679 if (flaggedSignatures.contains(member)) {
2680 // signature includes location information after the first null-terminator
2681 const char *location = member + qstrlen(member) + 1;
2682 if (*location != '\0')
2683 return location;
2684 }
2685 return nullptr;
2686}
2687
2688static bool check_signal_macro(const QObject *sender, const char *signal,
2689 const char *func, const char *op)
2690{
2691 int sigcode = extract_code(signal);
2692 if (sigcode != QSIGNAL_CODE) {
2693 if (sigcode == QSLOT_CODE)
2694 qCWarning(lcConnect, "QObject::%s: Attempt to %s non-signal %s::%s", func, op,
2695 sender->metaObject()->className(), signal + 1);
2696 else
2697 qCWarning(lcConnect, "QObject::%s: Use the SIGNAL macro to %s %s::%s", func, op,
2698 sender->metaObject()->className(), signal);
2699 return false;
2700 }
2701 return true;
2702}
2703
2704static bool check_method_code(int code, const QObject *object, const char *method, const char *func)
2705{
2706 if (code != QSLOT_CODE && code != QSIGNAL_CODE) {
2707 qCWarning(lcConnect,
2708 "QObject::%s: Use the SLOT or SIGNAL macro to "
2709 "%s %s::%s",
2710 func, func, object->metaObject()->className(), method);
2711 return false;
2712 }
2713 return true;
2714}
2715
2716#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
2717static void check_and_warn_non_slot(const char *func, const char *method, int membcode,
2718 const QMetaObject *rmeta, const QMetaMethod &rmethod)
2719{
2720 if (membcode == QSLOT_CODE && rmethod.methodType() != QMetaMethod::Slot) {
2721 // In Qt7 QMetaObject::indexOfSlot{,relative} will return -1 if `method`
2722 // isn't a slot.
2723 qCWarning(lcConnect,
2724 "QObject::%s: the SLOT() macro is used with a non-slot function: %s::%s. "
2725 "This currently works due to backwards-compatibility reasons. In Qt7 the "
2726 "SLOT() macro will work only for methods marked as slots.",
2727 func, rmeta->className(), method);
2728 }
2729}
2730#endif // QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
2731
2733static void err_method_notfound(const QObject *object,
2734 const char *method, const char *func)
2735{
2736 const char *type = "method";
2737 switch (extract_code(method)) {
2738 case QSLOT_CODE: type = "slot"; break;
2739 case QSIGNAL_CODE: type = "signal"; break;
2740 }
2741 const char *loc = extract_location(method);
2742 const char *err;
2743 if (strchr(method, ')') == nullptr) // common typing mistake
2744 err = "Parentheses expected,";
2745 else
2746 err = "No such";
2747 qCWarning(lcConnect, "QObject::%s: %s %s %s::%s%s%s", func, err, type,
2748 object->metaObject()->className(), method + 1, loc ? " in " : "", loc ? loc : "");
2749}
2750
2751enum class ConnectionEnd : bool { Sender, Receiver };
2753static void err_info_about_object(const char *func, const QObject *o, ConnectionEnd end)
2754{
2755 if (!o)
2756 return;
2757 const QString name = o->objectName();
2758 if (name.isEmpty())
2759 return;
2760 const bool sender = end == ConnectionEnd::Sender;
2761 qCWarning(lcConnect, "QObject::%s: (%s name:%*s'%ls')",
2762 func,
2763 sender ? "sender" : "receiver",
2764 sender ? 3 : 1, // ← length of generated whitespace
2765 "",
2766 qUtf16Printable(name));
2767}
2768
2770static void err_info_about_objects(const char *func, const QObject *sender, const QObject *receiver)
2771{
2774}
2775
2777static void connectWarning(const QObject *sender,
2778 const QMetaObject *senderMetaObject,
2779 const QObject *receiver,
2780 const char *message)
2781{
2782 const char *senderString = sender ? sender->metaObject()->className()
2783 : senderMetaObject ? senderMetaObject->className()
2784 : "Unknown";
2785 const char *receiverString = receiver ? receiver->metaObject()->className()
2786 : "Unknown";
2787 qCWarning(lcConnect, "QObject::connect(%s, %s): %s", senderString, receiverString, message);
2788}
2789
2790/*!
2791 Returns a pointer to the object that sent the signal, if called in
2792 a slot activated by a signal; otherwise it returns \nullptr. The pointer
2793 is valid only during the execution of the slot that calls this
2794 function from this object's thread context.
2795
2796 The pointer returned by this function becomes invalid if the
2797 sender is destroyed, or if the slot is disconnected from the
2798 sender's signal.
2799
2800 \warning This function violates the object-oriented principle of
2801 modularity. However, getting access to the sender might be useful
2802 when many signals are connected to a single slot.
2803
2804 \warning As mentioned above, the return value of this function is
2805 not valid when the slot is called via a Qt::DirectConnection from
2806 a thread different from this object's thread. Do not use this
2807 function in this type of scenario.
2808
2809 \sa senderSignalIndex()
2810*/
2811
2812QObject *QObject::sender() const
2813{
2814 Q_D(const QObject);
2815
2816 QMutexLocker locker(signalSlotLock(this));
2817 QObjectPrivate::ConnectionData *cd = d->connections.loadRelaxed();
2818 if (!cd || !cd->currentSender)
2819 return nullptr;
2820
2821 for (QObjectPrivate::Connection *c = cd->senders; c; c = c->next) {
2822 if (c->sender == cd->currentSender->sender)
2823 return cd->currentSender->sender;
2824 }
2825
2826 return nullptr;
2827}
2828
2829/*!
2830 \since 4.8
2831
2832 Returns the meta-method index of the signal that called the currently
2833 executing slot, which is a member of the class returned by sender().
2834 If called outside of a slot activated by a signal, -1 is returned.
2835
2836 For signals with default parameters, this function will always return
2837 the index with all parameters, regardless of which was used with
2838 connect(). For example, the signal \c {destroyed(QObject *obj = \nullptr)}
2839 will have two different indexes (with and without the parameter), but
2840 this function will always return the index with a parameter. This does
2841 not apply when overloading signals with different parameters.
2842
2843 \warning This function violates the object-oriented principle of
2844 modularity. However, getting access to the signal index might be useful
2845 when many signals are connected to a single slot.
2846
2847 \warning The return value of this function is not valid when the slot
2848 is called via a Qt::DirectConnection from a thread different from this
2849 object's thread. Do not use this function in this type of scenario.
2850
2851 \sa sender(), QMetaObject::indexOfSignal(), QMetaObject::method()
2852*/
2853
2854int QObject::senderSignalIndex() const
2855{
2856 Q_D(const QObject);
2857
2858 QMutexLocker locker(signalSlotLock(this));
2859 QObjectPrivate::ConnectionData *cd = d->connections.loadRelaxed();
2860 if (!cd || !cd->currentSender)
2861 return -1;
2862
2863 for (QObjectPrivate::Connection *c = cd->senders; c; c = c->next) {
2864 if (c->sender == cd->currentSender->sender) {
2865 // Convert from signal range to method range
2866 return QMetaObjectPrivate::signal(c->sender->metaObject(), cd->currentSender->signal).methodIndex();
2867 }
2868 }
2869
2870 return -1;
2871}
2872
2873/*!
2874 Returns the number of receivers connected to the \a signal.
2875
2876 Since both slots and signals can be used as receivers for signals,
2877 and the same connections can be made many times, the number of
2878 receivers is the same as the number of connections made from this
2879 signal.
2880
2881 When calling this function, you can use the \c SIGNAL() macro to
2882 pass a specific signal:
2883
2884 \snippet code/src_corelib_kernel_qobject.cpp 21
2885
2886 As the code snippet above illustrates, you can use this function to avoid
2887 expensive operations or emitting a signal that nobody listens to.
2888
2889 \warning In a multithreaded application, consecutive calls to this
2890 function are not guaranteed to yield the same results.
2891
2892 \warning This function violates the object-oriented principle of
2893 modularity. In particular, this function must not be called from an
2894 override of connectNotify() or disconnectNotify(), as those might get
2895 called from any thread.
2896
2897 \sa isSignalConnected()
2898*/
2899
2900int QObject::receivers(const char *signal) const
2901{
2902 Q_D(const QObject);
2903 int receivers = 0;
2904 if (signal) {
2905 QByteArray signal_name = QMetaObject::normalizedSignature(signal);
2906 signal = signal_name;
2907#ifndef QT_NO_DEBUG
2908 if (!check_signal_macro(this, signal, "receivers", "bind"))
2909 return 0;
2910#endif
2911 signal++; // skip code
2912 int signal_index = d->signalIndex(signal);
2913 if (signal_index < 0) {
2914#ifndef QT_NO_DEBUG
2915 err_method_notfound(this, signal - 1, "receivers");
2916#endif
2917 return 0;
2918 }
2919
2920 if (!d->isSignalConnected(signal_index))
2921 return receivers;
2922
2923 if (!d->isDeletingChildren && d->declarativeData && QAbstractDeclarativeData::receivers) {
2924 receivers += QAbstractDeclarativeData::receivers(d->declarativeData, this,
2925 signal_index);
2926 }
2927
2928 QMutexLocker locker(signalSlotLock(this));
2929 QObjectPrivate::ConnectionData *cd = d->connections.loadRelaxed();
2930 if (cd && signal_index < cd->signalVectorCount()) {
2931 const QObjectPrivate::Connection *c = cd->signalVector.loadRelaxed()->at(signal_index).first.loadRelaxed();
2932 while (c) {
2933 receivers += c->receiver.loadRelaxed() ? 1 : 0;
2934 c = c->nextConnectionList.loadRelaxed();
2935 }
2936 }
2937 }
2938 return receivers;
2939}
2940
2941/*!
2942 \since 5.0
2943 Returns \c true if the \a signal is connected to at least one receiver,
2944 otherwise returns \c false.
2945
2946 \a signal must be a signal member of this object, otherwise the behaviour
2947 is undefined.
2948
2949 \snippet code/src_corelib_kernel_qobject.cpp 49
2950
2951 As the code snippet above illustrates, you can use this function to avoid
2952 expensive operations or emitting a signal that nobody listens to.
2953
2954 \warning In a multithreaded application, consecutive calls to this
2955 function are not guaranteed to yield the same results.
2956
2957 \warning This function violates the object-oriented principle of
2958 modularity. In particular, this function must not be called from an
2959 override of connectNotify() or disconnectNotify(), as those might get
2960 called from any thread.
2961
2962 \sa receivers()
2963*/
2964bool QObject::isSignalConnected(const QMetaMethod &signal) const
2965{
2966 Q_D(const QObject);
2967 if (!signal.mobj)
2968 return false;
2969
2970 Q_ASSERT_X(signal.mobj->cast(this) && signal.methodType() == QMetaMethod::Signal,
2971 "QObject::isSignalConnected" , "the parameter must be a signal member of the object");
2972 uint signalIndex = signal.relativeMethodIndex();
2973
2974 if (signal.data.flags() & MethodCloned)
2975 signalIndex = QMetaObjectPrivate::originalClone(signal.mobj, signalIndex);
2976
2977 signalIndex += QMetaObjectPrivate::signalOffset(signal.mobj);
2978
2979 QMutexLocker locker(signalSlotLock(this));
2980 return d->isSignalConnected(signalIndex, true);
2981}
2982
2983/*!
2984 \internal
2985
2986 This helper function calculates signal and method index for the given
2987 member in the specified class.
2988
2989 \list
2990 \li If member.mobj is \nullptr then both signalIndex and methodIndex are set to -1.
2991
2992 \li If specified member is not a member of obj instance class (or one of
2993 its parent classes) then both signalIndex and methodIndex are set to -1.
2994 \endlist
2995
2996 This function is used by QObject::connect and QObject::disconnect which
2997 are working with QMetaMethod.
2998
2999 \a signalIndex is set to the signal index of member. If the member
3000 specified is not signal this variable is set to -1.
3001
3002 \a methodIndex is set to the method index of the member. If the
3003 member is not a method of the object specified by the \a obj argument this
3004 variable is set to -1.
3005*/
3006void QMetaObjectPrivate::memberIndexes(const QObject *obj,
3007 const QMetaMethod &member,
3008 int *signalIndex, int *methodIndex)
3009{
3010 *signalIndex = -1;
3011 *methodIndex = -1;
3012 if (!obj || !member.mobj)
3013 return;
3014 const QMetaObject *m = obj->metaObject();
3015 // Check that member is member of obj class
3016 while (m != nullptr && m != member.mobj)
3017 m = m->d.superdata;
3018 if (!m)
3019 return;
3020 *signalIndex = *methodIndex = member.relativeMethodIndex();
3021
3022 int signalOffset;
3023 int methodOffset;
3024 computeOffsets(m, &signalOffset, &methodOffset);
3025
3026 *methodIndex += methodOffset;
3027 if (member.methodType() == QMetaMethod::Signal) {
3028 *signalIndex = originalClone(m, *signalIndex);
3029 *signalIndex += signalOffset;
3030 } else {
3031 *signalIndex = -1;
3032 }
3033}
3034
3035#ifndef QT_NO_DEBUG
3036static inline void check_and_warn_compat(const QMetaObject *sender, const QMetaMethod &signal,
3037 const QMetaObject *receiver, const QMetaMethod &method)
3038{
3039 if (signal.attributes() & QMetaMethod::Compatibility) {
3040 if (!(method.attributes() & QMetaMethod::Compatibility))
3041 qCWarning(lcConnect, "QObject::connect: Connecting from COMPAT signal (%s::%s)",
3042 sender->className(), signal.methodSignature().constData());
3043 } else if ((method.attributes() & QMetaMethod::Compatibility)
3044 && method.methodType() == QMetaMethod::Signal) {
3045 qCWarning(lcConnect, "QObject::connect: Connecting from %s::%s to COMPAT slot (%s::%s)",
3046 sender->className(), signal.methodSignature().constData(), receiver->className(),
3047 method.methodSignature().constData());
3048 }
3049}
3050#endif
3051
3052/*!
3053 \threadsafe
3054
3055 Creates a connection of the given \a type from the \a signal in
3056 the \a sender object to the \a method in the \a receiver object.
3057 Returns a handle to the connection that can be used to disconnect
3058 it later.
3059
3060 You must use the \c SIGNAL() and \c SLOT() macros when specifying
3061 the \a signal and the \a method, for example:
3062
3063 \snippet code/src_corelib_kernel_qobject.cpp 22
3064
3065 This example ensures that the label always displays the current
3066 scroll bar value. Note that the signal and slots parameters must not
3067 contain any variable names, only the type. E.g. the following would
3068 not work and return false:
3069
3070 \snippet code/src_corelib_kernel_qobject.cpp 23
3071
3072 A signal can also be connected to another signal:
3073
3074 \snippet code/src_corelib_kernel_qobject.cpp 24
3075
3076 In this example, the \c MyWidget constructor relays a signal from
3077 a private member variable, and makes it available under a name
3078 that relates to \c MyWidget.
3079
3080 A signal can be connected to many slots and signals. Many signals
3081 can be connected to one slot.
3082
3083 If a signal is connected to several slots, the slots are activated
3084 in the same order in which the connections were made, when the
3085 signal is emitted.
3086
3087 The function returns a QMetaObject::Connection that represents
3088 a handle to a connection if it successfully
3089 connects the signal to the slot. The connection handle will be invalid
3090 if it cannot create the connection, for example, if QObject is unable
3091 to verify the existence of either \a signal or \a method, or if their
3092 signatures aren't compatible.
3093 You can check if the handle is valid by casting it to a bool.
3094
3095 By default, a signal is emitted for every connection you make;
3096 two signals are emitted for duplicate connections. You can break
3097 all of these connections with a single disconnect() call.
3098 If you pass the Qt::UniqueConnection \a type, the connection will only
3099 be made if it is not a duplicate. If there is already a duplicate
3100 (exact same signal to the exact same slot on the same objects),
3101 the connection will fail and connect will return an invalid QMetaObject::Connection.
3102
3103 \note Qt::UniqueConnections do not work for lambdas, non-member functions
3104 and functors; they only apply to connecting to member functions.
3105
3106 The optional \a type parameter describes the type of connection
3107 to establish. In particular, it determines whether a particular
3108 signal is delivered to a slot immediately or queued for delivery
3109 at a later time. If the signal is queued, the parameters must be
3110 of types that are known to Qt's meta-object system, because Qt
3111 needs to copy the arguments to store them in an event behind the
3112 scenes. If you try to use a queued connection and get the error
3113 message
3114
3115 \snippet code/src_corelib_kernel_qobject.cpp 25
3116
3117 call qRegisterMetaType() to register the data type before you
3118 establish the connection.
3119
3120 \sa disconnect(), sender(), qRegisterMetaType(), Q_DECLARE_METATYPE(),
3121 {Differences between String-Based and Functor-Based Connections}
3122*/
3123QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal,
3124 const QObject *receiver, const char *method,
3125 Qt::ConnectionType type)
3126{
3127 if (sender == nullptr || receiver == nullptr || signal == nullptr || method == nullptr) {
3128 qCWarning(lcConnect, "QObject::connect: Cannot connect %s::%s to %s::%s",
3129 sender ? sender->metaObject()->className() : "(nullptr)",
3130 (signal && *signal) ? signal + 1 : "(nullptr)",
3131 receiver ? receiver->metaObject()->className() : "(nullptr)",
3132 (method && *method) ? method + 1 : "(nullptr)");
3133 return QMetaObject::Connection(nullptr);
3134 }
3135
3136 if (!check_signal_macro(sender, signal, "connect", "bind"))
3137 return QMetaObject::Connection(nullptr);
3138
3139 int membcode = extract_code(method);
3140 if (!check_method_code(membcode, receiver, method, "connect"))
3141 return QMetaObject::Connection(nullptr);
3142
3143 QByteArray pinnedSignal;
3144 const QMetaObject *smeta = sender->metaObject();
3145 const char *signal_arg = signal;
3146 ++signal; // skip code
3147 QByteArrayView signalView{signal}; // after skipping code
3148 QArgumentTypeArray signalTypes;
3149 Q_ASSERT(QMetaObjectPrivate::get(smeta)->revision >= 7);
3150 QByteArrayView signalName = QMetaObjectPrivate::decodeMethodSignature(signalView, signalTypes);
3151 int signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signalName, signalTypes);
3152 if (signal_index < 0) {
3153 // check for normalized signatures
3154 pinnedSignal = QMetaObjectPrivate::normalizedSignature(signalView);
3155 signalView = pinnedSignal;
3156
3157 signalTypes.clear();
3158 signalName = QMetaObjectPrivate::decodeMethodSignature(signalView, signalTypes);
3159 smeta = sender->metaObject();
3160 signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signalName, signalTypes);
3161 }
3162 if (signal_index < 0) {
3163 err_method_notfound(sender, signal_arg, "connect");
3164 err_info_about_objects("connect", sender, receiver);
3165 return QMetaObject::Connection(nullptr);
3166 }
3167 signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
3168 signal_index += QMetaObjectPrivate::signalOffset(smeta);
3169
3170 QByteArray pinnedMethod;
3171 const char *method_arg = method;
3172 ++method; // skip code
3173 QByteArrayView methodView{method}; // after skipping code
3174
3175 QArgumentTypeArray methodTypes;
3176 QByteArrayView methodName = QMetaObjectPrivate::decodeMethodSignature(methodView, methodTypes);
3177 const QMetaObject *rmeta = receiver->metaObject();
3178 int method_index_relative = -1;
3179 Q_ASSERT(QMetaObjectPrivate::get(rmeta)->revision >= 7);
3180 switch (membcode) {
3181 case QSLOT_CODE:
3182 method_index_relative = QMetaObjectPrivate::indexOfSlotRelative(
3183 &rmeta, methodName, methodTypes);
3184 break;
3185 case QSIGNAL_CODE:
3186 method_index_relative = QMetaObjectPrivate::indexOfSignalRelative(
3187 &rmeta, methodName, methodTypes);
3188 break;
3189 }
3190
3191 if (method_index_relative < 0) {
3192 // check for normalized methods
3193 pinnedMethod = QMetaObjectPrivate::normalizedSignature(methodView);
3194 methodView = pinnedMethod;
3195
3196 methodTypes.clear();
3197 methodName = QMetaObjectPrivate::decodeMethodSignature(methodView, methodTypes);
3198 // rmeta may have been modified above
3199 rmeta = receiver->metaObject();
3200 switch (membcode) {
3201 case QSLOT_CODE:
3202 method_index_relative = QMetaObjectPrivate::indexOfSlotRelative(
3203 &rmeta, methodName, methodTypes);
3204 break;
3205 case QSIGNAL_CODE:
3206 method_index_relative = QMetaObjectPrivate::indexOfSignalRelative(
3207 &rmeta, methodName, methodTypes);
3208 break;
3209 }
3210 }
3211
3212 if (method_index_relative < 0) {
3213 err_method_notfound(receiver, method_arg, "connect");
3214 err_info_about_objects("connect", sender, receiver);
3215 return QMetaObject::Connection(nullptr);
3216 }
3217
3218 if (!QMetaObjectPrivate::checkConnectArgs(signalTypes, methodTypes)) {
3219 qCWarning(lcConnect,
3220 "QObject::connect: Incompatible sender/receiver arguments"
3221 "\n %s::%s --> %s::%s",
3222 sender->metaObject()->className(), signalView.constData(),
3223 receiver->metaObject()->className(), methodView.constData());
3224 return QMetaObject::Connection(nullptr);
3225 }
3226
3227 // ### Future work: attempt get the metatypes from the meta object first
3228 // because it's possible they're all registered.
3229 int *types = nullptr;
3230 if (type == Qt::QueuedConnection && !(types = queuedConnectionTypes(signalTypes))) {
3231 return QMetaObject::Connection(nullptr);
3232 }
3233
3234 QMetaMethod rmethod = rmeta->method(method_index_relative + rmeta->methodOffset());
3235#ifndef QT_NO_DEBUG
3236 QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
3237 check_and_warn_compat(smeta, smethod, rmeta, rmethod);
3238#endif
3239
3240#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
3241 check_and_warn_non_slot("connect", method, membcode, rmeta, rmethod);
3242#endif
3243
3244 QMetaObject::Connection handle = QMetaObject::Connection(QMetaObjectPrivate::connect(
3245 sender, signal_index, smeta, receiver, method_index_relative, rmeta ,type, types));
3246 return handle;
3247}
3248
3249/*!
3250 \since 4.8
3251
3252 Creates a connection of the given \a type from the \a signal in
3253 the \a sender object to the \a method in the \a receiver object.
3254 Returns a handle to the connection that can be used to disconnect
3255 it later.
3256
3257 The Connection handle will be invalid if it cannot create the
3258 connection, for example, the parameters were invalid.
3259 You can check if the QMetaObject::Connection is valid by casting it to a bool.
3260
3261 This function works in the same way as
3262 \c {connect(const QObject *sender, const char *signal,
3263 const QObject *receiver, const char *method,
3264 Qt::ConnectionType type)}
3265 but it uses QMetaMethod to specify signal and method.
3266
3267 \sa connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
3268 */
3269QMetaObject::Connection QObject::connect(const QObject *sender, const QMetaMethod &signal,
3270 const QObject *receiver, const QMetaMethod &method,
3271 Qt::ConnectionType type)
3272{
3273 if (sender == nullptr
3274 || receiver == nullptr
3275 || signal.methodType() != QMetaMethod::Signal
3276 || method.methodType() == QMetaMethod::Constructor) {
3277 qCWarning(lcConnect, "QObject::connect: Cannot connect %s::%s to %s::%s",
3278 sender ? sender->metaObject()->className() : "(nullptr)",
3279 signal.methodSignature().constData(),
3280 receiver ? receiver->metaObject()->className() : "(nullptr)",
3281 method.methodSignature().constData());
3282 return QMetaObject::Connection(nullptr);
3283 }
3284
3285 int signal_index;
3286 int method_index;
3287 {
3288 int dummy;
3289 QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
3290 QMetaObjectPrivate::memberIndexes(receiver, method, &dummy, &method_index);
3291 }
3292
3293 const QMetaObject *smeta = sender->metaObject();
3294 const QMetaObject *rmeta = receiver->metaObject();
3295 if (signal_index == -1) {
3296 qCWarning(lcConnect, "QObject::connect: Can't find signal %s on instance of class %s",
3297 signal.methodSignature().constData(), smeta->className());
3298 return QMetaObject::Connection(nullptr);
3299 }
3300 if (method_index == -1) {
3301 qCWarning(lcConnect, "QObject::connect: Can't find method %s on instance of class %s",
3302 method.methodSignature().constData(), rmeta->className());
3303 return QMetaObject::Connection(nullptr);
3304 }
3305
3306 if (!QMetaObject::checkConnectArgs(signal.methodSignature().constData(),
3307 method.methodSignature().constData())) {
3308 qCWarning(lcConnect,
3309 "QObject::connect: Incompatible sender/receiver arguments"
3310 "\n %s::%s --> %s::%s",
3311 smeta->className(), signal.methodSignature().constData(), rmeta->className(),
3312 method.methodSignature().constData());
3313 return QMetaObject::Connection(nullptr);
3314 }
3315
3316 int *types = nullptr;
3317 if ((type == Qt::QueuedConnection) && !(types = queuedConnectionTypes(signal)))
3318 return QMetaObject::Connection(nullptr);
3319
3320#ifndef QT_NO_DEBUG
3321 check_and_warn_compat(smeta, signal, rmeta, method);
3322#endif
3323 QMetaObject::Connection handle = QMetaObject::Connection(QMetaObjectPrivate::connect(
3324 sender, signal_index, signal.enclosingMetaObject(), receiver, method_index, nullptr, type, types));
3325 return handle;
3326}
3327
3328/*!
3329 \fn bool QObject::connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type) const
3330 \overload connect()
3331 \threadsafe
3332
3333 Connects \a signal from the \a sender object to this object's \a
3334 method.
3335
3336 Equivalent to connect(\a sender, \a signal, \c this, \a method, \a type).
3337
3338 Every connection you make emits a signal, so duplicate connections emit
3339 two signals. You can break a connection using disconnect().
3340
3341 \sa disconnect()
3342*/
3343
3344/*!
3345 \threadsafe
3346
3347 Disconnects \a signal in object \a sender from \a method in object
3348 \a receiver. Returns \c true if the connection is successfully broken;
3349 otherwise returns \c false.
3350
3351 A signal-slot connection is removed when either of the objects
3352 involved are destroyed.
3353
3354 disconnect() is typically used in three ways, as the following
3355 examples demonstrate.
3356 \list 1
3357 \li Disconnect everything connected to an object's signals:
3358
3359 \snippet code/src_corelib_kernel_qobject.cpp 26
3360
3361 equivalent to the non-static overloaded function
3362
3363 \snippet code/src_corelib_kernel_qobject.cpp 27
3364
3365 \li Disconnect everything connected to a specific signal:
3366
3367 \snippet code/src_corelib_kernel_qobject.cpp 28
3368
3369 equivalent to the non-static overloaded function
3370
3371 \snippet code/src_corelib_kernel_qobject.cpp 29
3372
3373 \li Disconnect a specific receiver:
3374
3375 \snippet code/src_corelib_kernel_qobject.cpp 30
3376
3377 equivalent to the non-static overloaded function
3378
3379 \snippet code/src_corelib_kernel_qobject.cpp 31
3380
3381 \endlist
3382
3383 \include includes/qobject.qdocinc disconnect-duplicates
3384 \include includes/qobject.qdocinc disconnect-mismatch
3385 \include includes/qobject.qdocinc disconnect-queued
3386
3387 \nullptr may be used as a wildcard, meaning "any signal", "any receiving
3388 object", or "any slot in the receiving object", respectively.
3389
3390 The \a sender may never be \nullptr. (You cannot disconnect signals
3391 from more than one object in a single call.)
3392
3393 If \a signal is \nullptr, it disconnects \a receiver and \a method from
3394 any signal. If not, only the specified signal is disconnected.
3395
3396 If \a receiver is \nullptr, it disconnects anything connected to \a
3397 signal. If not, slots in objects other than \a receiver are not
3398 disconnected.
3399
3400 If \a method is \nullptr, it disconnects anything that is connected to \a
3401 receiver. If not, only slots named \a method will be disconnected,
3402 and all other slots are left alone. The \a method must be \nullptr
3403 if \a receiver is left out, so you cannot disconnect a
3404 specifically-named slot on all objects.
3405
3406 \include includes/qobject.qdocinc disconnect-all
3407
3408 \sa connect()
3409*/
3410bool QObject::disconnect(const QObject *sender, const char *signal,
3411 const QObject *receiver, const char *method)
3412{
3413 if (sender == nullptr || (receiver == nullptr && method != nullptr)) {
3414 qCWarning(lcConnect, "QObject::disconnect: Unexpected nullptr parameter");
3415 return false;
3416 }
3417
3418 const char *signal_arg = signal;
3419 if (signal) {
3420 if (!check_signal_macro(sender, signal, "disconnect", "unbind"))
3421 return false;
3422 ++signal; // skip code
3423 }
3424
3425 const char *method_arg = method;
3426 int membcode = -1;
3427 if (method) {
3428 membcode = extract_code(method);
3429 if (!check_method_code(membcode, receiver, method, "disconnect"))
3430 return false;
3431 ++method; // skip code
3432 }
3433
3434 QByteArray pinnedSignal;
3435 const QMetaObject *smeta = sender->metaObject();
3436 Q_ASSERT(QMetaObjectPrivate::get(smeta)->revision >= 7);
3437 int signal_index = -1;
3438 QByteArrayView signalName;
3439 QArgumentTypeArray signalTypes;
3440 if (signal) {
3441 signalName = QMetaObjectPrivate::decodeMethodSignature(signal, signalTypes);
3442 signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signalName, signalTypes);
3443 if (signal_index == -1) {
3444 pinnedSignal = QMetaObject::normalizedSignature(signal);
3445 signal = pinnedSignal.constData();
3446 signalTypes.clear();
3447 signalName = QMetaObjectPrivate::decodeMethodSignature(signal, signalTypes);
3448 signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signalName,
3449 signalTypes);
3450 }
3451 if (signal_index == -1) {
3452 err_method_notfound(sender, signal_arg, "disconnect");
3453 err_info_about_objects("disconnect", sender, receiver);
3454 return false;
3455 }
3456 }
3457
3458 auto getMethodIndex = [](int code, const QMetaObject *mo, QByteArrayView name,
3459 const QArgumentTypeArray &types) {
3460 switch (code) {
3461 case QSLOT_CODE:
3462 return QMetaObjectPrivate::indexOfSlot(mo, name, types);
3463 case QSIGNAL_CODE:
3464 return QMetaObjectPrivate::indexOfSignal(mo, name, types);
3465 }
3466 return -1;
3467 };
3468
3469 QByteArray pinnedMethod;
3470 const QMetaObject *rmeta = receiver ? receiver->metaObject() : nullptr;
3471 Q_ASSERT(!rmeta || QMetaObjectPrivate::get(rmeta)->revision >= 7);
3472 int method_index = -1;
3473 QByteArrayView methodName;
3474 QArgumentTypeArray methodTypes;
3475 if (method) {
3476 methodName = QMetaObjectPrivate::decodeMethodSignature(method, methodTypes);
3477 method_index = getMethodIndex(membcode, rmeta, methodName, methodTypes);
3478 if (method_index == -1) {
3479 pinnedMethod = QMetaObject::normalizedSignature(method);
3480 method = pinnedMethod.constData();
3481 methodTypes.clear();
3482 methodName = QMetaObjectPrivate::decodeMethodSignature(method, methodTypes);
3483 method_index = getMethodIndex(membcode, rmeta, methodName, methodTypes);
3484 }
3485 if (method_index == -1) {
3486 err_method_notfound(receiver, method_arg, "disconnect");
3487 err_info_about_objects("disconnect", sender, receiver);
3488 return false;
3489 }
3490 }
3491
3492 /* We now iterate through all the sender's and receiver's meta
3493 * objects in order to also disconnect possibly shadowed signals
3494 * and slots with the same signature.
3495 */
3496 bool res = false;
3497 do {
3498 if (signal) {
3499 // Already computed the signal_index for `smeta` above
3500 if (smeta != sender->metaObject()) {
3501 signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signalName,
3502 signalTypes);
3503 }
3504 if (signal_index < 0)
3505 break;
3506 signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
3507 signal_index += QMetaObjectPrivate::signalOffset(smeta);
3508 }
3509
3510 if (!method) {
3511 res |= QMetaObjectPrivate::disconnect(sender, signal_index, smeta, receiver, -1, nullptr);
3512 } else {
3513 do {
3514 // Already computed the method_index for receiver->metaObject() above
3515 if (rmeta != receiver->metaObject())
3516 method_index = getMethodIndex(membcode, rmeta, methodName, methodTypes);
3517 if (method_index >= 0) {
3518#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
3519 check_and_warn_non_slot("disconnect", method, membcode, rmeta,
3520 rmeta->method(method_index));
3521#endif
3522 while (method_index < rmeta->methodOffset())
3523 rmeta = rmeta->superClass();
3524 }
3525 if (method_index < 0)
3526 break;
3527 res |= QMetaObjectPrivate::disconnect(sender, signal_index, smeta, receiver, method_index, nullptr);
3528 } while ((rmeta = rmeta->superClass()));
3529 }
3530 } while (signal && (smeta = smeta->superClass()));
3531
3532 if (res) {
3533 if (!signal)
3534 const_cast<QObject *>(sender)->disconnectNotify(QMetaMethod());
3535 }
3536 return res;
3537}
3538
3539/*!
3540 \since 4.8
3541
3542 Disconnects \a signal in object \a sender from \a method in object
3543 \a receiver. Returns \c true if the connection is successfully broken;
3544 otherwise returns \c false.
3545
3546 This function provides the same possibilities like
3547 \c {disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) }
3548 but uses QMetaMethod to represent the signal and the method to be disconnected.
3549
3550 Additionally this function returns false and no signals and slots disconnected
3551 if:
3552 \list 1
3553
3554 \li \a signal is not a member of sender class or one of its parent classes.
3555
3556 \li \a method is not a member of receiver class or one of its parent classes.
3557
3558 \li \a signal instance represents not a signal.
3559
3560 \endlist
3561
3562 \include includes/qobject.qdocinc disconnect-duplicates
3563 \include includes/qobject.qdocinc disconnect-mismatch
3564 \include includes/qobject.qdocinc disconnect-queued
3565
3566 QMetaMethod() may be used as wildcard in the meaning "any signal" or "any slot in receiving object".
3567 In the same way \nullptr can be used for \a receiver in the meaning "any receiving object".
3568 In this case method should also be QMetaMethod(). \a sender parameter should be never \nullptr.
3569
3570 \include includes/qobject.qdocinc disconnect-all
3571
3572 \sa disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)
3573 */
3574bool QObject::disconnect(const QObject *sender, const QMetaMethod &signal,
3575 const QObject *receiver, const QMetaMethod &method)
3576{
3577 if (sender == nullptr || (receiver == nullptr && method.mobj != nullptr)) {
3578 qCWarning(lcConnect, "QObject::disconnect: Unexpected nullptr parameter");
3579 return false;
3580 }
3581 if (signal.mobj) {
3582 if (signal.methodType() != QMetaMethod::Signal) {
3583 qCWarning(lcConnect, "QObject::%s: Attempt to %s non-signal %s::%s",
3584 "disconnect","unbind",
3585 sender->metaObject()->className(), signal.methodSignature().constData());
3586 return false;
3587 }
3588 }
3589 if (method.mobj) {
3590 if (method.methodType() == QMetaMethod::Constructor) {
3591 qCWarning(lcConnect, "QObject::disconnect: cannot use constructor as argument %s::%s",
3592 receiver->metaObject()->className(), method.methodSignature().constData());
3593 return false;
3594 }
3595 }
3596
3597 int signal_index;
3598 int method_index;
3599 {
3600 int dummy;
3601 QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
3602 QMetaObjectPrivate::memberIndexes(receiver, method, &dummy, &method_index);
3603 }
3604 // If we are here sender is not nullptr. If signal is not nullptr while signal_index
3605 // is -1 then this signal is not a member of sender.
3606 if (signal.mobj && signal_index == -1) {
3607 qCWarning(lcConnect, "QObject::disconnect: signal %s not found on class %s",
3608 signal.methodSignature().constData(), sender->metaObject()->className());
3609 return false;
3610 }
3611 // If this condition is true then method is not a member of receiver.
3612 if (receiver && method.mobj && method_index == -1) {
3613 qCWarning(lcConnect, "QObject::disconnect: method %s not found on class %s",
3614 method.methodSignature().constData(), receiver->metaObject()->className());
3615 return false;
3616 }
3617
3618 if (!QMetaObjectPrivate::disconnect(sender, signal_index, signal.mobj, receiver, method_index, nullptr))
3619 return false;
3620
3621 if (!signal.isValid()) {
3622 // The signal is a wildcard, meaning all signals were disconnected.
3623 // QMetaObjectPrivate::disconnect() doesn't call disconnectNotify()
3624 // per connection in this case. Call it once now, with an invalid
3625 // QMetaMethod as argument, as documented.
3626 const_cast<QObject *>(sender)->disconnectNotify(signal);
3627 }
3628 return true;
3629}
3630
3631/*!
3632 \threadsafe
3633
3634 \fn bool QObject::disconnect(const char *signal, const QObject *receiver, const char *method) const
3635 \overload disconnect()
3636
3637 Disconnects \a signal from \a method of \a receiver.
3638
3639 \include includes/qobject.qdocinc disconnect-duplicates
3640 \include includes/qobject.qdocinc disconnect-mismatch
3641 \include includes/qobject.qdocinc disconnect-queued
3642
3643 A signal-slot connection is removed when either of the objects
3644 involved are destroyed.
3645
3646 \include includes/qobject.qdocinc disconnect-all
3647*/
3648
3649/*!
3650 \fn bool QObject::disconnect(const QObject *receiver, const char *method) const
3651 \overload disconnect()
3652
3653 Disconnects all signals in this object from \a receiver's \a
3654 method.
3655
3656 \include includes/qobject.qdocinc disconnect-duplicates
3657 \include includes/qobject.qdocinc disconnect-mismatch
3658 \include includes/qobject.qdocinc disconnect-queued
3659
3660 A signal-slot connection is removed when either of the objects
3661 involved are destroyed.
3662*/
3663
3664
3665/*!
3666 \since 5.0
3667
3668 This virtual function is called when something has been connected
3669 to \a signal in this object.
3670
3671 If you want to compare \a signal with a specific signal, you can
3672 use QMetaMethod::fromSignal() as follows:
3673
3674 \snippet code/src_corelib_kernel_qobject.cpp 32
3675
3676 \warning This function violates the object-oriented principle of
3677 modularity. However, it might be useful when you need to perform
3678 an expensive operation only if something is connected to a signal.
3679
3680 \warning This function is called from the thread which performs the
3681 connection, which may be a different thread from the thread in which
3682 this object lives. This function may also be called with a QObject internal
3683 mutex locked. It is therefore not allowed to re-enter any QObject
3684 functions, including isSignalConnected(), from your reimplementation. If
3685 you lock a mutex in your reimplementation, make sure that you don't call
3686 QObject functions with that mutex held in other places or it will result in
3687 a deadlock.
3688
3689 \sa connect(), disconnectNotify()
3690*/
3691
3692void QObject::connectNotify(const QMetaMethod &signal)
3693{
3694 Q_UNUSED(signal);
3695}
3696
3697/*!
3698 \since 5.0
3699
3700 This virtual function is called when something has been
3701 disconnected from \a signal in this object.
3702
3703 See connectNotify() for an example of how to compare
3704 \a signal with a specific signal.
3705
3706 If all signals were disconnected from this object (e.g., the
3707 signal argument to disconnect() was \nullptr), disconnectNotify()
3708 is only called once, and the \a signal will be an invalid
3709 QMetaMethod (QMetaMethod::isValid() returns \c false).
3710
3711 When a receiver living in another thread is destroyed, this function is
3712 called later, from this object's own thread; if that thread has no running
3713 event loop, it is not called at all. In every other case it is called right
3714 away, from the thread that is disconnecting the signal.
3715
3716 \warning This function violates the object-oriented principle of
3717 modularity. However, it might be useful for optimizing access to
3718 expensive resources.
3719
3720 \warning This function is called from the thread which performs the
3721 disconnection, which may be a different thread from the thread in which
3722 this object lives. This function may also be called with a QObject internal
3723 mutex locked. It is therefore not allowed to re-enter any QObject
3724 functions, including isSignalConnected(), from your reimplementation. If
3725 you lock a mutex in your reimplementation, make sure that you don't call
3726 QObject functions with that mutex held in other places or it will result in
3727 a deadlock.
3728
3729 \sa disconnect(), connectNotify()
3730*/
3731
3732void QObject::disconnectNotify(const QMetaMethod &signal)
3733{
3734 Q_UNUSED(signal);
3735}
3736
3737/*
3738 \internal
3739 convert a signal index from the method range to the signal range
3740 */
3741static int methodIndexToSignalIndex(const QMetaObject **base, int signal_index)
3742{
3743 if (signal_index < 0)
3744 return signal_index;
3745 const QMetaObject *metaObject = *base;
3746 while (metaObject && metaObject->methodOffset() > signal_index)
3747 metaObject = metaObject->superClass();
3748
3749 if (metaObject) {
3750 int signalOffset, methodOffset;
3751 computeOffsets(metaObject, &signalOffset, &methodOffset);
3752 if (signal_index < metaObject->methodCount())
3753 signal_index = QMetaObjectPrivate::originalClone(metaObject, signal_index - methodOffset) + signalOffset;
3754 else
3755 signal_index = signal_index - methodOffset + signalOffset;
3756 *base = metaObject;
3757 }
3758 return signal_index;
3759}
3760
3761/*!
3762 \internal
3763 \a types is a 0-terminated vector of meta types for queued
3764 connections.
3765
3766 if \a signal_index is -1, then we effectively connect *all* signals
3767 from the sender to the receiver's slot
3768 */
3769QMetaObject::Connection QMetaObject::connect(const QObject *sender, int signal_index,
3770 const QObject *receiver, int method_index, int type,
3771 int *types)
3772{
3773 const QMetaObject *smeta = sender->metaObject();
3774 signal_index = methodIndexToSignalIndex(&smeta, signal_index);
3775 return Connection(QMetaObjectPrivate::connect(sender, signal_index, smeta,
3776 receiver, method_index,
3777 nullptr, //FIXME, we could speed this connection up by computing the relative index
3778 type, types));
3779}
3780
3781/*!
3782 \internal
3783 Same as the QMetaObject::connect, but \a signal_index must be the result of QObjectPrivate::signalIndex
3784
3785 method_index is relative to the rmeta metaobject, if rmeta is \nullptr, then it is absolute index
3786
3787 the QObjectPrivate::Connection* has a refcount of 2, so it must be passed to a QMetaObject::Connection
3788 */
3789QObjectPrivate::Connection *QMetaObjectPrivate::connect(const QObject *sender,
3790 int signal_index, const QMetaObject *smeta,
3791 const QObject *receiver, int method_index,
3792 const QMetaObject *rmeta, int type, int *types)
3793{
3794 QObject *s = const_cast<QObject *>(sender);
3795 QObject *r = const_cast<QObject *>(receiver);
3796
3797 int method_offset = rmeta ? rmeta->methodOffset() : 0;
3798 Q_ASSERT(!rmeta || QMetaObjectPrivate::get(rmeta)->revision >= 6);
3799 QObjectPrivate::StaticMetaCallFunction callFunction = rmeta ? rmeta->d.static_metacall : nullptr;
3800
3801 QOrderedMutexLocker locker(signalSlotLock(sender),
3802 signalSlotLock(receiver));
3803
3804 QObjectPrivate::ConnectionData *scd = QObjectPrivate::get(s)->connections.loadRelaxed();
3805 if (type & Qt::UniqueConnection && scd) {
3806 if (scd->signalVectorCount() > signal_index) {
3807 const QObjectPrivate::Connection *c2 = scd->signalVector.loadRelaxed()->at(signal_index).first.loadRelaxed();
3808
3809 int method_index_absolute = method_index + method_offset;
3810
3811 while (c2) {
3812 if (!c2->isSlotObject && c2->receiver.loadRelaxed() == receiver && c2->method() == method_index_absolute)
3813 return nullptr;
3814 c2 = c2->nextConnectionList.loadRelaxed();
3815 }
3816 }
3817 }
3818 type &= ~Qt::UniqueConnection;
3819
3820 const bool isSingleShot = type & Qt::SingleShotConnection;
3821 type &= ~Qt::SingleShotConnection;
3822
3823 Q_ASSERT(type >= 0);
3824 Q_ASSERT(type <= 3);
3825
3826 std::unique_ptr<QObjectPrivate::Connection> c{new QObjectPrivate::Connection};
3827 c->sender = s;
3828 c->signal_index = signal_index;
3829 c->receiver.storeRelaxed(r);
3830 QThreadData *td = r->d_func()->threadData.loadAcquire();
3831 td->ref();
3832 c->receiverThreadData.storeRelaxed(td);
3833 c->method_relative = method_index;
3834 c->method_offset = method_offset;
3835 c->connectionType = type;
3836 c->isSlotObject = false;
3837 c->argumentTypes.storeRelaxed(types);
3838 c->callFunction = callFunction;
3839 c->isSingleShot = isSingleShot;
3840
3841 QObjectPrivate::get(s)->addConnection(signal_index, c.get());
3842
3843 locker.unlock();
3844 QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
3845 if (smethod.isValid())
3846 s->connectNotify(smethod);
3847
3848 return c.release();
3849}
3850
3851/*!
3852 \internal
3853 */
3854bool QMetaObject::disconnect(const QObject *sender, int signal_index,
3855 const QObject *receiver, int method_index)
3856{
3857 const QMetaObject *smeta = sender->metaObject();
3858 signal_index = methodIndexToSignalIndex(&smeta, signal_index);
3859 return QMetaObjectPrivate::disconnect(sender, signal_index, smeta,
3860 receiver, method_index, nullptr);
3861}
3862
3863/*!
3864 \internal
3865
3866Disconnect a single signal connection. If QMetaObject::connect() has been called
3867multiple times for the same sender, signal_index, receiver and method_index only
3868one of these connections will be removed.
3869 */
3870bool QMetaObject::disconnectOne(const QObject *sender, int signal_index,
3871 const QObject *receiver, int method_index)
3872{
3873 const QMetaObject *smeta = sender->metaObject();
3874 signal_index = methodIndexToSignalIndex(&smeta, signal_index);
3875 return QMetaObjectPrivate::disconnect(sender, signal_index, smeta,
3876 receiver, method_index, nullptr,
3877 QMetaObjectPrivate::DisconnectOne);
3878}
3879
3880/*!
3881 \internal
3882 Helper function to remove the connection from the senders list and set the receivers to \nullptr
3883 */
3884bool QMetaObjectPrivate::disconnectHelper(QObjectPrivate::ConnectionData *connections, int signalIndex,
3885 const QObject *receiver, int method_index, void **slot,
3886 QBasicMutex *senderMutex, DisconnectType disconnectType)
3887{
3888 bool success = false;
3889
3890 auto &connectionList = connections->connectionsForSignal(signalIndex);
3891 auto *c = connectionList.first.loadRelaxed();
3892 while (c) {
3893 QObject *r = c->receiver.loadRelaxed();
3894 if (r && (receiver == nullptr || (r == receiver
3895 && (method_index < 0 || (!c->isSlotObject && c->method() == method_index))
3896 && (slot == nullptr || (c->isSlotObject && c->slotObj->compare(slot)))))) {
3897 bool needToUnlock = false;
3898 QBasicMutex *receiverMutex = nullptr;
3899 if (r) {
3900 receiverMutex = signalSlotLock(r);
3901 // need to relock this receiver and sender in the correct order
3902 needToUnlock = QOrderedMutexLocker::relock(senderMutex, receiverMutex);
3903 }
3904 if (c->receiver.loadRelaxed())
3905 connections->removeConnection(c);
3906
3907 if (needToUnlock)
3908 receiverMutex->unlock();
3909
3910 success = true;
3911
3912 if (disconnectType == DisconnectOne)
3913 return success;
3914 }
3915 c = c->nextConnectionList.loadRelaxed();
3916 }
3917 return success;
3918}
3919
3920/*!
3921 \internal
3922 Same as the QMetaObject::disconnect, but \a signal_index must be the result of QObjectPrivate::signalIndex
3923 */
3924bool QMetaObjectPrivate::disconnect(const QObject *sender,
3925 int signal_index, const QMetaObject *smeta,
3926 const QObject *receiver, int method_index, void **slot,
3927 DisconnectType disconnectType)
3928{
3929 if (!sender)
3930 return false;
3931
3932 QObject *s = const_cast<QObject *>(sender);
3933
3934 QBasicMutex *senderMutex = signalSlotLock(sender);
3935 QMutexLocker locker(senderMutex);
3936
3937 QObjectPrivate::ConnectionData *scd = QObjectPrivate::get(s)->connections.loadRelaxed();
3938 if (!scd)
3939 return false;
3940
3941 // Capture the message arguments now and emit the warning after unlocking:
3942 // qWarning() may re-enter connect/disconnect from the message handler and
3943 // deadlock on the lock held here (QTBUG-145216).
3944 struct WildcardDestroyedWarning
3945 {
3946 QByteArray className;
3947 QByteArray objectName;
3948 };
3949 std::optional<WildcardDestroyedWarning> wildcardDestroyedWarning;
3950
3951 bool success = false;
3952 {
3953 // prevent incoming connections changing the connections->receivers while unlocked
3954 QObjectPrivate::ConnectionDataPointer connections(scd);
3955
3956 if (signal_index < 0) {
3957 // wildcard disconnect - warn if this disconnects destroyed()
3958 if (!receiver && method_index < 0 && sender->d_func()->isSignalConnected(0)) {
3959 wildcardDestroyedWarning = WildcardDestroyedWarning{
3960 sender->metaObject()->className(),
3961 sender->objectName().toLocal8Bit()
3962 };
3963 }
3964 // remove from all connection lists
3965 for (int sig_index = -1; sig_index < scd->signalVectorCount(); ++sig_index) {
3966 if (disconnectHelper(connections.data(), sig_index, receiver, method_index, slot, senderMutex, disconnectType))
3967 success = true;
3968 }
3969 } else if (signal_index < scd->signalVectorCount()) {
3970 if (disconnectHelper(connections.data(), signal_index, receiver, method_index, slot, senderMutex, disconnectType))
3971 success = true;
3972 }
3973 }
3974
3975 locker.unlock();
3976
3977 if (wildcardDestroyedWarning) {
3978 qWarning("QObject::disconnect: wildcard call disconnects from destroyed signal of %s::%s",
3979 wildcardDestroyedWarning->className.constData(),
3980 wildcardDestroyedWarning->objectName.isEmpty()
3981 ? "unnamed"
3982 : wildcardDestroyedWarning->objectName.constData());
3983 }
3984
3985 if (success) {
3986 scd->cleanOrphanedConnections(s);
3987
3988 QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
3989 if (smethod.isValid())
3990 s->disconnectNotify(smethod);
3991 }
3992
3993 return success;
3994}
3995
3996// Helpers for formatting the connect statements of connectSlotsByName()'s debug mode
3997static QByteArray formatConnectionSignature(const char *className, const QMetaMethod &method)
3998{
3999 const auto signature = method.methodSignature();
4000 Q_ASSERT(signature.endsWith(')'));
4001 const qsizetype openParen = signature.indexOf('(');
4002 const bool hasParameters = openParen > 0 && openParen < signature.size() - 2;
4003 QByteArray result;
4004 if (hasParameters) {
4005 const qsizetype len = signature.size() - openParen - 2;
4006 result += "qOverload<" + QByteArrayView{signature}.slice(openParen + 1, len) + ">(";
4007 }
4008 result += '&';
4009 result += className + QByteArrayLiteral("::") + method.name();
4010 if (hasParameters)
4011 result += ')';
4012 return result;
4013}
4014
4015static QByteArray msgConnect(const QMetaObject *senderMo, const QByteArray &senderName,
4016 const QMetaMethod &signal, const QObject *receiver, int receiverIndex)
4017{
4018 const auto receiverMo = receiver->metaObject();
4019 const auto slot = receiverMo->method(receiverIndex);
4020 QByteArray message = QByteArrayLiteral("QObject::connect(")
4021 + senderName + ", " + formatConnectionSignature(senderMo->className(), signal)
4022 + ", " + receiver->objectName().toLatin1() + ", "
4023 + formatConnectionSignature(receiverMo->className(), slot) + ");";
4024 return message;
4025}
4026
4027/*!
4028 \fn void QMetaObject::connectSlotsByName(QObject *object)
4029
4030 Searches recursively for all child objects of the given \a object, and connects
4031 matching signals from them to slots of \a object that follow the following form:
4032
4033 \snippet code/src_corelib_kernel_qobject.cpp 33
4034
4035 Let's assume our object has a child object of type \c{QPushButton} with
4036 the \l{QObject::objectName}{object name} \c{button1}. The slot to catch the
4037 button's \c{clicked()} signal would be:
4038
4039 \snippet code/src_corelib_kernel_qobject.cpp 34
4040
4041 If \a object itself has a properly set object name, its own signals are also
4042 connected to its respective slots.
4043
4044 \sa QObject::setObjectName()
4045 */
4046void QMetaObject::connectSlotsByName(QObject *o)
4047{
4048 if (!o)
4049 return;
4050 const QMetaObject *mo = o->metaObject();
4051 Q_ASSERT(mo);
4052 const QObjectList list = // list of all objects to look for matching signals including...
4053 o->findChildren<QObject *>() // all children of 'o'...
4054 << o; // and the object 'o' itself
4055
4056 // for each method/slot of o ...
4057 for (int i = 0; i < mo->methodCount(); ++i) {
4058 const QByteArray slotSignature = mo->method(i).methodSignature();
4059 const char *slot = slotSignature.constData();
4060 Q_ASSERT(slot);
4061
4062 // ...that starts with "on_", ...
4063 if (slot[0] != 'o' || slot[1] != 'n' || slot[2] != '_')
4064 continue;
4065
4066 // ...we check each object in our list, ...
4067 bool foundIt = false;
4068 for (int j = 0; j < list.size(); ++j) {
4069 const QObject *co = list.at(j);
4070 const QByteArray coName = co->objectName().toLatin1();
4071
4072 // ...discarding those whose objectName is not fitting the pattern "on_<objectName>_...", ...
4073 if (coName.isEmpty() || qstrncmp(slot + 3, coName.constData(), coName.size()) || slot[coName.size()+3] != '_')
4074 continue;
4075
4076 const char *signal = slot + coName.size() + 4; // the 'signal' part of the slot name
4077
4078 // ...for the presence of a matching signal "on_<objectName>_<signal>".
4079 const QMetaObject *smeta;
4080 int sigIndex = co->d_func()->signalIndex(signal, &smeta);
4081 if (sigIndex < 0) {
4082 // if no exactly fitting signal (name + complete parameter type list) could be found
4083 // look for just any signal with the correct name and at least the slot's parameter list.
4084 // Note: if more than one of those signals exist, the one that gets connected is
4085 // chosen 'at random' (order of declaration in source file)
4086 QList<QByteArray> compatibleSignals;
4087 const QMetaObject *smo = co->metaObject();
4088 int sigLen = int(qstrlen(signal)) - 1; // ignore the trailing ')'
4089 for (int k = QMetaObjectPrivate::absoluteSignalCount(smo)-1; k >= 0; --k) {
4090 const QMetaMethod method = QMetaObjectPrivate::signal(smo, k);
4091 if (!qstrncmp(method.methodSignature().constData(), signal, sigLen)) {
4092 smeta = method.enclosingMetaObject();
4093 sigIndex = k;
4094 compatibleSignals.prepend(method.methodSignature());
4095 }
4096 }
4097 if (compatibleSignals.size() > 1)
4098 qCWarning(lcConnectSlotsByName) << "QMetaObject::connectSlotsByName: Connecting slot" << slot
4099 << "with the first of the following compatible signals:" << compatibleSignals;
4100 }
4101
4102 if (sigIndex < 0)
4103 continue;
4104
4105 // we connect it...
4106 if (Connection(QMetaObjectPrivate::connect(co, sigIndex, smeta, o, i))) {
4107 foundIt = true;
4108 qCDebug(lcConnectSlotsByName, "%s",
4109 msgConnect(smeta, coName, QMetaObjectPrivate::signal(smeta, sigIndex), o, i).constData());
4110 // ...and stop looking for further objects with the same name.
4111 // Note: the Designer will make sure each object name is unique in the above
4112 // 'list' but other code may create two child objects with the same name. In
4113 // this case one is chosen 'at random'.
4114 break;
4115 }
4116 }
4117 if (foundIt) {
4118 // we found our slot, now skip all overloads
4119 while (mo->method(i + 1).attributes() & QMetaMethod::Cloned)
4120 ++i;
4121 } else if (!(mo->method(i).attributes() & QMetaMethod::Cloned)) {
4122 // check if the slot has the following signature: "on_..._...(..."
4123 qsizetype iParen = slotSignature.indexOf('(');
4124 qsizetype iLastUnderscore = slotSignature.lastIndexOf('_', iParen - 1);
4125 if (iLastUnderscore > 3)
4126 qCWarning(lcConnectSlotsByName,
4127 "QMetaObject::connectSlotsByName: No matching signal for %s", slot);
4128 }
4129 }
4130}
4131
4132/*!
4133 \fn template<typename PointerToMemberFunction> QMetaObject::Connection QMetaObject::connect(
4134 const QObject *sender, const QMetaMethod &signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
4135
4136 \threadsafe
4137 \overload connect()
4138
4139 \since 6.10
4140
4141 Creates a connection of the given \a type from the \a signal in
4142 the \a sender object to the \a method in the \a receiver object.
4143 Returns a handle to the connection that can be used to disconnect
4144 it later.
4145
4146 The Connection handle will be invalid if it cannot create the
4147 connection, for example, the parameters were invalid.
4148 You can check if the QMetaObject::Connection is valid by casting
4149 it to a bool.
4150 Pass the returned handle to QObject::disconnect() to disconnect
4151 the connection.
4152
4153 A slot can be connected to a given signal if the signal has at
4154 least as many arguments as the slot. There must be an exact match
4155 between the corresponding signal and slot arguments, implicit
4156 conversions and type checking are not handled by this function.
4157 Overloaded slots need to be explicitly be resolved with
4158 help of \l qOverload.
4159 \a signal needs to be the meta-method of a signal, otherwise an
4160 invalid connection will be returned.
4161
4162 \sa QObject::connect(), QObject::disconnect()
4163 */
4164
4165/*!
4166 \fn template<typename Functor> QMetaObject::Connection QMetaObject::connect(
4167 const QObject *sender, const QMetaMethod &signal, const QObject *context, Functor functor, Qt::ConnectionType type)
4168
4169 \threadsafe
4170 \overload connect()
4171
4172 \since 6.10
4173
4174 Creates a connection of a given \a type from \a signal in
4175 \a sender object to \a functor to be placed in a specific event
4176 loop of \a context.
4177 Returns a handle to the connection that can be used to disconnect
4178 it later.
4179 This can be useful for connecting a signal retrieved from
4180 meta-object introspection to a lambda capturing local variables.
4181
4182 \note Qt::UniqueConnections do not work for lambdas, non-member
4183 functions and functors; they only apply to member functions.
4184
4185 The slot function can be any function or functor with with equal
4186 or fewer arguments than the signal. There must be an exact match
4187 between the corresponding signal and slot arguments, implicit
4188 conversions and type checking are not handled by this function.
4189 Overloaded functors need to be explicitly be resolved with
4190 help of \l qOverload.
4191 \a signal needs to be the meta-method of a signal, otherwise an
4192 invalid connection will be returned.
4193
4194 The connection will automatically disconnect if the sender or
4195 the context is destroyed.
4196 However, you should take care that any objects used within
4197 the functor are still alive when the signal is emitted.
4198
4199 \sa QObject::connect(), QObject::disconnect()
4200 */
4201QMetaObject::Connection QMetaObject::connectImpl(const QObject *sender, const QMetaMethod &signal,
4202 const QObject *receiver, void **slot,
4203 QtPrivate::QSlotObjectBase *slotObjRaw, Qt::ConnectionType type)
4204{
4205 QtPrivate::SlotObjUniquePtr slotObj(slotObjRaw);
4206 Q_ASSERT_X(slotObjRaw, "QMetaObject::connect", "Internal error, caller must not pass null slotObj");
4207
4208 const QMetaObject *senderMetaObject = sender->metaObject();
4209 if (!signal.isValid() || signal.methodType() != QMetaMethod::Signal) {
4210 connectWarning(sender, senderMetaObject, receiver, "invalid signal parameter");
4211 return QMetaObject::Connection();
4212 }
4213
4214 int signal_index;
4215 {
4216 int dummy;
4217 QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
4218 }
4219
4220 if (signal_index == -1) {
4221 qCWarning(lcConnect, "QObject::connect: Can't find signal %s on instance of class %s",
4222 signal.methodSignature().constData(), senderMetaObject->className());
4223 return QMetaObject::Connection();
4224 }
4225
4226 return QObjectPrivate::connectImpl(sender, signal_index, receiver, slot, slotObj.release(), type, nullptr, senderMetaObject);
4227}
4228
4229/*!
4230 \internal
4231 A small RAII helper for QSlotObjectBase.
4232 Calls ref on construction and destroyLastRef in its dtor.
4233 Allows construction from a nullptr in which case it does nothing.
4234 */
4236 SlotObjectGuard() = default;
4237 // move would be fine, but we do not need it currently
4245
4247 { return m_slotObject.get(); }
4248
4251
4252 ~SlotObjectGuard() = default;
4253private:
4254 QtPrivate::SlotObjUniquePtr m_slotObject;
4255};
4256
4257/*!
4258 \internal
4259
4260 \a signal must be in the signal index range (see QObjectPrivate::signalIndex()).
4261*/
4262static void queued_activate(QObject *sender, int signal, QObjectPrivate::Connection *c, void **argv)
4263{
4264 const int *argumentTypes = c->argumentTypes.loadRelaxed();
4265 if (!argumentTypes) {
4266 QMetaMethod m = QMetaObjectPrivate::signal(sender->metaObject(), signal);
4267 argumentTypes = queuedConnectionTypes(m);
4268 if (!argumentTypes) // cannot queue arguments
4269 argumentTypes = &DIRECT_CONNECTION_ONLY;
4270 if (!c->argumentTypes.testAndSetOrdered(nullptr, argumentTypes)) {
4271 if (argumentTypes != &DIRECT_CONNECTION_ONLY)
4272 delete[] argumentTypes;
4273 argumentTypes = c->argumentTypes.loadRelaxed();
4274 }
4275 }
4276 if (argumentTypes == &DIRECT_CONNECTION_ONLY) // cannot activate
4277 return;
4278 int nargs = 1; // include return type
4279 while (argumentTypes[nargs - 1])
4280 ++nargs;
4281
4282 QMutexLocker locker(signalSlotLock(c->receiver.loadRelaxed()));
4283 QObject *receiver = c->receiver.loadRelaxed();
4284 if (!receiver) {
4285 // the connection has been disconnected before we got the lock
4286 return;
4287 }
4288
4289 SlotObjectGuard slotObjectGuard { c->isSlotObject ? c->slotObj : nullptr };
4290 locker.unlock();
4291
4292 QVarLengthArray<const QtPrivate::QMetaTypeInterface *, 16> argTypes;
4293 argTypes.reserve(nargs);
4294 argTypes.emplace_back(nullptr); // return type
4295 for (int n = 1; n < nargs; ++n) {
4296 argTypes.emplace_back(QMetaType(argumentTypes[n - 1]).iface()); // convert type ids to QMetaTypeInterfaces
4297 }
4298
4299 auto ev = c->isSlotObject ?
4300 std::make_unique<QQueuedMetaCallEvent>(c->slotObj,
4301 sender, signal, nargs, argTypes.data(), argv) :
4302 std::make_unique<QQueuedMetaCallEvent>(c->method_offset, c->method_relative, c->callFunction,
4303 sender, signal, nargs, argTypes.data(), argv);
4304
4305 if (c->isSingleShot && !QObjectPrivate::removeConnection(c)) {
4306 return;
4307 }
4308
4309 locker.relock();
4310 if (!c->isSingleShot && !c->receiver.loadRelaxed()) {
4311 // the connection has been disconnected while we were unlocked
4312 locker.unlock();
4313 return;
4314 }
4315
4316 QCoreApplication::postEvent(receiver, ev.release());
4317}
4318
4319template <bool callbacks_enabled>
4320void doActivate(QObject *sender, int signal_index, void **argv)
4321{
4322 QObjectPrivate *sp = QObjectPrivate::get(sender);
4323
4324 if (sp->blockSig)
4325 return;
4326
4327 Q_TRACE_SCOPE(QMetaObject_activate, sender, signal_index);
4328
4329 if (sp->isDeclarativeSignalConnected(signal_index)
4330 && QAbstractDeclarativeData::signalEmitted) {
4331 Q_TRACE_SCOPE(QMetaObject_activate_declarative_signal, sender, signal_index);
4332 QAbstractDeclarativeData::signalEmitted(sp->declarativeData, sender,
4333 signal_index, argv);
4334 }
4335
4336 const QSignalSpyCallbackSet *signal_spy_set = callbacks_enabled ? qt_signal_spy_callback_set.loadAcquire() : nullptr;
4337
4338 void *empty_argv[] = { nullptr };
4339 if (!argv)
4340 argv = empty_argv;
4341
4342 bool senderDeleted = false;
4343 {
4344 QObjectPrivate::ConnectionDataPointer connections(sp->connections.loadAcquire());
4345 if (!connections || !sp->maybeSignalConnected(signal_index)) {
4346 // The possible declarative connection is done, and nothing else is connected
4347 if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
4348 signal_spy_set->signal_begin_callback(sender, signal_index, argv);
4349 if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
4350 signal_spy_set->signal_end_callback(sender, signal_index);
4351 return;
4352 }
4353
4354 if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
4355 signal_spy_set->signal_begin_callback(sender, signal_index, argv);
4356
4357 // loadAcquire pairs with the storeRelease in resizeSignalVector(), ensuring
4358 // that all writes to the new SignalVector's contents are visible here.
4359 QObjectPrivate::SignalVector *signalVector = connections->signalVector.loadAcquire();
4360
4361 const QObjectPrivate::ConnectionList *list;
4362 if (signal_index < signalVector->count())
4363 list = &signalVector->at(signal_index);
4364 else
4365 list = &signalVector->at(-1);
4366
4367 Qt::HANDLE currentThreadId = QThread::currentThreadId();
4368 bool inSenderThread = currentThreadId == QObjectPrivate::get(sender)->threadData.loadRelaxed()->threadId.loadRelaxed();
4369
4370 // We need to check against the highest connection id to ensure that signals added
4371 // during the signal emission are not emitted in this emission.
4372 uint highestConnectionId = connections->currentConnectionId.loadRelaxed();
4373 do {
4374 QObjectPrivate::Connection *c = list->first.loadAcquire();
4375 if (!c)
4376 continue;
4377
4378 do {
4379 QObject * const receiver = c->receiver.loadRelaxed();
4380 if (!receiver)
4381 continue;
4382
4383 QThreadData *td = c->receiverThreadData.loadRelaxed();
4384 if (!td)
4385 continue;
4386
4387 bool receiverInSameThread;
4388 if (inSenderThread) {
4389 receiverInSameThread = currentThreadId == td->threadId.loadRelaxed();
4390 } else {
4391 // need to lock before reading the threadId, because moveToThread() could interfere
4392 QMutexLocker lock(signalSlotLock(receiver));
4393 receiverInSameThread = currentThreadId == td->threadId.loadRelaxed();
4394 }
4395
4396
4397 // determine if this connection should be sent immediately or
4398 // put into the event queue
4399 if ((c->connectionType == Qt::AutoConnection && !receiverInSameThread)
4400 || (c->connectionType == Qt::QueuedConnection)) {
4401 queued_activate(sender, signal_index, c, argv);
4402 continue;
4403#if QT_CONFIG(thread)
4404 } else if (c->connectionType == Qt::BlockingQueuedConnection) {
4405 if (receiverInSameThread) {
4406 qWarning("Qt: Dead lock detected while activating a BlockingQueuedConnection: "
4407 "Sender is %s(%p), receiver is %s(%p)",
4408 sender->metaObject()->className(), sender,
4409 receiver->metaObject()->className(), receiver);
4410 }
4411
4412 if (c->isSingleShot && !QObjectPrivate::removeConnection(c))
4413 continue;
4414
4415 QLatch latch(1);
4416 {
4417 QMutexLocker locker(signalSlotLock(receiver));
4418 if (!c->isSingleShot && !c->receiver.loadAcquire())
4419 continue;
4420 QMetaCallEvent *ev = c->isSlotObject ?
4421 new QMetaCallEvent(c->slotObj, sender, signal_index, argv, &latch) :
4422 new QMetaCallEvent(c->method_offset, c->method_relative, c->callFunction,
4423 sender, signal_index, argv, &latch);
4424 QCoreApplication::postEvent(receiver, ev);
4425 }
4426 latch.wait();
4427 continue;
4428#endif
4429 }
4430
4431 if (c->isSingleShot && !QObjectPrivate::removeConnection(c))
4432 continue;
4433
4434 QObjectPrivate::Sender senderData(
4435 receiverInSameThread ? receiver : nullptr, sender, signal_index,
4436 receiverInSameThread ? QObjectPrivate::get(receiver)->connections.loadAcquire() : nullptr);
4437
4438 if (c->isSlotObject) {
4439 SlotObjectGuard obj{c->slotObj};
4440
4441 {
4442 Q_TRACE_SCOPE(QMetaObject_activate_slot_functor, c->slotObj);
4443 obj->call(receiver, argv);
4444 }
4445 } else if (c->callFunction && c->method_offset <= receiver->metaObject()->methodOffset()) {
4446 //we compare the vtable to make sure we are not in the destructor of the object.
4447 const int method_relative = c->method_relative;
4448 const auto callFunction = c->callFunction;
4449 const int methodIndex = (Q_HAS_TRACEPOINTS || callbacks_enabled) ? c->method() : 0;
4450 if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr)
4451 signal_spy_set->slot_begin_callback(receiver, methodIndex, argv);
4452
4453 {
4454 Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, methodIndex);
4455 callFunction(receiver, QMetaObject::InvokeMetaMethod, method_relative, argv);
4456 }
4457
4458 if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
4459 signal_spy_set->slot_end_callback(receiver, methodIndex);
4460 } else {
4461 const int method = c->method_relative + c->method_offset;
4462
4463 if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr) {
4464 signal_spy_set->slot_begin_callback(receiver, method, argv);
4465 }
4466
4467 {
4468 Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, method);
4469 QMetaObject::metacall(receiver, QMetaObject::InvokeMetaMethod, method, argv);
4470 }
4471
4472 if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
4473 signal_spy_set->slot_end_callback(receiver, method);
4474 }
4475 } while ((c = c->nextConnectionList.loadAcquire()) != nullptr && c->id.loadAcquire() <= highestConnectionId);
4476
4477 } while (list != &signalVector->at(-1) &&
4478 //start over for all signals;
4479 ((list = &signalVector->at(-1)), true));
4480
4481 if (connections->currentConnectionId.loadRelaxed() == 0)
4482 senderDeleted = true;
4483 }
4484
4485 if (!senderDeleted) {
4486 sp->connections.loadAcquire()->cleanOrphanedConnections(sender);
4487
4488 if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
4489 signal_spy_set->signal_end_callback(sender, signal_index);
4490 }
4491}
4492
4493/*!
4494 \internal
4495 */
4496void QMetaObject::activate(QObject *sender, const QMetaObject *m, int local_signal_index,
4497 void **argv)
4498{
4499 int signal_index = local_signal_index + QMetaObjectPrivate::signalOffset(m);
4500
4501 if (Q_UNLIKELY(qt_signal_spy_callback_set.loadRelaxed()))
4502 doActivate<true>(sender, signal_index, argv);
4503 else
4504 doActivate<false>(sender, signal_index, argv);
4505}
4506
4507/*!
4508 \internal
4509 */
4510void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_index, void **argv)
4511{
4512 int signal_index = signalOffset + local_signal_index;
4513
4514 if (Q_UNLIKELY(qt_signal_spy_callback_set.loadRelaxed()))
4515 doActivate<true>(sender, signal_index, argv);
4516 else
4517 doActivate<false>(sender, signal_index, argv);
4518}
4519
4520/*!
4521 \internal
4522 signal_index comes from indexOfMethod()
4523*/
4524void QMetaObject::activate(QObject *sender, int signal_index, void **argv)
4525{
4526 const QMetaObject *mo = sender->metaObject();
4527 while (mo->methodOffset() > signal_index)
4528 mo = mo->superClass();
4529 activate(sender, mo, signal_index - mo->methodOffset(), argv);
4530}
4531
4532/*!
4533 \internal
4534 Returns the signal index used in the internal connections->receivers vector.
4535
4536 It is different from QMetaObject::indexOfSignal(): indexOfSignal is the same as indexOfMethod
4537 while QObjectPrivate::signalIndex is smaller because it doesn't give index to slots.
4538
4539 If \a meta is not \nullptr, it is set to the meta-object where the signal was found.
4540*/
4541int QObjectPrivate::signalIndex(const char *signalName,
4542 const QMetaObject **meta) const
4543{
4544 Q_Q(const QObject);
4545 const QMetaObject *base = q->metaObject();
4546 Q_ASSERT(QMetaObjectPrivate::get(base)->revision >= 7);
4547 QArgumentTypeArray types;
4548 QByteArrayView name = QMetaObjectPrivate::decodeMethodSignature(signalName, types);
4549 int relative_index = QMetaObjectPrivate::indexOfSignalRelative(&base, name, types);
4550 if (relative_index < 0)
4551 return relative_index;
4552 relative_index = QMetaObjectPrivate::originalClone(base, relative_index);
4553 if (meta)
4554 *meta = base;
4555 return relative_index + QMetaObjectPrivate::signalOffset(base);
4556}
4557
4558/*****************************************************************************
4559 Properties
4560 *****************************************************************************/
4561
4562/*!
4563 \fn bool QObject::setProperty(const char *name, const QVariant &value)
4564
4565 Sets the value of the object's \a name property to \a value.
4566
4567 If the property is defined in the class using Q_PROPERTY then
4568 true is returned on success and false otherwise. If the property
4569 is not defined using Q_PROPERTY, and therefore not listed in the
4570 meta-object, it is added as a dynamic property and false is returned.
4571
4572 Information about all available properties is provided through the
4573 metaObject() and dynamicPropertyNames().
4574
4575 Dynamic properties can be queried again using property() and can be
4576 removed by setting the property value to an invalid QVariant.
4577 Changing the value of a dynamic property causes a QDynamicPropertyChangeEvent
4578 to be sent to the object.
4579
4580 \b{Note:} Dynamic properties starting with "_q_" are reserved for internal
4581 purposes.
4582
4583 \sa property(), metaObject(), dynamicPropertyNames(), QMetaProperty::write()
4584*/
4585
4586/*!
4587 \fn bool QObject::setProperty(const char *name, QVariant &&value)
4588 \since 6.6
4589 \overload setProperty
4590*/
4591
4592bool QObject::doSetProperty(const char *name, const QVariant &value, QVariant *rvalue)
4593{
4594 Q_D(QObject);
4595 const QMetaObject *meta = metaObject();
4596 if (!name || !meta)
4597 return false;
4598
4599 int id = meta->indexOfProperty(name);
4600 if (id < 0) {
4601 d->ensureExtraData();
4602
4603 const qsizetype idx = d->extraData->propertyNames.indexOf(name);
4604
4605 if (!value.isValid()) {
4606 if (idx == -1)
4607 return false;
4608 d->extraData->propertyNames.removeAt(idx);
4609 d->extraData->propertyValues.removeAt(idx);
4610 } else {
4611 if (idx == -1) {
4612 d->extraData->propertyNames.append(name);
4613 q_choose_append(d->extraData->propertyValues, value, rvalue);
4614 } else {
4615 if (value.userType() == d->extraData->propertyValues.at(idx).userType()
4616 && value == d->extraData->propertyValues.at(idx))
4617 return false;
4618 q_choose_assign(d->extraData->propertyValues[idx], value, rvalue);
4619 }
4620 }
4621
4622 QDynamicPropertyChangeEvent ev(name);
4623 QCoreApplication::sendEvent(this, &ev);
4624
4625 return false;
4626 }
4627 QMetaProperty p = meta->property(id);
4628#ifndef QT_NO_DEBUG
4629 if (!p.isWritable())
4630 qWarning("%s::setProperty: Property \"%s\" invalid,"
4631 " read-only or does not exist", metaObject()->className(), name);
4632#endif
4633 return rvalue ? p.write(this, std::move(*rvalue)) : p.write(this, value);
4634}
4635
4636/*!
4637 Returns the value of the object's \a name property.
4638
4639 If no such property exists, the returned variant is invalid.
4640
4641 Information about all available properties is provided through the
4642 metaObject() and dynamicPropertyNames().
4643
4644 \sa setProperty(), QVariant::isValid(), metaObject(), dynamicPropertyNames()
4645*/
4646QVariant QObject::property(const char *name) const
4647{
4648 Q_D(const QObject);
4649 const QMetaObject *meta = metaObject();
4650 if (!name || !meta)
4651 return QVariant();
4652
4653 int id = meta->indexOfProperty(name);
4654 if (id < 0) {
4655 if (!d->extraData)
4656 return QVariant();
4657 const qsizetype i = d->extraData->propertyNames.indexOf(name);
4658 return d->extraData->propertyValues.value(i);
4659 }
4660 QMetaProperty p = meta->property(id);
4661#ifndef QT_NO_DEBUG
4662 if (!p.isReadable())
4663 qWarning("%s::property: Property \"%s\" invalid or does not exist",
4664 metaObject()->className(), name);
4665#endif
4666 return p.read(this);
4667}
4668
4669/*!
4670 \since 4.2
4671
4672 Returns the names of all properties that were dynamically added to
4673 the object using setProperty().
4674*/
4675QList<QByteArray> QObject::dynamicPropertyNames() const
4676{
4677 Q_D(const QObject);
4678 if (d->extraData)
4679 return d->extraData->propertyNames;
4680 return QList<QByteArray>();
4681}
4682
4683/*****************************************************************************
4684 QObject debugging output routines.
4685 *****************************************************************************/
4686
4687std::string QObjectPrivate::flagsForDumping() const
4688{
4689 return {};
4690}
4691
4692static void dumpRecursive(int level, const QObject *object)
4693{
4694 if (object) {
4695 const int indent = level * 4;
4696 qDebug("%*s%s::%ls %s", indent, "", object->metaObject()->className(),
4697 qUtf16Printable(object->objectName()),
4698 QObjectPrivate::get(object)->flagsForDumping().c_str());
4699 for (auto child : object->children())
4700 dumpRecursive(level + 1, child);
4701 }
4702}
4703
4704
4705/*!
4706 Dumps a tree of children to the debug output.
4707
4708 \note Before Qt 5.9, this function was not const.
4709
4710 \sa dumpObjectInfo()
4711*/
4712
4713void QObject::dumpObjectTree() const
4714{
4715 dumpRecursive(0, this);
4716}
4717
4718/*!
4719 Dumps information about signal connections, etc. for this object
4720 to the debug output.
4721
4722 \note Before Qt 5.9, this function was not const.
4723
4724 \sa dumpObjectTree()
4725*/
4726
4727void QObject::dumpObjectInfo() const
4728{
4729 qDebug("OBJECT %s::%s", metaObject()->className(),
4730 objectName().isEmpty() ? "unnamed" : objectName().toLocal8Bit().data());
4731
4732 Q_D(const QObject);
4733 QMutexLocker locker(signalSlotLock(this));
4734
4735 // first, look for connections where this object is the sender
4736 qDebug(" SIGNALS OUT");
4737
4738 QObjectPrivate::ConnectionData *cd = d->connections.loadRelaxed();
4739 if (cd && cd->signalVectorCount() > 0) {
4740 QObjectPrivate::SignalVector *signalVector = cd->signalVector.loadRelaxed();
4741 for (int signal_index = 0; signal_index < signalVector->count(); ++signal_index) {
4742 const QObjectPrivate::Connection *c = signalVector->at(signal_index).first.loadRelaxed();
4743 if (!c)
4744 continue;
4745 const QMetaMethod signal = QMetaObjectPrivate::signal(metaObject(), signal_index);
4746 qDebug(" signal: %s", signal.methodSignature().constData());
4747
4748 // receivers
4749 while (c) {
4750 if (!c->receiver.loadRelaxed()) {
4751 qDebug(" <Disconnected receiver>");
4752 c = c->nextConnectionList.loadRelaxed();
4753 continue;
4754 }
4755 if (c->isSlotObject) {
4756 qDebug(" <functor or function pointer>");
4757 c = c->nextConnectionList.loadRelaxed();
4758 continue;
4759 }
4760 const QMetaObject *receiverMetaObject = c->receiver.loadRelaxed()->metaObject();
4761 const QMetaMethod method = receiverMetaObject->method(c->method());
4762 qDebug(" --> %s::%s %s",
4763 receiverMetaObject->className(),
4764 c->receiver.loadRelaxed()->objectName().isEmpty() ? "unnamed" : qPrintable(c->receiver.loadRelaxed()->objectName()),
4765 method.methodSignature().constData());
4766 c = c->nextConnectionList.loadRelaxed();
4767 }
4768 }
4769 } else {
4770 qDebug( " <None>" );
4771 }
4772
4773 // now look for connections where this object is the receiver
4774 qDebug(" SIGNALS IN");
4775
4776 if (cd && cd->senders) {
4777 for (QObjectPrivate::Connection *s = cd->senders; s; s = s->next) {
4778 QByteArray slotName = QByteArrayLiteral("<unknown>");
4779 if (!s->isSlotObject) {
4780 const QMetaMethod slot = metaObject()->method(s->method());
4781 slotName = slot.methodSignature();
4782 }
4783 qDebug(" <-- %s::%s %s",
4784 s->sender->metaObject()->className(),
4785 s->sender->objectName().isEmpty() ? "unnamed" : qPrintable(s->sender->objectName()),
4786 slotName.constData());
4787 }
4788 } else {
4789 qDebug(" <None>");
4790 }
4791}
4792
4793
4794#ifndef QT_NO_DEBUG_STREAM
4795void QObjectPrivate::writeToDebugStream(QDebug &dbg) const
4796{
4797 Q_Q(const QObject);
4798 dbg.nospace() << q->metaObject()->className() << '(' << (const void *)q;
4799 if (!q->objectName().isEmpty())
4800 dbg << ", name = " << q->objectName();
4801 dbg << ')';
4802}
4803
4804QDebug operator<<(QDebug dbg, const QObject *o)
4805{
4806 QDebugStateSaver saver(dbg);
4807 if (!o)
4808 return dbg << "QObject(0x0)";
4809
4810 const QObjectPrivate *d = QObjectPrivate::get(o);
4811 d->writeToDebugStream(dbg);
4812 return dbg;
4813}
4814#endif
4815
4816/*!
4817 \macro Q_CLASSINFO(Name, Value)
4818 \relates QObject
4819
4820 This macro associates extra information to the class, which is available
4821 using QObject::metaObject(). The extra information takes the form of a
4822 \a Name string and a \a Value literal string.
4823
4824 Example:
4825
4826 \snippet code/src_corelib_kernel_qobject.cpp 35
4827
4828 Qt makes use of the macro in \l{Qt D-Bus} and \l{Qt Qml} modules.
4829 For instance, when defining \l{QML Object Types} in C++, you can
4830 designate a property as the \e default one:
4831
4832 \snippet code/doc_src_properties.cpp 7
4833
4834 \sa QMetaObject::classInfo()
4835 \sa {Using Qt D-Bus Adaptors}
4836 \sa {Defining QML Types from C++}
4837*/
4838
4839/*!
4840 \macro Q_INTERFACES(...)
4841 \relates QObject
4842
4843 This macro tells Qt which interfaces the class implements. This
4844 is used when implementing plugins.
4845
4846 \sa Q_DECLARE_INTERFACE(), Q_PLUGIN_METADATA(), {How to Create Qt Plugins}
4847*/
4848
4849/*!
4850 \macro Q_PROPERTY(...)
4851 \relates QObject
4852
4853 This macro is used for declaring properties in classes that
4854 inherit QObject. Properties behave like class data members, but
4855 they have additional features accessible through the \l
4856 {Meta-Object System}.
4857
4858 \snippet code/doc_src_properties.cpp 0
4859
4860 The property name and type and the \c READ function are required.
4861 The type can be any type supported by QVariant, or it can be a
4862 user-defined type. The other items are optional, but a \c WRITE
4863 function is common. The attributes default to true except \c USER,
4864 which defaults to false.
4865
4866 For example:
4867
4868 \snippet code/src_corelib_kernel_qobject.cpp 37
4869
4870 For more details about how to use this macro, and a more detailed
4871 example of its use, see the discussion on \l {Qt's Property System}.
4872
4873 \sa {Qt's Property System}
4874*/
4875
4876/*!
4877 \macro Q_ENUMS(...)
4878 \relates QObject
4879 \deprecated [5.5]
4880
4881 In new code, you should prefer the use of the Q_ENUM() macro, which makes the
4882 type available also to the meta type system.
4883 For instance, QMetaEnum::fromType() will not work with types declared with Q_ENUMS().
4884
4885 This macro registers one or several enum types to the meta-object
4886 system.
4887
4888 If you want to register an enum that is declared in another class,
4889 the enum must be fully qualified with the name of the class
4890 defining it. In addition, the class \e defining the enum has to
4891 inherit QObject as well as declare the enum using Q_ENUMS().
4892
4893 \sa {Qt's Property System}
4894*/
4895
4896/*!
4897 \macro Q_FLAGS(...)
4898 \relates QObject
4899 \deprecated [5.5]
4900
4901 This macro registers one or several \l{QFlags}{flags types} with the
4902 meta-object system. It is typically used in a class definition to declare
4903 that values of a given enum can be used as flags and combined using the
4904 bitwise OR operator.
4905
4906 \note This macro takes care of registering individual flag values
4907 with the meta-object system, so it is unnecessary to use Q_ENUMS()
4908 in addition to this macro.
4909
4910 In new code, you should prefer the use of the Q_FLAG() macro, which makes the
4911 type available also to the meta type system.
4912
4913 \sa {Qt's Property System}
4914*/
4915
4916/*!
4917 \macro Q_ENUM(...)
4918 \relates QObject
4919 \since 5.5
4920
4921 This macro registers an enum type with the meta-object system.
4922 It must be placed after the enum declaration in a class that has the Q_OBJECT,
4923 Q_GADGET or Q_GADGET_EXPORT macro. For namespaces use \l Q_ENUM_NS() instead.
4924
4925 For example:
4926
4927 \snippet code/src_corelib_kernel_qobject.cpp 38
4928
4929 Enumerations that are declared with Q_ENUM have their QMetaEnum registered in the
4930 enclosing QMetaObject. You can also use QMetaEnum::fromType() to get the QMetaEnum.
4931
4932 Registered enumerations are automatically registered also to the Qt meta
4933 type system, making them known to QMetaType without the need to use
4934 Q_DECLARE_METATYPE(). This will enable useful features; for example, if used
4935 in a QVariant, you can convert them to strings. Likewise, passing them to
4936 QDebug will print out their names.
4937
4938 \sa {Qt's Property System}
4939*/
4940
4941
4942/*!
4943 \macro Q_FLAG(...)
4944 \relates QObject
4945 \since 5.5
4946
4947 This macro registers a single \l{QFlags}{flags type} with the
4948 meta-object system. It is typically used in a class definition to declare
4949 that values of a given enum can be used as flags and combined using the
4950 bitwise OR operator. For namespaces use \l Q_FLAG_NS() instead.
4951
4952 The macro must be placed after the enum declaration. The declaration of
4953 the flags type is done using the \l Q_DECLARE_FLAGS() macro.
4954
4955 For example, in QItemSelectionModel, the
4956 \l{QItemSelectionModel::SelectionFlags}{SelectionFlags} flag is
4957 declared in the following way:
4958
4959 \quotefromfile itemmodels/qitemselectionmodel.h
4960
4961 \skipto class Q_CORE_EXPORT QItemSelectionModel
4962 \printuntil Q_OBJECT
4963
4964 \dots
4965
4966 \skipto public:
4967 \printuntil Q_FLAG(SelectionFlags)
4968
4969 \skipuntil Q_DISABLE_COPY
4970 \printto Q_DECLARE_OPERATORS_FOR_FLAGS
4971
4972 \note The Q_FLAG macro takes care of registering individual flag values
4973 with the meta-object system, so it is unnecessary to use Q_ENUM()
4974 in addition to this macro.
4975
4976 \sa {Qt's Property System}
4977*/
4978
4979/*!
4980 \macro Q_ENUM_NS(...)
4981 \relates QObject
4982 \since 5.8
4983
4984 This macro registers an enum type with the meta-object system.
4985 It must be placed after the enum declaration in a namespace that
4986 has the Q_NAMESPACE macro. It is the same as \l Q_ENUM but in a
4987 namespace.
4988
4989 Enumerations that are declared with Q_ENUM_NS have their QMetaEnum
4990 registered in the enclosing QMetaObject. You can also use
4991 QMetaEnum::fromType() to get the QMetaEnum.
4992
4993 Registered enumerations are automatically registered also to the Qt meta
4994 type system, making them known to QMetaType without the need to use
4995 Q_DECLARE_METATYPE(). This will enable useful features; for example, if
4996 used in a QVariant, you can convert them to strings. Likewise, passing them
4997 to QDebug will print out their names.
4998
4999 \sa {Qt's Property System}
5000*/
5001
5002
5003/*!
5004 \macro Q_FLAG_NS(...)
5005 \relates QObject
5006 \since 5.8
5007
5008 This macro registers a single \l{QFlags}{flags type} with the
5009 meta-object system. It is used in a namespace that has the
5010 Q_NAMESPACE macro, to declare that values of a given enum can be
5011 used as flags and combined using the bitwise OR operator.
5012 It is the same as \l Q_FLAG but in a namespace.
5013
5014 The macro must be placed after the enum declaration.
5015
5016 \note The Q_FLAG_NS macro takes care of registering individual flag
5017 values with the meta-object system, so it is unnecessary to use
5018 Q_ENUM_NS() in addition to this macro.
5019
5020 \sa {Qt's Property System}
5021*/
5022
5023/*!
5024 \macro Q_OBJECT
5025 \relates QObject
5026
5027 The Q_OBJECT macro is used to enable meta-object features, such as dynamic
5028 properties, signals, and slots.
5029
5030 You can add the Q_OBJECT macro to any section of a class definition that
5031 declares its own signals and slots or that uses other services provided by
5032 Qt's meta-object system.
5033
5034//! [qobject-macros-private-access-specifier]
5035 \note This macro expansion ends with a \c private: access specifier. If you
5036 declare members immediately after this macro, those members will also be
5037 private. To add public (or protected) members right after the macro, use a
5038 \c {public:} (or \c {protected:}) access specifier.
5039//! [qobject-macros-private-access-specifier]
5040
5041 Example:
5042
5043 \snippet signalsandslots/signalsandslots.h 1
5044 \codeline
5045 \snippet signalsandslots/signalsandslots.h 2
5046 \snippet signalsandslots/signalsandslots.h 3
5047
5048 \note This macro requires the class to be a subclass of QObject. Use
5049 Q_GADGET or Q_GADGET_EXPORT instead of Q_OBJECT to enable the meta object
5050 system's support for enums in a class that is not a QObject subclass.
5051
5052 \sa {Meta-Object System}, {Signals and Slots}, {Qt's Property System}
5053*/
5054
5055/*!
5056 \macro Q_GADGET
5057 \relates QObject
5058
5059 The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes
5060 that do not inherit from QObject but still want to use some of the
5061 reflection capabilities offered by QMetaObject.
5062
5063 \include qobject.cpp qobject-macros-private-access-specifier
5064
5065 Q_GADGETs can have Q_ENUM, Q_PROPERTY and Q_INVOKABLE, but they cannot have
5066 signals or slots.
5067
5068 Q_GADGET makes a class member, \c{staticMetaObject}, available.
5069 \c{staticMetaObject} is of type QMetaObject and provides access to the
5070 enums declared with Q_ENUM.
5071
5072 \sa Q_GADGET_EXPORT
5073*/
5074
5075/*!
5076 \macro Q_GADGET_EXPORT(EXPORT_MACRO)
5077 \relates QObject
5078 \since 6.3
5079
5080 The Q_GADGET_EXPORT macro works exactly like the Q_GADGET macro.
5081 However, the \c{staticMetaObject} variable that is made available (see
5082 Q_GADGET) is declared with the supplied \a EXPORT_MACRO qualifier. This is
5083 useful if the object needs to be exported from a dynamic library, but the
5084 enclosing class as a whole should not be (e.g. because it consists of mostly
5085 inline functions).
5086
5087 \include qobject.cpp qobject-macros-private-access-specifier
5088
5089 For example:
5090
5091 \code
5092 class Point {
5093 Q_GADGET_EXPORT(EXPORT_MACRO)
5094 Q_PROPERTY(int x MEMBER x)
5095 Q_PROPERTY(int y MEMBER y)
5096 ~~~
5097 \endcode
5098
5099 \sa Q_GADGET, {Creating Shared Libraries}
5100*/
5101
5102/*!
5103 \macro Q_NAMESPACE
5104 \relates QObject
5105 \since 5.8
5106
5107 The Q_NAMESPACE macro can be used to add QMetaObject capabilities
5108 to a namespace.
5109
5110 Q_NAMESPACEs can have Q_CLASSINFO, Q_ENUM_NS, Q_FLAG_NS, but they
5111 cannot have Q_ENUM, Q_FLAG, Q_PROPERTY, Q_INVOKABLE, signals nor slots.
5112
5113 Q_NAMESPACE makes an external variable, \c{staticMetaObject}, available.
5114 \c{staticMetaObject} is of type QMetaObject and provides access to the
5115 enums declared with Q_ENUM_NS/Q_FLAG_NS.
5116
5117 For example:
5118
5119 \code
5120 namespace test {
5121 Q_NAMESPACE
5122 ...
5123 \endcode
5124
5125 \sa Q_NAMESPACE_EXPORT
5126*/
5127
5128/*!
5129 \macro Q_NAMESPACE_EXPORT(EXPORT_MACRO)
5130 \relates QObject
5131 \since 5.14
5132
5133 The Q_NAMESPACE_EXPORT macro can be used to add QMetaObject capabilities
5134 to a namespace.
5135
5136 It works exactly like the Q_NAMESPACE macro. However, the external
5137 \c{staticMetaObject} variable that gets defined in the namespace
5138 is declared with the supplied \a EXPORT_MACRO qualifier. This is
5139 useful if the object needs to be exported from a dynamic library.
5140
5141 For example:
5142
5143 \code
5144 namespace test {
5145 Q_NAMESPACE_EXPORT(EXPORT_MACRO)
5146 ...
5147 \endcode
5148
5149 \sa Q_NAMESPACE, {Creating Shared Libraries}
5150*/
5151
5152/*!
5153 \macro Q_MOC_INCLUDE
5154 \relates QObject
5155 \since 6.0
5156
5157 The Q_MOC_INCLUDE macro can be used within or outside a class, and tell the
5158 \l{moc}{Meta Object Compiler} to add an include.
5159
5160 \code
5161 // Put this in your code and the generated code will include this header.
5162 Q_MOC_INCLUDE("myheader.h")
5163 \endcode
5164
5165 This is useful if the types you use as properties or signal/slots arguments
5166 are forward declared.
5167*/
5168
5169/*!
5170 \macro Q_SIGNALS
5171 \relates QObject
5172
5173 Use this macro to replace the \c signals keyword in class
5174 declarations, when you want to use Qt Signals and Slots with a
5175 \l{3rd Party Signals and Slots} {3rd party signal/slot mechanism}.
5176
5177 The macro is normally used when \c no_keywords is specified with
5178 the \c CONFIG variable in the \c .pro file, but it can be used
5179 even when \c no_keywords is \e not specified.
5180*/
5181
5182/*!
5183 \macro Q_SIGNAL
5184 \relates QObject
5185
5186 This is an additional macro that allows you to mark a single
5187 function as a signal. It can be quite useful, especially when you
5188 use a 3rd-party source code parser which doesn't understand a \c
5189 signals or \c Q_SIGNALS groups.
5190
5191 Use this macro to replace the \c signals keyword in class
5192 declarations, when you want to use Qt Signals and Slots with a
5193 \l{3rd Party Signals and Slots} {3rd party signal/slot mechanism}.
5194
5195 The macro is normally used when \c no_keywords is specified with
5196 the \c CONFIG variable in the \c .pro file, but it can be used
5197 even when \c no_keywords is \e not specified.
5198*/
5199
5200/*!
5201 \macro Q_SLOTS
5202 \relates QObject
5203
5204 Use this macro to replace the \c slots keyword in class
5205 declarations, when you want to use Qt Signals and Slots with a
5206 \l{3rd Party Signals and Slots} {3rd party signal/slot mechanism}.
5207
5208 The macro is normally used when \c no_keywords is specified with
5209 the \c CONFIG variable in the \c .pro file, but it can be used
5210 even when \c no_keywords is \e not specified.
5211*/
5212
5213/*!
5214 \macro Q_SLOT
5215 \relates QObject
5216
5217 This is an additional macro that allows you to mark a single
5218 function as a slot. It can be quite useful, especially when you
5219 use a 3rd-party source code parser which doesn't understand a \c
5220 slots or \c Q_SLOTS groups.
5221
5222 Use this macro to replace the \c slots keyword in class
5223 declarations, when you want to use Qt Signals and Slots with a
5224 \l{3rd Party Signals and Slots} {3rd party signal/slot mechanism}.
5225
5226 The macro is normally used when \c no_keywords is specified with
5227 the \c CONFIG variable in the \c .pro file, but it can be used
5228 even when \c no_keywords is \e not specified.
5229*/
5230
5231/*!
5232 \macro Q_EMIT
5233 \relates QObject
5234
5235 Use this macro to replace the \c emit keyword for emitting
5236 signals, when you want to use Qt Signals and Slots with a
5237 \l{3rd Party Signals and Slots} {3rd party signal/slot mechanism}.
5238
5239 The macro is normally used when \c no_keywords is specified with
5240 the \c CONFIG variable in the \c .pro file, but it can be used
5241 even when \c no_keywords is \e not specified.
5242*/
5243
5244/*!
5245 \macro Q_INVOKABLE
5246 \relates QObject
5247
5248 Apply this macro to declarations of member functions to allow them to
5249 be invoked via the meta-object system. The macro is written before
5250 the return type, as shown in the following example:
5251
5252 \snippet qmetaobject-invokable/window.h Window class with invokable method
5253
5254 The \c invokableMethod() function is marked up using Q_INVOKABLE, causing
5255 it to be registered with the meta-object system and enabling it to be
5256 invoked using QMetaObject::invokeMethod().
5257 Since \c normalMethod() function is not registered in this way, it cannot
5258 be invoked using QMetaObject::invokeMethod().
5259
5260 If an invokable member function returns a pointer to a QObject or a
5261 subclass of QObject and it is invoked from QML, special ownership rules
5262 apply. See \l{qtqml-cppintegration-data.html}{Data Type Conversion Between QML and C++}
5263 for more information.
5264*/
5265
5266/*!
5267 \macro Q_REVISION
5268 \relates QObject
5269
5270 Apply this macro to declarations of member functions to tag them with a
5271 revision number in the meta-object system. The macro is written before
5272 the return type, as shown in the following example:
5273
5274 \snippet qmetaobject-revision/window.h Window class with revision
5275
5276 This is useful when using the meta-object system to dynamically expose
5277 objects to another API, as you can match the version expected by multiple
5278 versions of the other API. Consider the following simplified example:
5279
5280 \snippet qmetaobject-revision/main.cpp Window class using revision
5281
5282 Using the same Window class as the previous example, the newProperty and
5283 newMethod would only be exposed in this code when the expected version is
5284 \c{2.1} or greater.
5285
5286 Since all methods are considered to be in revision \c{0} if untagged, a tag
5287 of \c{Q_REVISION(0)} or \c{Q_REVISION(0, 0)} is invalid and ignored.
5288
5289 You can pass one or two integer parameters to \c{Q_REVISION}. If you pass
5290 one parameter, it denotes the minor version only. This means that the major
5291 version is unspecified. If you pass two, the first parameter is the major
5292 version and the second parameter is the minor version.
5293
5294 This tag is not used by the meta-object system itself. Currently this is only
5295 used by the QtQml module.
5296
5297 For a more generic string tag, see \l QMetaMethod::tag()
5298
5299 \sa QMetaMethod::revision()
5300*/
5301
5302/*!
5303 \macro Q_SET_OBJECT_NAME(Object)
5304 \relates QObject
5305 \since 5.0
5306
5307 This macro assigns \a Object the objectName "Object".
5308
5309 It doesn't matter whether \a Object is a pointer or not, the
5310 macro figures that out by itself.
5311
5312 \sa QObject::objectName()
5313*/
5314
5315/*!
5316 \macro QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
5317 \relates QObject
5318 \since 5.8
5319
5320 Defining this macro will disable narrowing and floating-point-to-integral
5321 conversions between the arguments carried by a signal and the arguments
5322 accepted by a slot, when the signal and the slot are connected using the
5323 PMF-based syntax.
5324
5325 \sa QObject::connect
5326*/
5327
5328/*!
5329 \macro QT_NO_CONTEXTLESS_CONNECT
5330 \relates QObject
5331 \since 6.7
5332
5333 Defining this macro will disable the overload of QObject::connect() that
5334 connects a signal to a functor, without also specifying a QObject
5335 as a receiver/context object (that is, the 3-arguments overload
5336 of QObject::connect()).
5337
5338 Using the context-less overload is error prone, because it is easy
5339 to connect to functors that depend on some local state of the
5340 receiving end. If such local state gets destroyed, the connection
5341 does not get automatically disconnected.
5342
5343 Moreover, such connections are always direct connections, which may
5344 cause issues in multithreaded scenarios (for instance, if the
5345 signal is emitted from another thread).
5346
5347 \sa QObject::connect, Qt::ConnectionType
5348*/
5349
5350/*!
5351 \since 6.12
5352 \macro QT_NO_DISCONNECT_CONST_CONNECTION
5353 \relates QObject
5354
5355 Disables the \c{const &} overload of
5356 \l{QObject::disconnect(QMetaObject::Connection&)}{QObject::disconnect()} to
5357 force callers to pass non-const objects.
5358
5359 Passing non-const objects is preferred, because they can be reset
5360 immediately, releasing resources sooner. Different versions of Qt handle
5361 the const overload differently. In older Qt versions, calling the const
5362 overload with a Connection originally declared \c{const} may invoke
5363 undefined behavior. Current Qt versions are safe in this regard, but future
5364 Qt versions may remove the const overload, or have it delay releasing
5365 resources until the Connection object is reassigned or destroyed.
5366
5367 Passing non-const objects avoids all of the issues above.
5368
5369 Code that compiles with this macro set also compiles (and doesn't invoke
5370 undefined behavior) without the macro enabled, and in all Qt versions since
5371 5.0.
5372*/
5373
5374/*!
5375 \typedef QObjectList
5376 \relates QObject
5377
5378 Synonym for QList<QObject *>.
5379*/
5380
5381/*!
5382 \fn template<typename PointerToMemberFunction> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
5383 \overload connect()
5384 \threadsafe
5385
5386 Creates a connection of the given \a type from the \a signal in
5387 the \a sender object to the \a method in the \a receiver object.
5388 Returns a handle to the connection that can be used to disconnect
5389 it later.
5390
5391 The signal must be a function declared as a signal in the header.
5392 The slot function can be any member function that can be connected
5393 to the signal.
5394 A slot can be connected to a given signal if the signal has at
5395 least as many arguments as the slot, and there is an implicit
5396 conversion between the types of the corresponding arguments in the
5397 signal and the slot.
5398
5399 Example:
5400
5401 \snippet code/src_corelib_kernel_qobject.cpp 44
5402
5403 This example ensures that the label always displays the current
5404 line edit text.
5405
5406 A signal can be connected to many slots and signals. Many signals
5407 can be connected to one slot.
5408
5409 If a signal is connected to several slots, the slots are activated
5410 in the same order as the order the connection was made, when the
5411 signal is emitted
5412
5413 The function returns an handle to a connection if it successfully
5414 connects the signal to the slot. The Connection handle will be invalid
5415 if it cannot create the connection, for example, if QObject is unable
5416 to verify the existence of \a signal (if it was not declared as a signal)
5417 You can check if the QMetaObject::Connection is valid by casting it to a bool.
5418
5419 By default, a signal is emitted for every connection you make;
5420 two signals are emitted for duplicate connections. You can break
5421 all of these connections with a single disconnect() call.
5422 If you pass the Qt::UniqueConnection \a type, the connection will only
5423 be made if it is not a duplicate. If there is already a duplicate
5424 (exact same signal to the exact same slot on the same objects),
5425 the connection will fail and connect will return an invalid QMetaObject::Connection.
5426
5427 The optional \a type parameter describes the type of connection
5428 to establish. In particular, it determines whether a particular
5429 signal is delivered to a slot immediately or queued for delivery
5430 at a later time. If the signal is queued, the parameters must be
5431 of types that are known to Qt's meta-object system, because Qt
5432 needs to copy the arguments to store them in an event behind the
5433 scenes. If you try to use a queued connection and get the error
5434 message
5435
5436 \snippet code/src_corelib_kernel_qobject.cpp 25
5437
5438 make sure to declare the argument type with Q_DECLARE_METATYPE
5439
5440 Overloaded functions can be resolved with help of \l qOverload.
5441
5442 \sa {Differences between String-Based and Functor-Based Connections}
5443 */
5444
5445/*!
5446 \fn template<typename PointerToMemberFunction, typename Functor> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
5447
5448 \threadsafe
5449 \overload connect()
5450
5451 Creates a connection from \a signal in
5452 \a sender object to \a functor, and returns a handle to the connection
5453
5454 The signal must be a function declared as a signal in the header.
5455 The slot function can be any function or functor that can be connected
5456 to the signal.
5457 A slot function can be connected to a given signal if the signal has at
5458 least as many arguments as the slot function. There must exist implicit
5459 conversion between the types of the corresponding arguments in the
5460 signal and the slot.
5461
5462 Example:
5463
5464 \snippet code/src_corelib_kernel_qobject.cpp 45
5465
5466 Lambda expressions can also be used:
5467
5468 \snippet code/src_corelib_kernel_qobject.cpp 46
5469
5470 The connection will automatically disconnect if the sender is destroyed.
5471 However, you should take care that any objects used within the functor
5472 are still alive when the signal is emitted.
5473
5474 For this reason, it is recommended to use the overload of connect()
5475 that also takes a QObject as a receiver/context. It is possible
5476 to disable the usage of the context-less overload by defining the
5477 \c{QT_NO_CONTEXTLESS_CONNECT} macro.
5478
5479 Overloaded functions can be resolved with help of \l qOverload.
5480
5481 */
5482
5483/*!
5484 \fn template<typename PointerToMemberFunction, typename Functor> QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
5485
5486 \threadsafe
5487 \overload connect()
5488
5489 \since 5.2
5490
5491 Creates a connection of a given \a type from \a signal in
5492 \a sender object to \a functor to be placed in a specific event
5493 loop of \a context, and returns a handle to the connection.
5494
5495 \note Qt::UniqueConnections do not work for lambdas, non-member functions
5496 and functors; they only apply to connecting to member functions.
5497
5498 The signal must be a function declared as a signal in the header.
5499 The slot function can be any function or functor that can be connected
5500 to the signal.
5501 A slot function can be connected to a given signal if the signal has at
5502 least as many arguments as the slot function. There must exist implicit
5503 conversion between the types of the corresponding arguments in the
5504 signal and the slot.
5505
5506 Example:
5507
5508 \snippet code/src_corelib_kernel_qobject.cpp 50_someFunction
5509 \snippet code/src_corelib_kernel_qobject.cpp 50
5510
5511 Lambda expressions can also be used:
5512
5513 \snippet code/src_corelib_kernel_qobject.cpp 51
5514
5515 The connection will automatically disconnect if the sender or the context
5516 is destroyed.
5517 However, you should take care that any objects used within the functor
5518 are still alive when the signal is emitted.
5519
5520 Overloaded functions can be resolved with help of \l qOverload.
5521 */
5522
5523/*!
5524 \internal
5525
5526 Implementation of the template version of connect
5527
5528 \a sender is the sender object
5529 \a signal is a pointer to a pointer to a member signal of the sender
5530 \a receiver is the receiver object, may not be \nullptr, will be equal to sender when
5531 connecting to a static function or a functor
5532 \a slot a pointer only used when using Qt::UniqueConnection
5533 \a type the Qt::ConnectionType passed as argument to connect
5534 \a types an array of integer with the metatype id of the parameter of the signal
5535 to be used with queued connection
5536 must stay valid at least for the whole time of the connection, this function
5537 do not take ownership. typically static data.
5538 If \nullptr, then the types will be computed when the signal is emit in a queued
5539 connection from the types from the signature.
5540 \a senderMetaObject is the metaobject used to lookup the signal, the signal must be in
5541 this metaobject
5542 */
5543QMetaObject::Connection QObject::connectImpl(const QObject *sender, void **signal,
5544 const QObject *receiver, void **slot,
5545 QtPrivate::QSlotObjectBase *slotObjRaw, Qt::ConnectionType type,
5546 const int *types, const QMetaObject *senderMetaObject)
5547{
5548 QtPrivate::SlotObjUniquePtr slotObj(slotObjRaw);
5549 Q_ASSERT_X(slotObjRaw, "QObject::connect", "Internal error, caller must not pass null slotObj");
5550 if (!signal) {
5551 connectWarning(sender, senderMetaObject, receiver, "invalid nullptr parameter");
5552 return QMetaObject::Connection();
5553 }
5554
5555 int signal_index = -1;
5556 void *args[] = { &signal_index, signal };
5557 for (; senderMetaObject && signal_index < 0; senderMetaObject = senderMetaObject->superClass()) {
5558 senderMetaObject->static_metacall(QMetaObject::IndexOfMethod, 0, args);
5559 if (signal_index >= 0 && signal_index < QMetaObjectPrivate::get(senderMetaObject)->signalCount)
5560 break;
5561 }
5562 if (!senderMetaObject) {
5563 connectWarning(sender, senderMetaObject, receiver, "signal not found");
5564 return QMetaObject::Connection(nullptr);
5565 }
5566 signal_index += QMetaObjectPrivate::signalOffset(senderMetaObject);
5567 return QObjectPrivate::connectImpl(sender, signal_index, receiver, slot, slotObj.release(), type, types, senderMetaObject);
5568}
5569
5570/*!
5571 \internal
5572
5573 Internal version of connect used by the template version of QObject::connect (called via connectImpl) and
5574 also used by the QObjectPrivate::connect version used by QML. The signal_index is expected to be relative
5575 to the number of signals.
5576 */
5577QMetaObject::Connection QObjectPrivate::connectImpl(const QObject *sender, int signal_index,
5578 const QObject *receiver, void **slot,
5579 QtPrivate::QSlotObjectBase *slotObjRaw, int type,
5580 const int *types, const QMetaObject *senderMetaObject)
5581{
5582 QtPrivate::SlotObjUniquePtr slotObj(slotObjRaw);
5583 Q_ASSERT(senderMetaObject);
5584 Q_ASSERT(slotObj);
5585
5586 if (!sender || !receiver) {
5587 connectWarning(sender, senderMetaObject, receiver, "invalid nullptr parameter");
5588 return QMetaObject::Connection();
5589 }
5590
5591 if (type & Qt::UniqueConnection && !slot) {
5592 connectWarning(sender, senderMetaObject, receiver, "unique connections require a pointer to member function of a QObject subclass");
5593 return QMetaObject::Connection();
5594 }
5595
5596 QObject *s = const_cast<QObject *>(sender);
5597 QObject *r = const_cast<QObject *>(receiver);
5598
5599 QOrderedMutexLocker locker(signalSlotLock(sender),
5600 signalSlotLock(receiver));
5601
5602 if (type & Qt::UniqueConnection) {
5603 QObjectPrivate::ConnectionData *connections = QObjectPrivate::get(s)->connections.loadRelaxed();
5604 if (connections && connections->signalVectorCount() > signal_index) {
5605 const QObjectPrivate::Connection *c2 = connections->signalVector.loadRelaxed()->at(signal_index).first.loadRelaxed();
5606
5607 while (c2) {
5608 if (c2->receiver.loadRelaxed() == receiver && c2->isSlotObject && c2->slotObj->compare(slot))
5609 return QMetaObject::Connection();
5610 c2 = c2->nextConnectionList.loadRelaxed();
5611 }
5612 }
5613 }
5614 type &= ~Qt::UniqueConnection;
5615
5616 const bool isSingleShot = type & Qt::SingleShotConnection;
5617 type &= ~Qt::SingleShotConnection;
5618
5619 Q_ASSERT(type >= 0);
5620 Q_ASSERT(type <= 3);
5621
5622 std::unique_ptr<QObjectPrivate::Connection> c{new QObjectPrivate::Connection};
5623 c->sender = s;
5624 c->signal_index = signal_index;
5625 QThreadData *td = r->d_func()->threadData.loadAcquire();
5626 td->ref();
5627 c->receiverThreadData.storeRelaxed(td);
5628 c->receiver.storeRelaxed(r);
5629 c->connectionType = type;
5630 c->isSlotObject = true;
5631 c->slotObj = slotObj.release();
5632 if (types) {
5633 c->argumentTypes.storeRelaxed(types);
5634 c->ownArgumentTypes = false;
5635 }
5636 c->isSingleShot = isSingleShot;
5637
5638 QObjectPrivate::get(s)->addConnection(signal_index, c.get());
5639 QMetaObject::Connection ret(c.release());
5640 locker.unlock();
5641
5642 QMetaMethod method = QMetaObjectPrivate::signal(senderMetaObject, signal_index);
5643 Q_ASSERT(method.isValid());
5644 s->connectNotify(method);
5645
5646 return ret;
5647}
5648
5649#ifndef QT_NO_DISCONNECT_CONST_CONNECTION
5650/*!
5651 Disconnects \a connection and resets it to
5652 \l{QMetaObject::Connection::operator bool()}{invalid}.
5653
5654 If \a connection is invalid or has already been disconnected, do nothing
5655 and return false.
5656
5657 \note Future versions of Qt may only accept non-const objects here.
5658
5659 \sa QT_NO_DISCONNECT_CONST_CONNECTION
5660 \sa connect()
5661 */
5662bool QObject::disconnect(const QMetaObject::Connection &connection)
5663{
5664 // keep in sync with non-const overload
5665 QObjectPrivate::Connection *c = static_cast<QObjectPrivate::Connection *>(connection.d_ptr);
5666 if (!c)
5667 return false;
5668 const bool disconnected = QObjectPrivate::removeConnection(c);
5669 connection.d_ptr = nullptr;
5670 c->deref(); // has been removed from the QMetaObject::Connection object
5671 return disconnected;
5672}
5673#endif // QT_NO_DISCONNECT_CONST_CONNECTION
5674
5675/*!
5676 \since 6.12
5677 \fn bool QObject::disconnect(QMetaObject::Connection &connection)
5678 \fn bool QObject::disconnect(QMetaObject::Connection &&connection)
5679
5680 Disconnect a connection.
5681
5682 If \a connection is
5683 \l{QMetaObject::Connection::operator bool()}{invalid}
5684 or has already been disconnected, do nothing and return false.
5685
5686 \note In Qt versions prior to 6.12, this function took only by \c{const-&}.
5687
5688 \sa connect()
5689 */
5690bool QObject::disconnect(QMetaObject::Connection &connection)
5691{
5692 // keep in sync with the overload above
5693 QObjectPrivate::Connection *c = static_cast<QObjectPrivate::Connection *>(connection.d_ptr);
5694 if (!c)
5695 return false;
5696 const bool disconnected = QObjectPrivate::removeConnection(c);
5697 connection.d_ptr = nullptr;
5698 c->deref(); // has been removed from the QMetaObject::Connection object
5699 return disconnected;
5700}
5701
5702/*! \fn template<typename PointerToMemberFunction> bool QObject::disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method)
5703 \overload disconnect()
5704 \threadsafe
5705
5706 Disconnects \a signal in object \a sender from \a method in object
5707 \a receiver. Returns \c true if the connection is successfully broken;
5708 otherwise returns \c false.
5709
5710 A signal-slot connection is removed when either of the objects
5711 involved are destroyed.
5712
5713 disconnect() is typically used in three ways, as the following
5714 examples demonstrate.
5715 \list 1
5716 \li Disconnect everything connected to an object's signals:
5717
5718 \snippet code/src_corelib_kernel_qobject.cpp 26
5719
5720 \li Disconnect everything connected to a specific signal:
5721
5722 \snippet code/src_corelib_kernel_qobject.cpp 47
5723
5724 \li Disconnect a specific receiver:
5725
5726 \snippet code/src_corelib_kernel_qobject.cpp 30
5727
5728 \li Disconnect a connection from one specific signal to a specific slot:
5729
5730 \snippet code/src_corelib_kernel_qobject.cpp 48
5731
5732
5733 \endlist
5734
5735 \nullptr may be used as a wildcard, meaning "any signal", "any receiving
5736 object", or "any slot in the receiving object", respectively.
5737
5738 The \a sender may never be \nullptr. (You cannot disconnect signals
5739 from more than one object in a single call.)
5740
5741 If \a signal is \nullptr, it disconnects \a receiver and \a method from
5742 any signal. If not, only the specified signal is disconnected.
5743
5744 If \a receiver is \nullptr, it disconnects anything connected to \a
5745 signal. If not, only slots in the specified receiver are disconnected.
5746 disconnect() with a non-null \a receiver also disconnects slot functions
5747 that were connected with \a receiver as their context object.
5748
5749 If \a method is \nullptr, it disconnects anything that is connected to \a
5750 receiver. If not, only slots named \a method will be disconnected,
5751 and all other slots are left alone. The \a method must be \nullptr
5752 if \a receiver is left out, so you cannot disconnect a
5753 specifically-named slot on all objects.
5754
5755 \include includes/qobject.qdocinc disconnect-duplicates
5756
5757 \note It is not possible to use this overload to disconnect signals
5758 connected to functors or lambda expressions. That is because it is not
5759 possible to compare them. Instead, use the overload that takes a
5760 QMetaObject::Connection.
5761
5762 \note Unless \a method is \nullptr, this function will also not break
5763 connections that were made using the string-based version of connect(). To
5764 break such connections, use the corresponding string-based overload of
5765 disconnect().
5766
5767 \sa connect()
5768*/
5769
5770bool QObject::disconnectImpl(const QObject *sender, void **signal, const QObject *receiver, void **slot, const QMetaObject *senderMetaObject)
5771{
5772 if (sender == nullptr || (receiver == nullptr && slot != nullptr)) {
5773 qCWarning(lcConnect, "QObject::disconnect: Unexpected nullptr parameter");
5774 return false;
5775 }
5776
5777 int signal_index = -1;
5778 if (signal) {
5779 void *args[] = { &signal_index, signal };
5780 for (; senderMetaObject && signal_index < 0; senderMetaObject = senderMetaObject->superClass()) {
5781 senderMetaObject->static_metacall(QMetaObject::IndexOfMethod, 0, args);
5782 if (signal_index >= 0 && signal_index < QMetaObjectPrivate::get(senderMetaObject)->signalCount)
5783 break;
5784 }
5785 if (!senderMetaObject) {
5786 qCWarning(lcConnect, "QObject::disconnect: signal not found in %s", sender->metaObject()->className());
5787 return false;
5788 }
5789 signal_index += QMetaObjectPrivate::signalOffset(senderMetaObject);
5790 }
5791
5792 return QMetaObjectPrivate::disconnect(sender, signal_index, senderMetaObject, receiver, -1, slot);
5793}
5794
5795/*!
5796 \internal
5797 Used by QML to connect a signal by index to a slot implemented in JavaScript
5798 (wrapped in a custom QSlotObjectBase subclass).
5799
5800 This version of connect assumes that sender and receiver are the same object.
5801
5802 The signal_index is an index relative to the number of methods.
5803 */
5804QMetaObject::Connection QObjectPrivate::connect(const QObject *sender, int signal_index, QtPrivate::QSlotObjectBase *slotObj, Qt::ConnectionType type)
5805{
5806 return QObjectPrivate::connect(sender, signal_index, sender, slotObj, type);
5807}
5808
5809/*!
5810 \internal
5811 Used by QML to connect a signal by index to a slot implemented in JavaScript
5812 (wrapped in a custom QSlotObjectBase subclass).
5813
5814 This is an overload that should be used when \a sender and \a receiver are
5815 different objects.
5816
5817 The signal_index is an index relative to the number of methods.
5818 */
5819QMetaObject::Connection QObjectPrivate::connect(const QObject *sender, int signal_index,
5820 const QObject *receiver,
5821 QtPrivate::QSlotObjectBase *slotObjRaw,
5822 Qt::ConnectionType type)
5823{
5824 QtPrivate::SlotObjUniquePtr slotObj(slotObjRaw);
5825 Q_ASSERT_X(slotObjRaw, "QObjectPrivate::connect", "Internal error, caller must not pass null slotObj");
5826 if (!sender) {
5827 connectWarning(sender, nullptr, receiver, "invalid nullptr parameter");
5828 return QMetaObject::Connection();
5829 }
5830 const QMetaObject *senderMetaObject = sender->metaObject();
5831 signal_index = methodIndexToSignalIndex(&senderMetaObject, signal_index);
5832
5833 return connectImpl(sender, signal_index, receiver, /*slot*/ nullptr, slotObj.release(),
5834 type, /*types*/ nullptr, senderMetaObject);
5835}
5836
5837/*!
5838 \internal
5839 Used by QML to disconnect a signal by index that's connected to a slot implemented in JavaScript (wrapped in a custom QSlotObjectBase subclass)
5840 In the QML case the slot is not a pointer to a pointer to the function to disconnect, but instead it is a pointer to an array of internal values
5841 required for the disconnect.
5842
5843 This version of disconnect assumes that sender and receiver are the same object.
5844 */
5845bool QObjectPrivate::disconnect(const QObject *sender, int signal_index, void **slot)
5846{
5847 return QObjectPrivate::disconnect(sender, signal_index, sender, slot);
5848}
5849
5850/*!
5851 \internal
5852
5853 Used by QML to disconnect a signal by index that's connected to a slot
5854 implemented in JavaScript (wrapped in a custom QSlotObjectBase subclass) In the
5855 QML case the slot is not a pointer to a pointer to the function to disconnect,
5856 but instead it is a pointer to an array of internal values required for the
5857 disconnect.
5858
5859 This is an overload that should be used when \a sender and \a receiver are
5860 different objects.
5861 */
5862bool QObjectPrivate::disconnect(const QObject *sender, int signal_index, const QObject *receiver,
5863 void **slot)
5864{
5865 const QMetaObject *senderMetaObject = sender->metaObject();
5866 signal_index = methodIndexToSignalIndex(&senderMetaObject, signal_index);
5867
5868 return QMetaObjectPrivate::disconnect(sender, signal_index, senderMetaObject, receiver, -1,
5869 slot);
5870}
5871
5872/*!
5873 \internal
5874 \threadsafe
5875*/
5876inline bool QObjectPrivate::removeConnection(QObjectPrivate::Connection *c)
5877{
5878 if (!c)
5879 return false;
5880 QObject *receiver = c->receiver.loadRelaxed();
5881 if (!receiver)
5882 return false;
5883
5884 QBasicMutex *senderMutex = signalSlotLock(c->sender);
5885 QBasicMutex *receiverMutex = signalSlotLock(receiver);
5886
5887 QObjectPrivate::ConnectionData *connections;
5888 {
5889 QOrderedMutexLocker locker(senderMutex, receiverMutex);
5890
5891 // load receiver once again and recheck to ensure nobody else has removed the connection in the meantime
5892 receiver = c->receiver.loadRelaxed();
5893 if (!receiver)
5894 return false;
5895
5896 connections = QObjectPrivate::get(c->sender)->connections.loadRelaxed();
5897 Q_ASSERT(connections);
5898 connections->removeConnection(c);
5899
5900 c->sender->disconnectNotify(QMetaObjectPrivate::signal(c->sender->metaObject(), c->signal_index));
5901 // We must not hold the receiver mutex, else we risk dead-locking; we also only need the sender mutex
5902 // It is however vital to hold the senderMutex before calling cleanOrphanedConnections, as otherwise
5903 // another thread might modify/delete the connection
5904 if (receiverMutex != senderMutex) {
5905 receiverMutex->unlock();
5906 }
5907 connections->cleanOrphanedConnections(c->sender, ConnectionData::AlreadyLockedAndTemporarilyReleasingLock);
5908 senderMutex->unlock(); // now both sender and receiver mutex have been manually unlocked
5909 locker.dismiss(); // so we dismiss the QOrderedMutexLocker
5910 }
5911
5912 return true;
5913}
5914
5915/*!
5916 \internal
5917
5918 Used by QPropertyAdaptorSlotObject to get an existing instance for a property, if available
5919 */
5920QtPrivate::QPropertyAdaptorSlotObject *
5921QObjectPrivate::getPropertyAdaptorSlotObject(const QMetaProperty &property)
5922{
5923 if (auto conns = connections.loadAcquire()) {
5924 Q_Q(QObject);
5925 const QMetaObject *metaObject = q->metaObject();
5926 int signal_index = methodIndexToSignalIndex(&metaObject, property.notifySignalIndex());
5927 if (signal_index >= conns->signalVectorCount())
5928 return nullptr;
5929 const auto &connectionList = conns->connectionsForSignal(signal_index);
5930 for (auto c = connectionList.first.loadRelaxed(); c;
5931 c = c->nextConnectionList.loadRelaxed()) {
5932 if (c->isSlotObject) {
5933 if (auto p = QtPrivate::QPropertyAdaptorSlotObject::cast(c->slotObj,
5934 property.propertyIndex()))
5935 return p;
5936 }
5937 }
5938 }
5939 return nullptr;
5940}
5941
5942/*! \class QMetaObject::Connection
5943 \inmodule QtCore
5944 Represents a handle to a signal-slot (or signal-functor) connection.
5945
5946 It can be used to check if the connection is valid and to disconnect it using
5947 QObject::disconnect(). For a signal-functor connection without a context object,
5948 it is the only way to selectively disconnect that connection.
5949
5950 As Connection is just a handle, the underlying signal-slot connection is unaffected
5951 when Connection is destroyed or reassigned.
5952 */
5953
5954/*!
5955 Create a copy of the handle to the \a other connection
5956 */
5957QMetaObject::Connection::Connection(const QMetaObject::Connection &other) : d_ptr(other.d_ptr)
5958{
5959 if (d_ptr)
5960 static_cast<QObjectPrivate::Connection *>(d_ptr)->ref();
5961}
5962
5963/*!
5964 Assigns \a other to this connection and returns a reference to this connection.
5965*/
5966QMetaObject::Connection &QMetaObject::Connection::operator=(const QMetaObject::Connection &other)
5967{
5968 if (other.d_ptr != d_ptr) {
5969 if (d_ptr)
5970 static_cast<QObjectPrivate::Connection *>(d_ptr)->deref();
5971 d_ptr = other.d_ptr;
5972 if (other.d_ptr)
5973 static_cast<QObjectPrivate::Connection *>(other.d_ptr)->ref();
5974 }
5975 return *this;
5976}
5977
5978/*!
5979 \fn QMetaObject::Connection::Connection();
5980
5981 Creates a Connection instance.
5982*/
5983
5984/*!
5985 Destructor for QMetaObject::Connection.
5986*/
5987QMetaObject::Connection::~Connection()
5988{
5989 if (d_ptr)
5990 static_cast<QObjectPrivate::Connection *>(d_ptr)->deref();
5991}
5992
5993/*! \internal Returns true if the object is still connected */
5994bool QMetaObject::Connection::isConnected_helper() const
5995{
5996 Q_ASSERT(d_ptr); // we're only called from operator RestrictedBool() const
5997 QObjectPrivate::Connection *c = static_cast<QObjectPrivate::Connection *>(d_ptr);
5998
5999 return c->receiver.loadRelaxed();
6000}
6001
6002
6003/*!
6004 \fn QMetaObject::Connection::operator bool() const
6005
6006 Returns \c true if the connection is valid.
6007
6008 The connection is valid if the call to QObject::connect succeeded.
6009 The connection is invalid if QObject::connect was not able to find
6010 the signal or the slot, or if the arguments do not match.
6011 */
6012
6013QT_END_NAMESPACE
6014
6015#include "moc_qobject.cpp"
Combined button and popup list for selecting options.
Q_TRACE_POINT(qtcore, QCoreApplication_postEvent_exit)
#define qCWarning(category,...)
#define qCDebug(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
static void check_and_warn_compat(const QMetaObject *sender, const QMetaMethod &signal, const QMetaObject *receiver, const QMetaMethod &method)
Definition qobject.cpp:3036
static int * queuedConnectionTypes(QSpan< const QArgumentType > argumentTypes)
Definition qobject.cpp:116
static int DIRECT_CONNECTION_ONLY
Definition qobject.cpp:67
static void disconnectNotifySender(QObject *sender, int signalIndex, Qt::HANDLE currentThreadId)
Definition qobject.cpp:166
static int methodIndexToSignalIndex(const QMetaObject **base, int signal_index)
Definition qobject.cpp:3741
QObject * qt_qFindChild_helper(const QObject *parent, QAnyStringView name, const QMetaObject &mo, Qt::FindChildOptions options)
Definition qobject.cpp:2258
static const char * extract_location(const char *member)
Definition qobject.cpp:2677
ConnectionEnd
Definition qobject.cpp:2751
Q_TRACE_POINT(qtcore, QMetaObject_activate_slot_functor_entry, void *slotObject)
static bool check_parent_thread(QObject *parent, QThreadData *parentThreadData, QThreadData *currentThreadData)
Definition qobject.cpp:972
static int * queuedConnectionTypes(const QMetaMethod &method)
Definition qobject.cpp:87
static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int *methodOffset)
Definition qobject.cpp:251
static QBasicMutex * signalSlotLock(const QObject *o)
Definition qobject.cpp:148
static Q_DECL_COLD_FUNCTION void err_method_notfound(const QObject *object, const char *method, const char *func)
Definition qobject.cpp:2733
static Q_DECL_COLD_FUNCTION void connectWarning(const QObject *sender, const QMetaObject *senderMetaObject, const QObject *receiver, const char *message)
Definition qobject.cpp:2777
static bool check_method_code(int code, const QObject *object, const char *method, const char *func)
Definition qobject.cpp:2704
static Q_DECL_COLD_FUNCTION void err_info_about_object(const char *func, const QObject *o, ConnectionEnd end)
Definition qobject.cpp:2753
void qt_register_signal_spy_callbacks(QSignalSpyCallbackSet *callback_set)
Definition qobject.cpp:74
static bool matches_objectName_non_null(QObject *obj, QAnyStringView name)
Definition qobject.cpp:2211
Q_TRACE_POINT(qtcore, QObject_dtor, QObject *object)
Q_TRACE_POINT(qtcore, QMetaObject_activate_entry, QObject *sender, int signalIndex)
static int extract_code(const char *member)
Definition qobject.cpp:2671
static bool check_signal_macro(const QObject *sender, const char *signal, const char *func, const char *op)
Definition qobject.cpp:2688
static Q_DECL_COLD_FUNCTION void err_info_about_objects(const char *func, const QObject *sender, const QObject *receiver)
Definition qobject.cpp:2770
Q_CORE_EXPORT void qt_qFindChildren_helper(const QObject *parent, QAnyStringView name, const QMetaObject &mo, QList< void * > *list, Qt::FindChildOptions options)
Definition qobject.cpp:2221
Q_CORE_EXPORT const char * qFlagLocation(const char *method)
Definition qobject.cpp:2665
SlotObjectGuard()=default