Qt 4.8
Public Slots | Signals | Public Functions | Static Public Functions | Static Public Variables | Protected Functions | Protected Variables | Static Protected Variables | Properties | Friends | Related Functions | List of all members
QObject Class Reference

The QObject class is the base class of all Qt objects. More...

#include <qobject.h>

Inheritance diagram for QObject:
_IapAddTimer ActiveObject AVAudioOutput AVBackend AVMediaObject Maemo::DBusDispatcher Maemo::Icd ModelObject QAbstractAnimation QAbstractAudioDeviceInfo QAbstractAudioInput QAbstractAudioOutput QAbstractEventDispatcher QAbstractFontEngine QAbstractHostInfoLookupManager QAbstractItemDelegate QAbstractItemModel QAbstractMessageHandler QAbstractNetworkCache QAbstractScrollAreaFilter QAbstractSocketEngine QAbstractState QAbstractTextDocumentLayout QAbstractTransition QAbstractUriResolver QAbstractVideoSurface QAccessibleBridgePlugin QAccessibleHierarchyManager QAccessiblePlugin QACConnectionObject QAction QActionGroup QAhiScreenPrivate QAnimationDriver QAuBucketQWS QAudioEnginePlugin QAudioInput QAudioOutput QAuServer QAxFactory QAxObject QAxScript QAxScriptManager QAxServerBase QBBAbstractVirtualKeyboard QBBBpsEventFilter QBBButtonEventNotifier QBBNavigatorEventHandler QBBNavigatorEventNotifier QBBScreenEventHandler QBBSystemLocaleData QBearerEngine QBearerEnginePlugin QButtonGroup QCalendarTextNavigator QClipboard QCompleter QConnmanDBusHelper QCopChannel QCoreApplication QCoreFuriCuri QDataWidgetMapper QDBusAbstractAdaptor QDBusAbstractInterface QDBusAbstractInterfaceBase QDBusAdaptorConnector QDBusConnectionConstructor QDBusConnectionPrivate QDBusPendingCallWatcher QDBusPendingCallWatcherHelper QDBusServer QDBusServiceWatcher QDBusVirtualObject QDeclarativeAbstractAnimation QDeclarativeAbstractBoundSignal QDeclarativeAnchors QDeclarativeAnchorSet QDeclarativeApplication QDeclarativeBehavior QDeclarativeBind QDeclarativeBoundSignalParameters QDeclarativeCompiledBindings QDeclarativeComponent QDeclarativeComponentAttached QDeclarativeConnections QDeclarativeContents QDeclarativeContext QDeclarativeDataLoader QDeclarativeDebugClient QDeclarativeDebugConnectionPrivate QDeclarativeDebugQuery QDeclarativeDebugServer QDeclarativeDebugService QDeclarativeDebugWatch QDeclarativeDrag QDeclarativeEngine QDeclarativeEngineDebug QDeclarativeExpression QDeclarativeExtensionPlugin QDeclarativeFlickableVisibleArea QDeclarativeFontLoader QDeclarativeFontObject QDeclarativeGradient QDeclarativeGradientStop QDeclarativeGraphics_DerivedObject QDeclarativeGraphicsWidget QDeclarativeGridViewAttached QDeclarativeInclude QDeclarativeKeyEvent QDeclarativeKeyNavigationAttached QDeclarativeKeysAttached QDeclarativeLayoutMirroringAttached QDeclarativeListElement QDeclarativeListModelWorkerAgent QDeclarativeListViewAttached QDeclarativeMouseEvent QDeclarativePackage QDeclarativePackageAttached QDeclarativeParticleMotion QDeclarativePath QDeclarativePathElement QDeclarativePathViewAttached QDeclarativePen QDeclarativePinch QDeclarativePinchEvent QDeclarativePixmapReaderThreadObject QDeclarativePixmapReply QDeclarativePixmapStore QDeclarativePropertyMap QDeclarativeScaleGrid QDeclarativeState QDeclarativeStateGroup QDeclarativeStateOperation QDeclarativeSystemPalette QDeclarativeTimer QDeclarativeTransition QDeclarativeTypeNotAvailable QDeclarativeValueType QDeclarativeViewSection QDeclarativeVisualDataModelData QDeclarativeVisualDataModelParts QDeclarativeVisualItemModelAttached QDeclarativeVisualModel QDeclarativeWatcher QDeclarativeWatchProxy QDeclarativeWorkerScript QDeclarativeWorkerScriptEnginePrivate QDeclarativeXMLHttpRequest QDeclarativeXmlListModelRole QDeclarativeXmlQueryThreadObject QDecorationPlugin QDeferredGraphicsSystemChange QDeviceClosedNotifier QDirectFBKeyboardHandlerPrivate QDirectFBMouseHandlerPrivate QDirectFBScreenPrivate QDirectPainter QDrag QDragManager QEventLoop QFactoryLoader QFileSystemWatcher QFontCache QFontEngine QFontEnginePlugin QFtp QFtpDTP QFtpPI QFutureWatcherBase QGenericPlugin QGesture QGestureManager QGLBlurTextureCache QGLEngineShaderManager QGLGlyphCache QGLGradientCache QGLOffscreen QGLPrivateCleanup QGLProgramCache QGLShader QGLShaderProgram QGLSignalProxy QGLTextureDestroyer QGLWindowSurface QGraphicsAnchor QGraphicsEffect QGraphicsEffectSource QGraphicsItemAnimation QGraphicsObject QGraphicsScene QGraphicsSceneIndex QGraphicsSystemPlugin QGraphicsTransform QGtkStyleFilter QGtkStyleUpdateScheduler QGuiPlatformPlugin QHostInfoAgent QHostInfoResult QHttp QHttpMultiPart QHttpNetworkConnection QHttpNetworkConnectionChannel QHttpNetworkReply QHttpThreadDelegate QIconEnginePlugin QIconEnginePluginV2 QIconLoader QImageIOPlugin QInputContext QInputContextPlugin QIntMouseHandler QIntMousePrivate QIODevice QItemSelectionModel QJSDebuggerAgent QKbdDriverPlugin QKeyMapper QLayout QLibrary QLineControl QLinuxFbScreenPrivate QLinuxInputKeyboardHandler QLinuxInputMouseHandler QListModelInterface QLocalServer QMacAnimateCursor QMacStylePrivate QMdi::ControlContainer QMeeGoGraphicsSystemSwitchHandler QMimeData QmlJSDebugger::AbstractTool QmlJSDebugger::AbstractViewInspector QmlJSDebugger::BoundingBox QmlJSDebugger::InspectorProtocol QmlJSDebugger::QDeclarativeInspectorPlugin QmlJSDebugger::QDeclarativeViewInspectorPrivate QmlOstPlugin QMouseDriverPlugin QMovie QMYSQLResultPrivate QNetworkAccessBackend QNetworkAccessCache QNetworkAccessManager QNetworkConfigurationManager QNetworkConfigurationManagerPrivate QNetworkCookieJar QNetworkManagerConnectionActive QNetworkManagerInterface QNetworkManagerInterfaceAccessPoint QNetworkManagerInterfaceDevice QNetworkManagerInterfaceDeviceWired QNetworkManagerInterfaceDeviceWireless QNetworkManagerIp4Config QNetworkManagerSettings QNetworkManagerSettingsConnection QNetworkSession QNetworkSessionManagerPrivate QNetworkSessionPrivate QNmDBusHelper QNonContiguousByteDevice QObjectCleanupHandler QOfonoDBusHelper QOpenUrlHandlerRegistry QPacketProtocol QPacketProtocolPrivate QPaintBufferResource QPaintBufferSignalProxy QPatternist::NetworkAccessDelegator QPictureFormatPlugin QPixmapFilter QPlatformCursor QPlatformIntegrationPlugin QPlatformScreen QPluginLoader QPMCache QQnxMouseHandler QScreenDriverPlugin QScript::QObjectConnectionManager QScript::QObjectNotifyCaller QScript::QObjectPrototypeObject QScript::StaticQtMetaObject QScriptCompletionTaskInterface QScriptDBusConnection QScriptDBusInterfaceConstructor QScriptDBusMessageConstructor QScriptDebugger QScriptDebuggerBackendEventReceiver QScriptDebuggerConsoleGlobalObject QScriptDebuggerFrontendEventReceiver QScriptDebuggerStandardWidgetFactory QScriptEngine QScriptEngineDebugger QScriptExtensionPlugin QSessionManager QSettings QSharedMemory QShortcut QSignalEventGenerator QSignalMapper QSignalSpy QSingleShotTimer QSmSocketReceiver QSocketNotifier QSocks5BindStore QSoftKeyManager QSound QSqlDriver QSqlDriverPlugin QStyle QStylePlugin QStyleSheetStyleCaches QSvgRenderer QSyntaxHighlighter QSystemTrayIcon QTcpServer QTcpServerConnection QTestEventLoop QTextCodecPlugin QTextControl QTextDocument QTextImageHandler QTextObject QThread QThreadPool QTimeLine QTimer QtMultimediaInternal::QAudioInputBuffer QtMultimediaInternal::QAudioOutputBuffer QTranslator QTransportAuth QTsLibMouseHandler QUIKitSoftwareInputHandler QUndoGroup QUndoStack QUnifiedTimer QUnixSocketPrivate QUnixSocketServer QUnixSocketServerPrivate QValidator QVFbKeyboardHandler QVFbMouseHandler QVFbScreenKeyboardHandler QVFbScreenMouseHandler QVGFontEngineCleaner QVistaHelper QVNCScreenPrivate QVNCScreenPrivate QVNCServer QVNCServer QWaylandClipboardSignalEmitter QWaylandDisplay QWhatsThisPrivate QWidget QWidgetAnimator QWidgetResizeHandler QWinEventNotifier QWSClient QWSInputMethod QWSIntKbPrivate QWSKbPrivate QWSLinuxInputKbPrivate QWSLinuxInputMousePrivate QWSLinuxTPMouseHandlerPrivate QWSPcMouseHandlerPrivate QWSQnxKeyboardHandler QWSServer QWSServerSignalBridge QWSSoundServerClient QWSSoundServerPrivate QWSTslibMouseHandlerPrivate QWSTtyKbPrivate QWSUmKeyboardHandlerPrivate QXcbConnection StaticQtMetaObject StaticQtMetaObject SxeRegistryLocker

Public Slots

void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Static Public Variables

static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 

Protected Functions

virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Protected Variables

QScopedPointer< QObjectDatad_ptr
 

Static Protected Variables

static const QMetaObject staticQtMetaObject
 

Properties

QString objectName
 the name of this object More...
 

Friends

class QApplication
 
class QApplicationPrivate
 
class QCoreApplication
 
class QCoreApplicationPrivate
 
struct QMetaObject
 
class QThreadData
 
class QWidget
 

Related Functions

(Note that these are not member functions.)

qFindChildqFindChildren (const QObject *obj, const QString &name)()
 
QList< T > qFindChildrenqFindChildren (const QObject *obj, const QString &name)()
 
QList< T > qFindChildrenqFindChildren (const QObject *obj, const QRegExp &regExp)()
 
T * qobject_cast (QObject *object)
 
 QObjectList
 
void * qt_find_obj_child (QObject *parent, const char *type, const QString &name)
 Returns a pointer to the object named name that inherits type and with a given parent. More...
 

Detailed Description

The QObject class is the base class of all Qt objects.

Note
This class or function is reentrant.

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect(). To avoid never ending notification loops you can temporarily block signals with blockSignals(). The protected functions connectNotify() and disconnectNotify() make it possible to track connections.

QObjects organize themselves in Object Trees & Ownership {object trees}. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().

Every object has an objectName() and its class name can be found via the corresponding metaObject() (see QMetaObject::className()). You can determine whether the object's class inherits another class in the QObject inheritance hierarchy by using the inherits() function.

When an object is deleted, it emits a destroyed() signal. You can catch this signal to avoid dangling references to QObjects.

QObjects can receive events through event() and filter the events of other objects. See installEventFilter() and eventFilter() for details. A convenience handler, childEvent(), can be reimplemented to catch child events.

Last but not least, QObject provides the basic timer support in Qt; see QTimer for high-level support for timers.

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

All Qt widgets inherit QObject. The convenience function isWidgetType() returns whether an object is actually a widget. It is much faster than qobject_cast<QWidget *>(obj) or obj->inherits("QWidget").

Some QObject functions, e.g. children(), return a QObjectList. QObjectList is a typedef for QList<QObject *>.

Thread Affinity

A QObject instance is said to have a thread affinity, or that it lives in a certain thread. When a QObject receives a queued signal or a The Event System::Sending Events{posted event}, the slot or event handler will run in the thread that the object lives in.

Note
If a QObject has no thread affinity (that is, if thread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.

By default, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread() and changed using moveToThread().

All QObjects must live in the same thread as their parent. Consequently:

setParent() will fail if the two QObjects involved live in different threads.

Note
A QObject's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor, or by calling setParent(). Without this step, the object's member variables will remain in the old thread when moveToThread() is called.

No copy constructor or assignment operator

QObject has neither a copy constructor nor an assignment operator. This is by design. Actually, they are declared, but in a private section with the macro Q_DISABLE_COPY(). In fact, all Qt classes derived from QObject (direct or indirect) use this macro to declare their copy constructor and assignment operator to be private. The reasoning is found in the discussion on Identity vs Value {Identity vs Value} on the Qt Object Model page.

The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers.

Auto-Connection

Qt's meta-object system provides a mechanism to automatically connect signals and slots between QObject subclasses and their children. As long as objects are defined with suitable object names, and slots follow a simple naming convention, this connection can be performed at run-time by the QMetaObject::connectSlotsByName() function.

uic generates code that invokes this function to enable auto-connection to be performed between widgets on forms created with . More information about using auto-connection with is given in the Using a Designer UI File in Your Application section of the manual.

Dynamic Properties

From Qt 4.2, dynamic properties can be added to and removed from QObject instances at run-time. Dynamic properties do not need to be declared at compile-time, yet they provide the same advantages as static properties and are manipulated using the same API - using property() to read them and setProperty() to write them.

From Qt 4.3, dynamic properties are supported by Qt Designer's Widget Editing Mode::The Property Editor{Qt Designer}, and both standard Qt widgets and user-created forms can be given dynamic properties.

(i18n)

Internationalization (i18n)

All QObject subclasses support Qt's translation features, making it possible to translate an application's user interface into different languages.

To make user-visible text translatable, it must be wrapped in calls to the tr() function. This is explained in detail in the Writing Source Code for Translation document.

See also
QMetaObject, QPointer, QObjectCleanupHandler, Q_DISABLE_COPY()
{Object Trees & Ownership}

Definition at line 111 of file qobject.h.

Constructors and Destructors

◆ QObject() [1/2]

QObject::QObject ( QObject parent = 0)
explicit

Constructs an object with parent object parent.

The parent of an object may be viewed as the object's owner. For instance, a dialog box is the parent of the OK and Cancel buttons it contains.

The destructor of a parent object destroys all child objects.

Setting parent to 0 constructs an object with no parent. If the object is a widget, it will become a top-level window.

See also
parent(), findChild(), findChildren()

Definition at line 753 of file qobject.cpp.

Referenced by connManager(), QThread::priority(), QCopChannel::QCopChannel(), QCoreApplication::QCoreApplication(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeXmlQueryEngine::QDeclarativeXmlQueryEngine(), QFtp::QFtp(), QHttpNetworkConnection::QHttpNetworkConnection(), QSignalMapper::QSignalMapper(), QSocketNotifier::QSocketNotifier(), QSound::QSound(), QTimer::QTimer(), QTranslator::QTranslator(), QValidator::QValidator(), QWidget::QWidget(), QWSServer::QWSServer(), and QAction::setFont().

754  : d_ptr(new QObjectPrivate)
755 {
756  Q_D(QObject);
757  d_ptr->q_ptr = this;
758  d->threadData = (parent && !parent->thread()) ? parent->d_func()->threadData : QThreadData::current();
759  d->threadData->ref();
760  if (parent) {
761  QT_TRY {
762  if (!check_parent_thread(parent, parent ? parent->d_func()->threadData : 0, d->threadData))
763  parent = 0;
764  setParent(parent);
765  } QT_CATCH(...) {
766  d->threadData->deref();
767  QT_RETHROW;
768  }
769  }
770  qt_addObject(this);
771 }
double d
Definition: qnumeric_p.h:62
Q_CORE_EXPORT void qt_addObject(QObject *)
Definition: qobject.cpp:114
QObject * q_ptr
Definition: qobject.h:91
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
void setParent(QObject *)
Makes the object a child of parent.
Definition: qobject.cpp:1950
#define QT_RETHROW
Definition: qglobal.h:1539
#define QT_CATCH(A)
Definition: qglobal.h:1537
static bool check_parent_thread(QObject *parent, QThreadData *parentThreadData, QThreadData *currentThreadData)
Definition: qobject.cpp:718
static QThreadData * current()
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320
QThread * thread() const
Returns the thread in which the object lives.
Definition: qobject.cpp:1419
#define QT_TRY
Definition: qglobal.h:1536

◆ ~QObject()

QObject::~QObject ( )
virtual

Destroys the object, deleting all its child objects.

All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly.

Warning
All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash. We do not recommend holding pointers to child objects from outside the parent. If you still do, the destroyed() signal gives you an opportunity to detect when an object is destroyed.
Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.
See also
deleteLater()

Definition at line 853 of file qobject.cpp.

854 {
855  Q_D(QObject);
856  d->wasDeleted = true;
857  d->blockSig = 0; // unblock signals so we always emit destroyed()
858 
859  if (d->hasGuards && !d->isWidget) {
860  // set all QPointers for this object to zero - note that
861  // ~QWidget() does this for us, so we don't have to do it twice
863  }
864 
865  if (d->sharedRefcount) {
866  if (d->sharedRefcount->strongref > 0) {
867  qWarning("QObject: shared QObject was deleted directly. The program is malformed and may crash.");
868  // but continue deleting, it's too late to stop anyway
869  }
870 
871  // indicate to all QWeakPointers that this QObject has now been deleted
872  d->sharedRefcount->strongref = 0;
873  if (!d->sharedRefcount->weakref.deref())
874  delete d->sharedRefcount;
875  }
876 
877 
878  if (d->isSignalConnected(0)) {
879  QT_TRY {
880  emit destroyed(this);
881  } QT_CATCH(...) {
882  // all the signal/slots connections are still in place - if we don't
883  // quit now, we will crash pretty soon.
884  qWarning("Detected an unexpected exception in ~QObject while emitting destroyed().");
885  QT_RETHROW;
886  }
887  }
888 
889  if (d->declarativeData)
890  QAbstractDeclarativeData::destroyed(d->declarativeData, this);
891 
892  // set ref to zero to indicate that this object has been deleted
893  if (d->currentSender != 0)
894  d->currentSender->ref = 0;
895  d->currentSender = 0;
896 
897  if (d->connectionLists || d->senders) {
898  QMutex *signalSlotMutex = signalSlotLock(this);
899  QMutexLocker locker(signalSlotMutex);
900 
901  // disconnect all receivers
902  if (d->connectionLists) {
903  ++d->connectionLists->inUse;
904  int connectionListsCount = d->connectionLists->count();
905  for (int signal = -1; signal < connectionListsCount; ++signal) {
906  QObjectPrivate::ConnectionList &connectionList =
907  (*d->connectionLists)[signal];
908 
909  while (QObjectPrivate::Connection *c = connectionList.first) {
910  if (!c->receiver) {
911  connectionList.first = c->nextConnectionList;
912  delete c;
913  continue;
914  }
915 
916  QMutex *m = signalSlotLock(c->receiver);
917  bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
918 
919  if (c->receiver) {
920  *c->prev = c->next;
921  if (c->next) c->next->prev = c->prev;
922  }
923  if (needToUnlock)
924  m->unlockInline();
925 
926  connectionList.first = c->nextConnectionList;
927  delete c;
928  }
929  }
930 
931  if (!--d->connectionLists->inUse) {
932  delete d->connectionLists;
933  } else {
934  d->connectionLists->orphaned = true;
935  }
936  d->connectionLists = 0;
937  }
938 
939  // disconnect all senders
940  QObjectPrivate::Connection *node = d->senders;
941  while (node) {
942  QObject *sender = node->sender;
943  QMutex *m = signalSlotLock(sender);
944  node->prev = &node;
945  bool needToUnlock = QOrderedMutexLocker::relock(signalSlotMutex, m);
946  //the node has maybe been removed while the mutex was unlocked in relock?
947  if (!node || node->sender != sender) {
948  m->unlockInline();
949  continue;
950  }
951  node->receiver = 0;
952  QObjectConnectionListVector *senderLists = sender->d_func()->connectionLists;
953  if (senderLists)
954  senderLists->dirty = true;
955 
956  node = node->next;
957  if (needToUnlock)
958  m->unlockInline();
959  }
960  }
961 
962  if (!d->children.isEmpty())
963  d->deleteChildren();
964 
965  qt_removeObject(this);
966 
967  if (d->parent) // remove it from parent object
968  d->setParent_helper(0);
969 
970 #ifdef QT_JAMBI_BUILD
971  if (d->inEventHandler) {
972  qWarning("QObject: Do not delete object, '%s', during its event handler!",
973  objectName().isNull() ? "unnamed" : qPrintable(objectName()));
974  }
975 #endif
976 }
static void clearGuards(QObject *)
Definition: qobject.cpp:467
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
The QMutex class provides access serialization between threads.
Definition: qmutex.h:60
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
QObject * sender() const
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; othe...
Definition: qobject.cpp:2327
#define QT_RETHROW
Definition: qglobal.h:1539
void destroyed(QObject *=0)
This signal is emitted immediately before the object obj is destroyed, and can not be blocked...
void unlockInline()
Definition: qmutex.h:196
#define emit
Definition: qobjectdefs.h:76
Q_CORE_EXPORT void qWarning(const char *,...)
#define QT_CATCH(A)
Definition: qglobal.h:1537
Q_CORE_EXPORT void qt_removeObject(QObject *)
Definition: qobject.cpp:119
static QMutex * signalSlotLock(const QObject *o)
Definition: qobject.cpp:103
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
static void(* destroyed)(QAbstractDeclarativeData *, QObject *)
Definition: qobject_p.h:93
QString objectName() const
#define qPrintable(string)
Definition: qglobal.h:1750
#define QT_TRY
Definition: qglobal.h:1536
static bool isNull(const QVariant::Private *d)
Definition: qvariant.cpp:300

◆ QObject() [2/2]

QObject::QObject ( QObjectPrivate dd,
QObject parent = 0 
)
protected
Warning
This function is not part of the public interface.

Definition at line 801 of file qobject.cpp.

802  : d_ptr(&dd)
803 {
804  Q_D(QObject);
805  d_ptr->q_ptr = this;
806  d->threadData = (parent && !parent->thread()) ? parent->d_func()->threadData : QThreadData::current();
807  d->threadData->ref();
808  if (parent) {
809  QT_TRY {
810  if (!check_parent_thread(parent, parent ? parent->d_func()->threadData : 0, d->threadData))
811  parent = 0;
812  if (d->isWidget) {
813  if (parent) {
814  d->parent = parent;
815  d->parent->d_func()->children.append(this);
816  }
817  // no events sent here, this is done at the end of the QWidget constructor
818  } else {
819  setParent(parent);
820  }
821  } QT_CATCH(...) {
822  d->threadData->deref();
823  QT_RETHROW;
824  }
825  }
826  qt_addObject(this);
827 }
double d
Definition: qnumeric_p.h:62
Q_CORE_EXPORT void qt_addObject(QObject *)
Definition: qobject.cpp:114
QObject * q_ptr
Definition: qobject.h:91
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
void setParent(QObject *)
Makes the object a child of parent.
Definition: qobject.cpp:1950
#define QT_RETHROW
Definition: qglobal.h:1539
#define QT_CATCH(A)
Definition: qglobal.h:1537
QObject * parent() const
Returns a pointer to the parent object.
Definition: qobject.h:273
static bool check_parent_thread(QObject *parent, QThreadData *parentThreadData, QThreadData *currentThreadData)
Definition: qobject.cpp:718
static QThreadData * current()
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320
QThread * thread() const
Returns the thread in which the object lives.
Definition: qobject.cpp:1419
#define QT_TRY
Definition: qglobal.h:1536

Functions

◆ blockSignals()

bool QObject::blockSignals ( bool  block)

If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).

If block is false, no such blocking will occur.

The return value is the previous value of signalsBlocked().

Note that the destroyed() signal will be emitted even if the signals for this object have been blocked.

See also
signalsBlocked()

Definition at line 1406 of file qobject.cpp.

Referenced by QPlainTextEditPrivate::_q_adjustScrollbars(), QAbstractSpinBoxPrivate::_q_editorCursorPositionChanged(), QHttpPrivate::_q_slotError(), QHttpPrivate::_q_slotReadyRead(), QHttpPrivate::_q_slotSendRequest(), QTabWidgetPrivate::_q_tabMoved(), QFontComboBoxPrivate::_q_updateModel(), QWorkspace::cascade(), QDateTimeEditPrivate::clearSection(), QMenuPrivate::hideMenu(), isProcessBeingDebugged(), operator>>(), QDataStream::QDataStream(), QSocks5SocketEnginePrivate::reauthenticate(), QTreeModel::removeRows(), QItemSelectionModel::reset(), QColSpinBox::setValue(), QDateTimeEditPrivate::syncCalendarWidget(), QWorkspace::tile(), QMdiAreaPrivate::updateActiveWindow(), QDateTimeEditPrivate::updateEdit(), QAbstractSpinBoxPrivate::updateEdit(), QDockAreaLayoutInfo::updateTabBar(), and QTextStreamPrivate::~QTextStreamPrivate().

1407 {
1408  Q_D(QObject);
1409  bool previous = d->blockSig;
1410  d->blockSig = block;
1411  return previous;
1412 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

◆ childEvent()

void QObject::childEvent ( QChildEvent )
protectedvirtual

This event handler can be reimplemented in a subclass to receive child events.

The event is passed in the event parameter.

QEvent::ChildAdded and QEvent::ChildRemoved events are sent to objects when children are added or removed. In both cases you can only rely on the child being a QObject, or if isWidgetType() returns true, a QWidget. (This is because, in the ChildAdded case, the child is not yet fully constructed, and in the ChildRemoved case it might have been destructed already).

QEvent::ChildPolished events are sent to widgets when children are polished, or when polished children are added. If you receive a child polished event, the child's construction is usually completed. However, this is not guaranteed, and multiple polish events may be delivered during the execution of a widget's constructor.

For every child widget, you receive one ChildAdded event, zero or more ChildPolished events, and one ChildRemoved event.

The ChildPolished event is omitted if a child is removed immediately after it is added. If a child is polished several times during construction and destruction, you may receive several child polished events for the same child, each time with a different virtual table.

See also
event()

Reimplemented in QWorkspaceChild, QLayout, QMdiArea, QToolBar, QMdiSubWindow, QSplitter, QWorkspace, and QGroupBox.

Definition at line 1332 of file qobject.cpp.

Referenced by QToolBar::childEvent(), QAnimationGroup::event(), event(), and QToolBar::isAreaAllowed().

1333 {
1334 }

◆ children()

const QObjectList & QObject::children ( ) const
inline

Returns a list of child objects.

The QObjectList class is defined in the <QObject> header file as the following:

src/corelib/kernel/qobject.h /typedef .*QObjectList/ QObjectList

The first child added is the first object in the list and the last child added is the last object in the list, i.e. new children are appended at the end.

Note that the list order changes when QWidget children are raised or lowered. A widget that is raised becomes the last object in the list, and a widget that is lowered becomes the first object in the list.

See also
findChild(), findChildren(), parent(), setParent()

Definition at line 197 of file qobject.h.

Referenced by QWidgetPrivate::activateChildLayoutsRecursively(), boundingRectOfFloatsInSelection(), buddyString(), QDeclarativeEngineDebugService::buildObjectDump(), QDeclarativeEngineDebugService::buildStatesList(), QDeclarativeContents::calcHeight(), QDeclarativeContents::calcWidth(), QDeclarativeItem::childAt(), QWidgetPrivate::childAt_helper(), QWidgetPrivate::childAtRecursiveHelper(), QGraphicsItemPrivate::children_at(), children_at_helper(), QGraphicsItemPrivate::childrenList(), QStatePrivate::childStates(), childWidgets(), QDeclarativeContents::complete(), QWidgetPrivate::createRecursively(), QDeclarativeFlickablePrivate::data_at(), QDeclarativeFlickablePrivate::data_clear(), QDeclarativeFlickablePrivate::data_count(), QTreeView::drawBranches(), QWidgetPrivate::drawWidget(), QWidget::ensurePolished(), QDockWidget::event(), find_child(), findChildObject(), findChildrenHelper(), findMenuBar(), QWidgetPrivate::getOpaqueChildren(), QWidgetPrivate::hideChildren(), QStatePrivate::historyStates(), QTreeModel::insertColumns(), QAxServerBase::internalCreate(), QMdiAreaPrivate::internalRaise(), killTimer(), QTreeViewPrivate::layout(), QWidget::lower(), make_win_eventUPP(), markFrames(), QDirModel::parent(), QDBusAdaptorConnector::polish(), QDeclarativeEngineDebugService::prepareDeferredObjects(), QDeclarativeBasePositioner::prePositioning(), QWidgetPrivate::propagatePaletteChange(), q_createNativeChildrenAndSetParent(), qDBusFindAdaptorConnector(), QObject(), QScript::qobjectProtoFuncFindChildren(), qt_find_obj_child(), qt_qFindChild_helper(), qt_qFindChildren_helper(), qt_set_windows_updateScrollBar(), qt_x11_recreateNativeWidgetsRecursive(), QWidget::raise(), QAccessibleGroupBox::relationTo(), QFileSystemModel::remove(), QStyleSheetStyle::repolish(), QDeclarativeItemPrivate::resources_at(), QDeclarativeItemPrivate::resources_clear(), QDeclarativeItemPrivate::resources_count(), QDeclarativeParentChange::saveCurrentValues(), QWidget::scroll(), QWidgetPrivate::sendPendingMoveAndResizeEvents(), sendResizeEvents(), QWidgetPrivate::setEnabled_helper(), QDeclarativeItemPrivate::setImplicitLayoutMirror(), QWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLocale_helper(), QWidgetResizeHandler::setMouseCursor(), setObjectName(), QObjectPrivate::setParent_helper(), QDeclarativePropertyPrivate::setSignalExpression(), QLocalSocket::setSocketDescriptor(), QWidgetPrivate::setStyle_helper(), QWidgetPrivate::setUpdatesEnabled_helper(), QDeclarativeVisualItemModel::setWatchedRoles(), QWidgetPrivate::setWindowIcon_helper(), QWidgetPrivate::showChildren(), QDeclarativePropertyPrivate::signalExpression(), QWidget::stackUnder(), QStateMachinePrivate::stateEntryLessThan(), QStateMachinePrivate::stateExitLessThan(), QWidgetBackingStore::staticContents(), QWidgetPrivate::subtractOpaqueChildren(), QWidgetPrivate::subtractOpaqueSiblings(), QMdiAreaPrivate::subWindowList(), QStatePrivate::transitions(), QWidgetBackingStoreTracker::unregisterWidgetSubtree(), QWidgetPrivate::updateFont(), QWidgetBackingStore::updateLists(), QWorkspace::windowList(), QDeclarativeContents::~QDeclarativeContents(), and QSingleDesktopWidget::~QSingleDesktopWidget().

197 { return d_ptr->children; }
QObjectList children
Definition: qobject.h:93
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320

◆ connect() [1/3]

bool QObject::connect ( const QObject sender,
const char *  signal,
const QObject receiver,
const char *  method,
Qt::ConnectionType  type = Qt::AutoConnection 
)
static

Creates a connection of the given type from the signal in the sender object to the method in the receiver object.

Note
This class or function is threadsafe.

Returns true if the connection succeeds; otherwise returns false.

You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:

QLabel *label = new QLabel;
QScrollBar *scrollBar = new QScrollBar;
QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
label, SLOT(setNum(int)));

This example ensures that the label always displays the current scroll bar value. Note that the signal and slots parameters must not contain any variable names, only the type. E.g. the following would not work and return false:

// WRONG
QObject::connect(scrollBar, SIGNAL(valueChanged(int value)),
label, SLOT(setNum(int value)));

A signal can also be connected to another signal:

class MyWidget : public QWidget
{
public:
MyWidget();
void buttonClicked();
private:
QPushButton *myButton;
};
MyWidget::MyWidget()
{
myButton = new QPushButton(this);
connect(myButton, SIGNAL(clicked()),
this, SIGNAL(buttonClicked()));
}

In this example, the MyWidget constructor relays a signal from a private member variable, and makes it available under a name that relates to MyWidget.

A signal can be connected to many slots and signals. Many signals can be connected to one slot.

If a signal is connected to several slots, the slots are activated in the same order as the order the connection was made, when the signal is emitted.

The function returns true if it successfully connects the signal to the slot. It will return false if it cannot create the connection, for example, if QObject is unable to verify the existence of either signal or method, or if their signatures aren't compatible.

By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return false.

The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message

QObject::connect: Cannot queue arguments of type 'MyType'
(Make sure 'MyType' is registered using qRegisterMetaType().)

call qRegisterMetaType() to register the data type before you establish the connection.

See also
disconnect(), sender(), qRegisterMetaType(), Q_DECLARE_METATYPE()

Definition at line 2580 of file qobject.cpp.

Referenced by QNetworkReplyImplPrivate::_q_bufferOutgoingData(), QAbstractSocketPrivate::_q_connectToNextAddress(), QTextControlPrivate::_q_documentLayoutChanged(), QGraphicsScenePrivate::_q_emitUpdated(), QWSServerPrivate::_q_newConnection(), QScriptDebuggerLocalsWidgetPrivate::_q_onCompletionTaskFinished(), QNetworkReplyImplPrivate::_q_startOperation(), QDeclarativeItemPrivate::_states(), QmlJSDebugger::AbstractViewInspector::AbstractViewInspector(), QToolButton::actionEvent(), QMenuBar::actionEvent(), QMenu::actionEvent(), QNetworkManagerInterface::activateConnection(), QObjectCleanupHandler::add(), _IapAddTimer::add(), QDBusPendingCallWatcherHelper::add(), QActionGroup::addAction(), QMenuBar::addAction(), QMenu::addAction(), QToolBar::addAction(), QDialogButtonBoxPrivate::addButton(), QDeclarativeAnchorsPrivate::addDepend(), QJSDebugService::addEngine(), QWizardPrivate::addField(), QPrintPropertiesDialog::addItemToOptions(), QAxScriptManager::addObject(), QWindowsFileSystemWatcherEngine::addPaths(), QConnmanEngine::addServiceConfiguration(), QGLShaderProgram::addShader(), QMainWindow::addToolBar(), QWorkspace::addWindow(), QApplication::alert(), QWidgetAnimator::animate(), QCopChannel::answer(), QMdiAreaPrivate::appendChild(), QStateMachinePrivate::applyProperties(), QDeclarativeXmlListModel::classBegin(), QScriptDebugger::clearConsoleAction(), QScriptDebugger::clearDebugOutputAction(), QScriptDebugger::clearErrorLogAction(), QScriptDebuggerLocalsWidgetPrivate::complete(), QDeclarativePath::componentComplete(), QBBVirtualKeyboardPps::connect(), QUnixSocket::connect(), QWizardPrivate::connectButton(), QDeclarativePixmap::connectDownloadProgress(), QDeclarativePixmap::connectFinished(), QOfonoManagerInterface::connectNotify(), QConnmanManagerInterface::connectNotify(), QOfonoModemInterface::connectNotify(), QOfonoNetworkRegistrationInterface::connectNotify(), QOfonoNetworkOperatorInterface::connectNotify(), QConnmanServiceInterface::connectNotify(), QOfonoSimInterface::connectNotify(), QConnmanTechnologyInterface::connectNotify(), QOfonoDataConnectionManagerInterface::connectNotify(), QOfonoPrimaryDataContextInterface::connectNotify(), QOfonoSmsInterface::connectNotify(), QDeclarativeProperty::connectNotifySignal(), ShaderEffectItem::connectPropertySignals(), QDBusConnectionPrivate::connectSignal(), QFtpDTP::connectToHost(), QProxyModel::connectToModel(), QAnimationGroupPrivate::connectUncontrolledAnimation(), connManager(), QScriptDebugger::continueAction(), QMdi::ControlContainer::ControlContainer(), QLineControl::copy(), QSoftKeyManager::createAction(), QmlJSDebugger::BoundingRectHighlighter::createBoundingBox(), QProcessPrivate::createChannel(), QColumnViewPrivate::createColumn(), QmlJSDebugger::LiveSelectionTool::createContextMenu(), QScriptEngineDebuggerPrivate::createDebugger(), QBBIntegration::createDisplay(), QScriptDebuggerLocalsItemDelegate::createEditor(), QScriptBreakpointsItemDelegate::createEditor(), QToolBarLayout::createItem(), QSoftKeyManager::createKeyedAction(), QFileDialogPrivate::createMenuActions(), QUndoGroup::createRedoAction(), QUndoStack::createRedoAction(), QNetworkAccessManager::createRequest(), QNetworkAccessManagerPrivate::createSession(), QLineEdit::createStandardContextMenu(), QFileDialogPrivate::createToolButtons(), QUndoGroup::createUndoAction(), QUndoStack::createUndoAction(), QFileDialogPrivate::createWidgets(), QWSDisplay::Data::Data(), QMenuBar::defaultAction(), QCopChannel::detach(), QNetworkManagerEngine::deviceAdded(), QAbstractSocket::disconnectFromHostImplementation(), QDeclarativeFontObject::download(), QVGPaintEngine::drawCachedGlyphs(), QAbstractItemViewPrivate::editor(), QNetworkAccessCache::emitEntryReady(), QInputDialogPrivate::ensureComboBox(), QIcdEngine::ensureDBusConnection(), QInputDialogPrivate::ensureDoubleSpinBox(), QInputDialogPrivate::ensureEnabledConnection(), QInputDialogPrivate::ensureIntSpinBox(), QInputDialogPrivate::ensureLayout(), QInputDialogPrivate::ensureLineEdit(), QInputDialogPrivate::ensureListView(), QLabelPrivate::ensureTextControl(), QDialog::exec(), QDeclarativeViewPrivate::execute(), QWSSoundServerPrivate::feedDevice(), QScriptDebugger::findInScriptAction(), QScriptDebugger::findNextInScriptAction(), QScriptDebugger::findPreviousInScriptAction(), QDeclarativeInclude::finished(), QLineEdit::focusInEvent(), QNetworkSessionManagerPrivate::forceSessionClose(), QNetworkAccessFtpBackend::ftpConnectionReady(), QMainWindowLayout::getTabBar(), QScriptDebugger::goToLineAction(), QWizardPrivate::handleAeroStyleChange(), QGLWindowSurface::hijackWindow(), QWorkspaceChild::iconWidget(), QGraphicsSvgItemPrivate::init(), QToolButtonPrivate::init(), QTextBrowserPrivate::init(), QColorDialogPrivate::init(), QTextEditPrivate::init(), QCompleterPrivate::init(), QToolBarPrivate::init(), QDialPrivate::init(), QDeclarativeTextEditPrivate::init(), QAbstractScrollAreaPrivate::init(), QFontDialogPrivate::init(), QDockWidgetPrivate::init(), QLineEditPrivate::init(), QProgressDialogPrivate::init(), QAuServerNAS::init(), QFileSystemWatcherPrivate::init(), QAbstractItemViewPrivate::init(), QPlainTextEditPrivate::init(), QSidebar::init(), QGraphicsSceneIndexPrivate::init(), QHttpPrivate::init(), QHttpNetworkConnectionChannel::init(), QStandardItemModelPrivate::init(), QTableViewPrivate::init(), QTabBarPrivate::init(), QPrintPreviewDialogPrivate::init(), QDeclarativeGridViewPrivate::init(), Maemo::IcdPrivate::init(), QMessageBoxPrivate::init(), QPrintPreviewWidgetPrivate::init(), QTabWidgetPrivate::init(), QDeclarativeListViewPrivate::init(), QPageSetupDialogPrivate::init(), QVNCServer::init(), QWorkspacePrivate::init(), QDateTimeEditPrivate::initCalendarPopup(), QFileSystemWatcherPrivate::initForcedEngine(), QSocks5SocketEngine::initialize(), QHttpSocketEngine::initialize(), QConnmanEngine::initialize(), QNetworkManagerEngine::initialize(), QTreeViewPrivate::initialize(), QColumnViewPrivate::initialize(), QSocks5SocketEnginePrivate::initialize(), QItemSelectionModelPrivate::initModel(), QFileSystemWatcherPrivate::initPollerEngine(), QWSServerPrivate::initServer(), QStyleSheetStyle::initWidget(), QToolBox::insertItem(), QTabBar::insertTab(), QMainWindow::insertToolBar(), QBBSystemLocaleData::installSocketNotifiers(), QNetworkManagerEngine::interfacePropertiesChanged(), QScriptDebugger::interruptAction(), QDeclarativeGridView::itemsRemoved(), QDeclarativeListView::itemsRemoved(), QScriptDebuggerConsoleWidget::keyPressEvent(), QTcpServerConnection::listen(), QUnixSocketServer::listen(), QDeclarativeLoaderPrivate::load(), QDeclarativeAnimatedImage::load(), QPatternist::AccelTreeResourceLoader::load(), QDeclarativeDataLoader::load(), loadDocument(), QHostInfo::lookupHost(), QDeclarativeAnimatedImage::movieRequestFinished(), QDeclarativeDataLoader::networkReplyFinished(), QNetworkManagerEngine::newAccessPoint(), QTcpServerConnection::newConnection(), QNetworkManagerEngine::newConnection(), QVNCServer::newConnection(), QWSPcMouseHandlerPrivate::notify(), QScriptDBusConnection::objectRegisteredAt(), QNetworkAccessFileBackend::open(), QPrintPreviewDialog::open(), QColorDialog::open(), QFontDialog::open(), QProgressDialog::open(), QAudioInputPrivate::open(), QPrintDialog::open(), QMessageBox::open(), QInputDialog::open(), QTipLabel::placeTip(), QStyleSheetStyle::polish(), QToolButtonPrivate::popupTimerDone(), QNetworkAccessHttpBackend::postRequest(), QConnmanEngine::propertyChangedContext(), QAuBucketQWS::QAuBucketQWS(), QAudioInput::QAudioInput(), QAudioInputPrivate::QAudioInputPrivate(), QAudioOutput::QAudioOutput(), QtMultimediaInternal::QAudioOutputBuffer::QAudioOutputBuffer(), QAudioOutputPrivate::QAudioOutputPrivate(), QAuServerNAS::QAuServerNAS(), QAuServerQWS::QAuServerQWS(), QAuthDevice::QAuthDevice(), QAxScript::QAxScript(), QAxSelect::QAxSelect(), QBalloonTip::QBalloonTip(), QBBIntegration::QBBIntegration(), QByteDeviceWrappingIoDevice::QByteDeviceWrappingIoDevice(), QCalendarWidget::QCalendarWidget(), QColorShower::QColorShower(), QComboBoxPrivateContainer::QComboBoxPrivateContainer(), QCoreWlanEngine::QCoreWlanEngine(), QDBusAbstractInterface::QDBusAbstractInterface(), QDBusConnectionInterface::QDBusConnectionInterface(), qDBusRealAddWatch(), QDBusServer::QDBusServer(), QDeclarativeContents::QDeclarativeContents(), QDeclarativeDebugConnectionPrivate::QDeclarativeDebugConnectionPrivate(), QDeclarativeEngineDebugService::QDeclarativeEngineDebugService(), QDeclarativeFolderListModel::QDeclarativeFolderListModel(), QDeclarativeInclude::QDeclarativeInclude(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeTimer::QDeclarativeTimer(), QmlJSDebugger::QDeclarativeViewInspector::QDeclarativeViewInspector(), QDeclarativeWatchProxy::QDeclarativeWatchProxy(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::QDeclarativeXmlQueryEngine(), QDirectFBKeyboardHandlerPrivate::QDirectFBKeyboardHandlerPrivate(), QDirectFBMouseHandlerPrivate::QDirectFBMouseHandlerPrivate(), QDirectFBScreenPrivate::QDirectFBScreenPrivate(), QDnotifyFileSystemWatcherEngine::QDnotifyFileSystemWatcherEngine(), QErrorMessage::QErrorMessage(), QExpandingLineEdit::QExpandingLineEdit(), QFbScreen::QFbScreen(), QFileInfoGatherer::QFileInfoGatherer(), QFontComboBox::QFontComboBox(), QFtp::QFtp(), QFtpDTP::QFtpDTP(), QFtpPI::QFtpPI(), QHostInfoLookupManager::QHostInfoLookupManager(), QInputDialogDoubleSpinBox::QInputDialogDoubleSpinBox(), QInputDialogSpinBox::QInputDialogSpinBox(), QIntMouseHandler::QIntMouseHandler(), QPatternist::QIODeviceDelegate::QIODeviceDelegate(), QLinuxInputKeyboardHandler::QLinuxInputKeyboardHandler(), QLinuxInputMouseHandler::QLinuxInputMouseHandler(), QMdiSubWindow::QMdiSubWindow(), QmlApplicationViewer::QmlApplicationViewer(), QmlJSDebugger::QmlToolBar::QmlToolBar(), QMovie::QMovie(), QMultiInputContext::QMultiInputContext(), QNativeWifiEngine::QNativeWifiEngine(), QNetworkConfigurationManager::QNetworkConfigurationManager(), QNetworkManagerEngine::QNetworkManagerEngine(), QNetworkManagerInterface::QNetworkManagerInterface(), QNetworkSession::QNetworkSession(), QNlaEngine::QNlaEngine(), QNonContiguousByteDeviceBufferImpl::QNonContiguousByteDeviceBufferImpl(), QNonContiguousByteDeviceIoDeviceImpl::QNonContiguousByteDeviceIoDeviceImpl(), QScriptEnginePrivate::qobjectData(), QPacketProtocolPrivate::QPacketProtocolPrivate(), QPageSetupWidget::QPageSetupWidget(), QPaintBufferResource::QPaintBufferResource(), QPrintPropertiesDialog::QPrintPropertiesDialog(), QQnxMouseHandler::QQnxMouseHandler(), QScriptBreakpointsWidget::QScriptBreakpointsWidget(), QScriptDebuggerCodeFinderWidget::QScriptDebuggerCodeFinderWidget(), QScriptDebuggerCodeView::QScriptDebuggerCodeView(), QScriptDebuggerConsoleWidget::QScriptDebuggerConsoleWidget(), QScriptEdit::QScriptEdit(), QScriptNewBreakpointWidget::QScriptNewBreakpointWidget(), QShortcut::QShortcut(), QSingleShotTimer::QSingleShotTimer(), QSmoothedAnimation::QSmoothedAnimation(), QSortFilterProxyModel::QSortFilterProxyModel(), QStackedWidget::QStackedWidget(), QSvgWidget::QSvgWidget(), qt_create_commandline(), QToolBarLayout::QToolBarLayout(), QToolButton::QToolButton(), QTreeWidget::QTreeWidget(), QTsLibMouseHandler::QTsLibMouseHandler(), QUndoModel::QUndoModel(), QUnixPrintWidgetPrivate::QUnixPrintWidgetPrivate(), QUnixSocketPrivate::QUnixSocketPrivate(), QVFbKeyboardHandler::QVFbKeyboardHandler(), QVFbMouseHandler::QVFbMouseHandler(), QVFbScreenKeyboardHandler::QVFbScreenKeyboardHandler(), QVFbScreenMouseHandler::QVFbScreenMouseHandler(), QVFbScreenPrivate::QVFbScreenPrivate(), QWaylandDisplay::QWaylandDisplay(), QWhatsThis::QWhatsThis(), QWhatsThisAction::QWhatsThisAction(), QWizardPage::QWizardPage(), QWorkspaceChild::QWorkspaceChild(), QWSClient::QWSClient(), QWSIntKbPrivate::QWSIntKbPrivate(), QWSKbPrivate::QWSKbPrivate(), QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(), QWSLinuxInputMousePrivate::QWSLinuxInputMousePrivate(), QWSLinuxTPMouseHandlerPrivate::QWSLinuxTPMouseHandlerPrivate(), QWSQnxKeyboardHandler::QWSQnxKeyboardHandler(), QWSSocket::QWSSocket(), QWSSoundServerClient::QWSSoundServerClient(), QWSTslibMouseHandlerPrivate::QWSTslibMouseHandlerPrivate(), QWSTtyKbPrivate::QWSTtyKbPrivate(), QWSUmKeyboardHandlerPrivate::QWSUmKeyboardHandlerPrivate(), QXcbConnection::QXcbConnection(), QXlibScreen::QXlibScreen(), QCopChannel::registerChannel(), QAbstractTextDocumentLayout::registerHandler(), QDBusConnectionPrivate::registerObject(), QTransportAuth::registerPolicyReceiver(), QWSDisplay::Data::reinit(), QDeclarativeXmlListModel::reload(), QAbstractScrollAreaPrivate::replaceScrollBar(), QDeclarativeXMLHttpRequest::requestFromUrl(), QWidgetAction::requestWidget(), QAlphaWidget::run(), QInotifyFileSystemWatcherEngine::run(), QDnotifySignalThread::run(), QPollingFileSystemWatcherEngine::run(), QRollEffect::run(), QScriptDebugger::runToCursorAction(), QScriptDebugger::runToNewScriptAction(), QDeclarativeListView::sectionCriteria(), QmlJSDebugger::LiveSelectionTool::selectedItemsChanged(), QSidebar::selectUrl(), QHttpNetworkConnectionChannel::sendRequest(), QDBusConnectionPrivate::sendWithReply(), QDBusConnectionPrivate::sendWithReplyAsync(), ShaderEffectItem::setActive(), QUndoGroup::setActiveStack(), QDeclarativeBehavior::setAnimation(), AVMediaObject::setAudioOutput(), QDBusAbstractAdaptor::setAutoRelaySignals(), QScriptEngineDebugger::setAutoShowStandardWindow(), QDeclarativeFlipable::setBack(), QScriptBreakpointsWidget::setBreakpointsModel(), QScriptDebuggerCodeWidget::setBreakpointsModel(), QDBusConnectionPrivate::setBusService(), QCalendarPopup::setCalendarWidget(), QProgressDialog::setCancelButton(), QAuthDevice::setClient(), QScriptDebugger::setCodeFinderWidget(), QLineEdit::setCompleter(), QNetworkManagerInterfaceAccessPoint::setConnections(), QNetworkManagerInterfaceDevice::setConnections(), QNetworkManagerInterfaceDeviceWired::setConnections(), QNetworkManagerInterfaceDeviceWireless::setConnections(), QNetworkManagerSettingsConnection::setConnections(), QNetworkManagerConnectionActive::setConnections(), QScriptDebugger::setConsoleWidget(), QTextControlPrivate::setContent(), QScriptDebuggerCodeWidget::setCurrentScript(), QDeclarativeTextEdit::setCursorDelegate(), QMenuBar::setDefaultAction(), QSyntaxHighlighter::setDocument(), QPPDOptionsEditor::setEditorData(), QUrlModel::setFileSystemModel(), QUndoView::setGroup(), QTreeView::setHeader(), QTableView::setHorizontalHeader(), QDataWidgetMapper::setItemDelegate(), QAbstractItemView::setItemDelegate(), QAbstractItemView::setItemDelegateForColumn(), QAbstractItemView::setItemDelegateForRow(), QComboBoxPrivateContainer::setItemView(), QAbstractSpinBox::setLineEdit(), QComboBox::setLineEdit(), QScriptDebuggerLocalsWidget::setLocalsModel(), QSignalMapper::setMapping(), QPushButton::setMenu(), QDeclarativeRepeater::setModel(), QTableView::setModel(), QDataWidgetMapper::setModel(), QTreeView::setModel(), QHeaderView::setModel(), QDeclarativePathView::setModel(), QCompleter::setModel(), QDeclarativeGridView::setModel(), QAbstractItemView::setModel(), QDeclarativeListView::setModel(), QDeclarativeVisualDataModel::setModel(), QComboBox::setModel(), QLabel::setMovie(), QMenuPrivate::setOverrideMenuAction(), QWizard::setPage(), QDeclarativePathView::setPath(), QCompleter::setPopup(), QmlOstPlugin::setPort(), QFileDialog::setProxyModel(), QColumnView::setResizeGripsVisible(), QDeclarativeAbstractAnimation::setRunning(), QGraphicsView::setScene(), QScriptDebuggerCodeWidget::setScriptsModel(), QScriptDebuggerScriptsWidget::setScriptsModel(), QScriptDebugger::setScriptsWidget(), QWorkspace::setScrollBarsEnabled(), QmlJSDebugger::QDeclarativeViewInspectorPrivate::setSelectedItemsForTools(), QTreeView::setSelectionModel(), QAbstractItemView::setSelectionModel(), QMenu::setSeparatorsCollapsible(), QHttpPrivate::setSock(), QUnixSocket::setSocketDescriptor(), QTableView::setSortingEnabled(), QTreeView::setSortingEnabled(), QDeclarativeFontLoader::setSource(), ShaderEffectItem::setSource(), ShaderEffectSource::setSourceItem(), QAbstractProxyModel::setSourceModel(), QIdentityProxyModel::setSourceModel(), QSortFilterProxyModel::setSourceModel(), QCompletionModel::setSourceModel(), QUndoModel::setStack(), QScriptDebuggerStackWidget::setStackModel(), QScriptDebugger::setStackWidget(), QTabWidget::setTabBar(), QTabWidget::setTabsClosable(), QTabBar::setTabsClosable(), QGraphicsItemAnimation::setTimeLine(), QListWidgetPrivate::setup(), QTableWidgetPrivate::setup(), QPrintPreviewDialogPrivate::setupActions(), QPrintDialogPrivate::setupDestination(), QDeviceClosedNotifier::setupDevice(), QPrintDialogPrivate::setupOptions(), QPrintDialogPrivate::setupPaper(), QPrintDialogPrivate::setupPrinterSettings(), QFtpDTP::setupSocket(), QDesktopServices::setUrlHandler(), QToolBarLayout::setUsePopupMenu(), QTableView::setVerticalHeader(), QMdiAreaPrivate::setViewMode(), QGraphicsProxyWidgetPrivate::setWidget_helper(), ShaderEffectItem::ShaderEffectItem(), QSidebar::showContextMenu(), QWorkspacePrivate::showMaximizeControls(), QStatusBar::showMessage(), QScriptEngineDebugger::standardWindow(), QBBNavigatorEventNotifier::start(), QBBButtonEventNotifier::start(), QNetworkConfigurationManagerPrivate::startPolling(), QProcessPrivate::startProcess(), QHttpThreadDelegate::startRequest(), QJSDebugService::statusChanged(), QScriptDebugger::stepIntoAction(), QScriptDebugger::stepOutAction(), QScriptDebugger::stepOverAction(), QStyleSheetStyle::styleRules(), QPSQLDriver::subscribeToNotificationImplementation(), QXcbConnection::sync(), QNetworkSessionPrivateImpl::syncStateWithInterface(), QGraphicsTextItemPrivate::textControl(), QCoreFuriCuri::timerEvent(), QScriptDebugger::toggleBreakpointAction(), QmlJSDebugger::ToolBarColorBox::ToolBarColorBox(), QNetworkConfigurationManagerPrivate::updateConfigurations(), QDeclarativeGridViewPrivate::updateTrackedItem(), QComboBoxPrivate::viewContainer(), QGraphicsView::viewportEvent(), QNetworkSession::waitForOpened(), QDeclarativeBasePositionerPrivate::watchChanges(), QmlJSDebugger::ZoomTool::ZoomTool(), and QVFbScreenPrivate::~QVFbScreenPrivate().

2583 {
2584  {
2585  const void *cbdata[] = { sender, signal, receiver, method, &type };
2587  return true;
2588  }
2589 
2590 #ifndef QT_NO_DEBUG
2591  bool warnCompat = true;
2592 #endif
2593  if (type == Qt::AutoCompatConnection) {
2594  type = Qt::AutoConnection;
2595 #ifndef QT_NO_DEBUG
2596  warnCompat = false;
2597 #endif
2598  }
2599 
2600  if (sender == 0 || receiver == 0 || signal == 0 || method == 0) {
2601  qWarning("QObject::connect: Cannot connect %s::%s to %s::%s",
2602  sender ? sender->metaObject()->className() : "(null)",
2603  (signal && *signal) ? signal+1 : "(null)",
2604  receiver ? receiver->metaObject()->className() : "(null)",
2605  (method && *method) ? method+1 : "(null)");
2606  return false;
2607  }
2608  QByteArray tmp_signal_name;
2609 
2610  if (!check_signal_macro(sender, signal, "connect", "bind"))
2611  return false;
2612  const QMetaObject *smeta = sender->metaObject();
2613  const char *signal_arg = signal;
2614  ++signal; //skip code
2615  int signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
2616  if (signal_index < 0) {
2617  // check for normalized signatures
2618  tmp_signal_name = QMetaObject::normalizedSignature(signal - 1);
2619  signal = tmp_signal_name.constData() + 1;
2620 
2621  smeta = sender->metaObject();
2622  signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
2623  }
2624  if (signal_index < 0) {
2625  // re-use tmp_signal_name and signal from above
2626 
2627  smeta = sender->metaObject();
2628  signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, true);
2629  }
2630  if (signal_index < 0) {
2631  err_method_notfound(sender, signal_arg, "connect");
2632  err_info_about_objects("connect", sender, receiver);
2633  return false;
2634  }
2635  signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
2636  int signalOffset, methodOffset;
2637  computeOffsets(smeta, &signalOffset, &methodOffset);
2638  int signal_absolute_index = signal_index + methodOffset;
2639  signal_index += signalOffset;
2640 
2641  QByteArray tmp_method_name;
2642  int membcode = extract_code(method);
2643 
2644  if (!check_method_code(membcode, receiver, method, "connect"))
2645  return false;
2646  const char *method_arg = method;
2647  ++method; // skip code
2648 
2649  const QMetaObject *rmeta = receiver->metaObject();
2650  int method_index_relative = -1;
2651  switch (membcode) {
2652  case QSLOT_CODE:
2653  method_index_relative = QMetaObjectPrivate::indexOfSlotRelative(&rmeta, method, false);
2654  break;
2655  case QSIGNAL_CODE:
2656  method_index_relative = QMetaObjectPrivate::indexOfSignalRelative(&rmeta, method, false);
2657  break;
2658  }
2659 
2660  if (method_index_relative < 0) {
2661  // check for normalized methods
2662  tmp_method_name = QMetaObject::normalizedSignature(method);
2663  method = tmp_method_name.constData();
2664 
2665  // rmeta may have been modified above
2666  rmeta = receiver->metaObject();
2667  switch (membcode) {
2668  case QSLOT_CODE:
2669  method_index_relative = QMetaObjectPrivate::indexOfSlotRelative(&rmeta, method, false);
2670  if (method_index_relative < 0)
2671  method_index_relative = QMetaObjectPrivate::indexOfSlotRelative(&rmeta, method, true);
2672  break;
2673  case QSIGNAL_CODE:
2674  method_index_relative = QMetaObjectPrivate::indexOfSignalRelative(&rmeta, method, false);
2675  if (method_index_relative < 0)
2676  method_index_relative = QMetaObjectPrivate::indexOfSignalRelative(&rmeta, method, true);
2677  break;
2678  }
2679  }
2680 
2681  if (method_index_relative < 0) {
2682  err_method_notfound(receiver, method_arg, "connect");
2683  err_info_about_objects("connect", sender, receiver);
2684  return false;
2685  }
2686 
2687  if (!QMetaObject::checkConnectArgs(signal, method)) {
2688  qWarning("QObject::connect: Incompatible sender/receiver arguments"
2689  "\n %s::%s --> %s::%s",
2690  sender->metaObject()->className(), signal,
2691  receiver->metaObject()->className(), method);
2692  return false;
2693  }
2694 
2695  int *types = 0;
2696  if ((type == Qt::QueuedConnection)
2697  && !(types = queuedConnectionTypes(smeta->method(signal_absolute_index).parameterTypes())))
2698  return false;
2699 
2700 #ifndef QT_NO_DEBUG
2701  if (warnCompat) {
2702  QMetaMethod smethod = smeta->method(signal_absolute_index);
2703  QMetaMethod rmethod = rmeta->method(method_index_relative + rmeta->methodOffset());
2704  check_and_warn_compat(smeta, smethod, rmeta, rmethod);
2705  }
2706 #endif
2707  if (!QMetaObjectPrivate::connect(sender, signal_index, receiver, method_index_relative, rmeta ,type, types))
2708  return false;
2709  const_cast<QObject*>(sender)->connectNotify(signal - 1);
2710  return true;
2711 }
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
int type
Definition: qmetatype.cpp:239
static QByteArray normalizedSignature(const char *method)
Normalizes the signature of the given method.
static bool connect(const QObject *sender, int signal_index, const QObject *receiver, int method_index_relative, const QMetaObject *rmeta=0, int type=0, int *types=0)
Definition: qobject.cpp:3209
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int *methodOffset)
Definition: qobject.cpp:225
static int indexOfSignalRelative(const QMetaObject **baseObject, const char *name, bool normalizeStringData)
Same as QMetaObject::indexOfSignal, but the result is the local offset to the base object...
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
static bool check_signal_macro(const QObject *sender, const char *signal, const char *func, const char *op)
Definition: qobject.cpp:2245
virtual void connectNotify(const char *signal)
This virtual function is called when something has been connected to signal in this object...
Definition: qobject.cpp:3142
QObject * sender() const
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; othe...
Definition: qobject.cpp:2327
static void err_info_about_objects(const char *func, const QObject *sender, const QObject *receiver)
Definition: qobject.cpp:2293
static void err_method_notfound(const QObject *object, const char *method, const char *func)
Definition: qobject.cpp:2272
int methodOffset() const
Returns the method offset for this class; i.e.
static bool activateCallbacks(Callback, void **)
Definition: qglobal.cpp:3653
static bool check_method_code(int code, const QObject *object, const char *method, const char *func)
Definition: qobject.cpp:2261
Q_CORE_EXPORT void qWarning(const char *,...)
static bool checkConnectArgs(const char *signal, const char *method)
Returns true if the signal and method arguments are compatible; otherwise returns false...
static int originalClone(const QMetaObject *obj, int local_method_index)
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
#define QSIGNAL_CODE
Definition: qobjectdefs.h:244
QList< QByteArray > parameterTypes() const
Returns a list of parameter types.
static const struct @32 types[]
static int indexOfSlotRelative(const QMetaObject **m, const char *slot, bool normalizeStringData)
#define QSLOT_CODE
Definition: qobjectdefs.h:243
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
static int * queuedConnectionTypes(const QList< QByteArray > &typeNames)
Definition: qobject.cpp:73
QMetaMethod method(int index) const
Returns the meta-data for the method with the given index.
static int extract_code(const char *member)
Definition: qobject.cpp:2228
static void check_and_warn_compat(const QMetaObject *sender, const QMetaMethod &signal, const QMetaObject *receiver, const QMetaMethod &method)
Definition: qobject.cpp:2497
The QMetaMethod class provides meta-data about a member function.
Definition: qmetaobject.h:56
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ connect() [2/3]

bool QObject::connect ( const QObject sender,
const QMetaMethod signal,
const QObject receiver,
const QMetaMethod method,
Qt::ConnectionType  type = Qt::AutoConnection 
)
static
Since
4.8

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns true if the connection succeeds; otherwise returns false.

This function works in the same way as connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type) but it uses QMetaMethod to specify signal and method.

See also
connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)

Definition at line 2730 of file qobject.cpp.

2733 {
2734 #ifndef QT_NO_DEBUG
2735  bool warnCompat = true;
2736 #endif
2737  if (type == Qt::AutoCompatConnection) {
2739 #ifndef QT_NO_DEBUG
2740  warnCompat = false;
2741 #endif
2742  }
2743 
2744  if (sender == 0
2745  || receiver == 0
2746  || signal.methodType() != QMetaMethod::Signal
2747  || method.methodType() == QMetaMethod::Constructor) {
2748  qWarning("QObject::connect: Cannot connect %s::%s to %s::%s",
2749  sender ? sender->metaObject()->className() : "(null)",
2750  signal.signature(),
2751  receiver ? receiver->metaObject()->className() : "(null)",
2752  method.signature() );
2753  return false;
2754  }
2755 
2756  QVarLengthArray<char> signalSignature;
2757  QObjectPrivate::signalSignature(signal, &signalSignature);
2758 
2759  {
2760  QByteArray methodSignature;
2761  methodSignature.reserve(qstrlen(method.signature())+1);
2762  methodSignature.append((char)(method.methodType() == QMetaMethod::Slot ? QSLOT_CODE
2763  : method.methodType() == QMetaMethod::Signal ? QSIGNAL_CODE : 0 + '0'));
2764  methodSignature.append(method.signature());
2765  const void *cbdata[] = { sender, signalSignature.constData(), receiver, methodSignature.constData(), &type };
2767  return true;
2768  }
2769 
2770 
2771  int signal_index;
2772  int method_index;
2773  {
2774  int dummy;
2775  QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
2776  QMetaObjectPrivate::memberIndexes(receiver, method, &dummy, &method_index);
2777  }
2778 
2779  const QMetaObject *smeta = sender->metaObject();
2780  const QMetaObject *rmeta = receiver->metaObject();
2781  if (signal_index == -1) {
2782  qWarning("QObject::connect: Can't find signal %s on instance of class %s",
2783  signal.signature(), smeta->className());
2784  return false;
2785  }
2786  if (method_index == -1) {
2787  qWarning("QObject::connect: Can't find method %s on instance of class %s",
2788  method.signature(), rmeta->className());
2789  return false;
2790  }
2791 
2792  if (!QMetaObject::checkConnectArgs(signal.signature(), method.signature())) {
2793  qWarning("QObject::connect: Incompatible sender/receiver arguments"
2794  "\n %s::%s --> %s::%s",
2795  smeta->className(), signal.signature(),
2796  rmeta->className(), method.signature());
2797  return false;
2798  }
2799 
2800  int *types = 0;
2801  if ((type == Qt::QueuedConnection)
2802  && !(types = queuedConnectionTypes(signal.parameterTypes())))
2803  return false;
2804 
2805 #ifndef QT_NO_DEBUG
2806  if (warnCompat)
2807  check_and_warn_compat(smeta, signal, rmeta, method);
2808 #endif
2809  if (!QMetaObjectPrivate::connect(sender, signal_index, receiver, method_index, 0, type, types))
2810  return false;
2811 
2812  const_cast<QObject*>(sender)->connectNotify(signalSignature.constData());
2813  return true;
2814 }
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
const T * constData() const
int type
Definition: qmetatype.cpp:239
static void signalSignature(const QMetaMethod &signal, QVarLengthArray< char > *result)
Definition: qobject_p.h:255
static bool connect(const QObject *sender, int signal_index, const QObject *receiver, int method_index_relative, const QMetaObject *rmeta=0, int type=0, int *types=0)
Definition: qobject.cpp:3209
QByteArray & append(char c)
Appends the character ch to this byte array.
static void memberIndexes(const QObject *obj, const QMetaMethod &member, int *signalIndex, int *methodIndex)
This helper function calculates signal and method index for the given member in the specified class...
Definition: qobject.cpp:2468
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
virtual void connectNotify(const char *signal)
This virtual function is called when something has been connected to signal in this object...
Definition: qobject.cpp:3142
QObject * sender() const
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; othe...
Definition: qobject.cpp:2327
static bool activateCallbacks(Callback, void **)
Definition: qglobal.cpp:3653
Q_CORE_EXPORT void qWarning(const char *,...)
static bool checkConnectArgs(const char *signal, const char *method)
Returns true if the signal and method arguments are compatible; otherwise returns false...
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
MethodType methodType() const
Returns the type of this method (signal, slot, or method).
#define QSIGNAL_CODE
Definition: qobjectdefs.h:244
uint qstrlen(const char *str)
Definition: qbytearray.h:79
QList< QByteArray > parameterTypes() const
Returns a list of parameter types.
static const struct @32 types[]
#define QSLOT_CODE
Definition: qobjectdefs.h:243
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
static int * queuedConnectionTypes(const QList< QByteArray > &typeNames)
Definition: qobject.cpp:73
const char * signature() const
Returns the signature of this method (e.g., setValue(double)).
void reserve(int size)
Attempts to allocate memory for at least size bytes.
Definition: qbytearray.h:449
static void check_and_warn_compat(const QMetaObject *sender, const QMetaMethod &signal, const QMetaObject *receiver, const QMetaMethod &method)
Definition: qobject.cpp:2497
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ connect() [3/3]

bool QObject::connect ( const QObject sender,
const char *  signal,
const char *  member,
Qt::ConnectionType  type = Qt::AutoConnection 
) const
inline

Definition at line 337 of file qobject.h.

339 { return connect(asender, asignal, this, amember, atype); }
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580

◆ connectNotify()

void QObject::connectNotify ( const char *  signal)
protectedvirtual

This virtual function is called when something has been connected to signal in this object.

If you want to compare signal with a specific signal, use QLatin1String and the SIGNAL() macro as follows:

if (QLatin1String(signal) == SIGNAL(valueChanged(int))) {
// signal is valueChanged(int)
}

If the signal contains multiple parameters or parameters that contain spaces, call QMetaObject::normalizedSignature() on the result of the SIGNAL() macro.

Warning
This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.
See also
connect(), disconnectNotify()

Reimplemented in QOfonoSmsInterface, QOfonoPrimaryDataContextInterface, QConnmanAgentInterface, QOfonoDataConnectionManagerInterface, QConnmanTechnologyInterface, QOfonoSimInterface, QConnmanServiceInterface, QOfonoNetworkOperatorInterface, QOfonoNetworkRegistrationInterface, QConnmanProfileInterface, QOfonoModemInterface, QConnmanManagerInterface, QDBusAbstractInterface, QNetworkSession, QOfonoManagerInterface, QFutureWatcherBase, QClipboard, QAxWidget, QBuffer, and QAxObject.

Definition at line 3142 of file qobject.cpp.

Referenced by connect(), and QNetworkSession::connectNotify().

3143 {
3144 }

◆ customEvent()

void QObject::customEvent ( QEvent )
protectedvirtual

This event handler can be reimplemented in a subclass to receive custom events.

Custom events are user-defined events with a type value at least as large as the QEvent::User item of the QEvent::Type enum, and is typically a QEvent subclass. The event is passed in the event parameter.

See also
event(), QEvent

Reimplemented in QDBusConnectionPrivate.

Definition at line 1346 of file qobject.cpp.

Referenced by event().

1347 {
1348 }

◆ deleteLater

void QObject::deleteLater ( )
slot

Schedules this object for deletion.

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.

Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.

See also
destroyed(), QPointer

Definition at line 2145 of file qobject.cpp.

Referenced by QWSServerPrivate::_q_clientClosed(), QScriptDebuggerLocalsWidgetPrivate::_q_onCompletionTaskFinished(), QScriptDebuggerConsoleWidgetPrivate::_q_onCompletionTaskFinished(), QToolBoxPrivate::_q_widgetDestroyed(), QUnixSocket::abort(), QHttpThreadDelegate::abortRequest(), QLocalServerPrivate::addListener(), QNetworkConfigurationManagerPrivate::cleanup(), QDeclarativeLoaderPrivate::clear(), QGraphicsWidget::close(), QColumnViewPrivate::closeColumns(), connManager(), QWidgetAction::deleteWidget(), QDBusConnectionPrivate::deleteYourself(), QDeclarativeObjectScriptClass::destroy(), QDeclarativeXMLHttpRequest::destroyNetwork(), QDeferredGraphicsSystemChange::doChange(), doDeleteLater(), QDragManager::drag(), QOleDropTarget::Drop(), QScriptEdit::extraAreaMouseEvent(), QDeclarativeInclude::finished(), QTipLabel::hideTipImmediately(), QDeclarativeDataLoader::networkReplyFinished(), QDeclarativePixmapReader::networkRequestDone(), QNetworkAccessHttpBackend::postRequest(), QDeclarativePixmapReader::processJobs(), qFadeEffect(), qScrollEffect(), QWSSoundServerClient::QWSSoundServerClient(), QDeclarativeVisualDataModel::release(), QAbstractItemViewPrivate::releaseEditor(), QNetworkManagerEngine::removeConnection(), QBBIntegration::removeDisplay(), QAlphaWidget::render(), QDeclarativeFontObject::replyFinished(), QRollEffect::scroll(), QMainWindow::setMenuBar(), QAbstractItemView::setModel(), QColumnView::setResizeGripsVisible(), QDeclarativeConnections::setTarget(), QToolBarLayout::takeAt(), QWidget::update(), QX11Data::xdndHandleBadwindow(), QDeclarativePixmapReader::~QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine(), QDeclarativeXmlQueryEngine::~QDeclarativeXmlQueryEngine(), QEventDispatcherMac::~QEventDispatcherMac(), and QScriptEngineDebuggerBackendPrivate::~QScriptEngineDebuggerBackendPrivate().

2146 {
2148 }
static void postEvent(QObject *receiver, QEvent *event)
Adds the event event, with the object receiver as the receiver of the event, to an event queue and re...
The QEvent class is the base class of all event classes.
Definition: qcoreevent.h:56

◆ destroyed

QObject::destroyed ( QObject obj = 0)
signal

This signal is emitted immediately before the object obj is destroyed, and can not be blocked.

All the objects's children are destroyed immediately after this signal is emitted.

See also
deleteLater(), QPointer

Referenced by QObjectCleanupHandler::add(), QDeclarativeAnchorsPrivate::addDepend(), QWizardPrivate::addField(), QAxScriptManager::addObject(), QGLShaderProgram::addShader(), QDialogButtonBox::clear(), QDBusConnectionPrivate::connectSignal(), connManager(), QSoftKeyManager::createAction(), QmlJSDebugger::BoundingRectHighlighter::createBoundingBox(), QSoftKeyManager::createKeyedAction(), QDeclarativeData::destroyed(), QVGPaintEngine::drawCachedGlyphs(), QAbstractItemViewPrivate::editor(), QGLWindowSurface::hijackWindow(), QAuServerNAS::init(), QStyleSheetStyle::initWidget(), QToolBox::insertItem(), QTipLabel::placeTip(), QBalloonTip::QBalloonTip(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeXmlQueryEngine::QDeclarativeXmlQueryEngine(), QHostInfoLookupManager::QHostInfoLookupManager(), QAbstractTextDocumentLayout::registerHandler(), QDBusConnectionPrivate::registerObject(), QWidgetAction::releaseWidget(), QDeclarativeAnchorsPrivate::remDepend(), QObjectCleanupHandler::remove(), QDialogButtonBox::removeButton(), QWizardPrivate::removeFieldAt(), QToolBox::removeItem(), QGLShaderProgram::removeShader(), QWidgetAction::requestWidget(), QTipLabel::reuseTip(), QAuthDevice::setClient(), QMenuBar::setDefaultAction(), QComboBoxPrivateContainer::setItemView(), QSignalMapper::setMapping(), QDataWidgetMapper::setModel(), QAbstractItemView::setModel(), QComboBox::setModel(), QMenuPrivate::setOverrideMenuAction(), QmlJSDebugger::QDeclarativeViewInspectorPrivate::setSelectedItemsForTools(), QAbstractProxyModel::setSourceModel(), QCompletionModel::setSourceModel(), QUndoModel::setStack(), QDesktopServices::setUrlHandler(), QGraphicsProxyWidgetPrivate::setWidget_helper(), QComboBox::~QComboBox(), QGraphicsProxyWidget::~QGraphicsProxyWidget(), ~QObject(), and QWidgetAction::~QWidgetAction().

◆ disconnect() [1/4]

bool QObject::disconnect ( const QObject sender,
const char *  signal,
const QObject receiver,
const char *  method 
)
static

Disconnects signal in object sender from method in object receiver.

Note
This class or function is threadsafe.

Returns true if the connection is successfully broken; otherwise returns false.

A signal-slot connection is removed when either of the objects involved are destroyed.

disconnect() is typically used in three ways, as the following examples demonstrate.

  1. Disconnect everything connected to an object's signals:

    disconnect(myObject, 0, 0, 0);

    equivalent to the non-static overloaded function

    myObject->disconnect();
  2. Disconnect everything connected to a specific signal:

    disconnect(myObject, SIGNAL(mySignal()), 0, 0);

    equivalent to the non-static overloaded function

    myObject->disconnect(SIGNAL(mySignal()));
  3. Disconnect a specific receiver:

    disconnect(myObject, 0, myReceiver, 0);

    equivalent to the non-static overloaded function

    myObject->disconnect(myReceiver);

0 may be used as a wildcard, meaning "any signal", "any receiving object", or "any slot in the receiving object", respectively.

The sender may never be 0. (You cannot disconnect signals from more than one object in a single call.)

If signal is 0, it disconnects receiver and method from any signal. If not, only the specified signal is disconnected.

If receiver is 0, it disconnects anything connected to signal. If not, slots in objects other than receiver are not disconnected.

If method is 0, it disconnects anything that is connected to receiver. If not, only slots named method will be disconnected, and all other slots are left alone. The method must be 0 if receiver is left out, so you cannot disconnect a specifically-named slot on all objects.

See also
connect()

Definition at line 2895 of file qobject.cpp.

Referenced by QStateMachinePrivate::_q_animationFinished(), QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished(), QMessageBoxPrivate::_q_buttonClicked(), QProgressDialogPrivate::_q_disconnectOnClose(), QNetworkAccessManagerPrivate::_q_networkSessionClosed(), QScriptDebuggerLocalsWidgetPrivate::_q_onCompletionTaskFinished(), QNetworkReplyImpl::abort(), QToolButton::actionEvent(), QMenuBar::actionEvent(), QMenu::actionEvent(), _IapAddTimer::add(), QMainWindow::addToolBar(), QStateMachinePrivate::applyProperties(), QNetworkSessionPrivateImpl::cleanupSession(), QDeclarativePixmap::clear(), QDialogButtonBox::clear(), QLabelPrivate::clearContents(), QNetworkReplyImpl::close(), QPSQLDriver::close(), QNetworkReplyImplPrivate::completeCacheSave(), QDeclarativeView::continueExecute(), QLineControl::copy(), QNetworkAccessManagerPrivate::createSession(), QNetworkSessionPrivateImpl::decrementTimeout(), QDeclarativeXmlListModelPrivate::deleteReply(), QDeclarativeCompiledBindingsPrivate::Binding::destroy(), QDeclarativeXMLHttpRequest::destroyNetwork(), QVistaHelper::disconnectBackButton(), QNetworkAccessFtpBackend::disconnectFromFtp(), QProxyModel::disconnectFromModel(), ShaderEffectItem::disconnectPropertySignals(), QMdiAreaPrivate::disconnectSubWindow(), QAnimationGroupPrivate::disconnectUncontrolledAnimation(), QAbstractPageSetupDialog::done(), QPrintPreviewDialog::done(), QPrintDialog::done(), QFontDialog::done(), QColorDialog::done(), QInputDialog::done(), QNetworkAccessCache::emitEntryReady(), QDeclarativeInclude::finished(), QLineEdit::focusOutEvent(), QNetworkSessionManagerPrivate::forceSessionClose(), QmlJSDebugger::BoundingRectHighlighter::freeBoundingBox(), QNetworkAccessFtpBackend::ftpDone(), QDBusConnectionPrivate::objectDestroyed(), QScriptDBusConnection::objectRegisteredAt(), QToolButtonPrivate::popupTimerDone(), QDeclarativeDebugConnectionPrivate::readyRead(), QPacketProtocolPrivate::readyToRead(), QDBusConnectionPrivate::registerObject(), QAbstractItemViewPrivate::releaseEditor(), QDeclarativeGridViewPrivate::releaseItem(), QWidgetAction::releaseWidget(), QDeclarativeAnchorsPrivate::remDepend(), QObjectCleanupHandler::remove(), QActionGroup::removeAction(), QDialogButtonBox::removeButton(), QConnmanEngine::removeConfiguration(), QWizardPrivate::removeFieldAt(), QToolBox::removeItem(), QGLShaderProgram::removeShader(), QMainWindowLayout::removeToolBar(), QAbstractSocketPrivate::resetSocketLayer(), QTipLabel::reuseTip(), QmlJSDebugger::LiveSelectionTool::selectedItemsChanged(), QSidebar::selectUrl(), QHttpNetworkConnectionChannel::sendRequest(), ShaderEffectItem::setActive(), QUndoGroup::setActiveStack(), AVMediaObject::setAudioOutput(), QDBusAbstractAdaptor::setAutoRelaySignals(), QScriptEngineDebugger::setAutoShowStandardWindow(), QNetworkReplyImplPrivate::setCachingEnabled(), QScriptDebugger::setCodeFinderWidget(), QLineEdit::setCompleter(), QScriptDebugger::setConsoleWidget(), QMenuBar::setDefaultAction(), QSyntaxHighlighter::setDocument(), QUrlModel::setFileSystemModel(), QUndoView::setGroup(), QInputDialogPrivate::setInputWidget(), QDataWidgetMapper::setItemDelegate(), QAbstractItemView::setItemDelegate(), QAbstractItemView::setItemDelegateForColumn(), QAbstractItemView::setItemDelegateForRow(), QComboBoxPrivateContainer::setItemView(), QScriptDebuggerLocalsWidget::setLocalsModel(), QDeclarativeRepeater::setModel(), QTableView::setModel(), QDataWidgetMapper::setModel(), QTreeView::setModel(), QHeaderView::setModel(), QDeclarativePathView::setModel(), QDeclarativeGridView::setModel(), QAbstractItemView::setModel(), QDeclarativeListView::setModel(), QDeclarativeVisualDataModel::setModel(), QComboBox::setModel(), QMenuPrivate::setOverrideMenuAction(), QDeclarativePathView::setPath(), QCompleter::setPopup(), QGraphicsView::setScene(), QScriptDebugger::setScriptsWidget(), QmlJSDebugger::QDeclarativeViewInspectorPrivate::setSelectedItemsForTools(), QTreeView::setSelectionModel(), QAbstractItemView::setSelectionModel(), QHttpPrivate::setSock(), QTableView::setSortingEnabled(), QTreeView::setSortingEnabled(), ShaderEffectSource::setSourceItem(), QAbstractProxyModel::setSourceModel(), QIdentityProxyModel::setSourceModel(), QSortFilterProxyModel::setSourceModel(), QCompletionModel::setSourceModel(), QUndoModel::setStack(), QScriptDebugger::setStackWidget(), QTabWidget::setTabsClosable(), QDeviceClosedNotifier::setupDevice(), QToolBarLayout::setUsePopupMenu(), QGraphicsProxyWidgetPrivate::setWidget_helper(), QHttpThreadDelegate::synchronousAuthenticationRequiredSlot(), QHttpThreadDelegate::synchronousProxyAuthenticationRequiredSlot(), QConnmanEngine::technologyPropertyChangedContext(), QStyleSheetStyle::unpolish(), QTransportAuth::unregisterPolicyReceiver(), QPSQLDriver::unsubscribeFromNotificationImplementation(), QDeclarativeBasePositionerPrivate::unwatchChanges(), QDeclarativeGridViewPrivate::updateTrackedItem(), _IapAddTimer::~_IapAddTimer(), Maemo::IcdPrivate::~IcdPrivate(), QAudioInputPrivate::~QAudioInputPrivate(), QAudioOutputPrivate::~QAudioOutputPrivate(), QComboBox::~QComboBox(), QGraphicsProxyWidget::~QGraphicsProxyWidget(), QIntMouseHandler::~QIntMouseHandler(), QVFbScreenPrivate::~QVFbScreenPrivate(), and QWidgetAction::~QWidgetAction().

2897 {
2898  if (sender == 0 || (receiver == 0 && method != 0)) {
2899  qWarning("Object::disconnect: Unexpected null parameter");
2900  return false;
2901  }
2902 
2903  {
2904  const void *cbdata[] = { sender, signal, receiver, method };
2906  return true;
2907  }
2908 
2909  const char *signal_arg = signal;
2910  QByteArray signal_name;
2911  bool signal_found = false;
2912  if (signal) {
2913  QT_TRY {
2914  signal_name = QMetaObject::normalizedSignature(signal);
2915  signal = signal_name.constData();
2916  } QT_CATCH (const std::bad_alloc &) {
2917  // if the signal is already normalized, we can continue.
2918  if (sender->metaObject()->indexOfSignal(signal + 1) == -1)
2919  QT_RETHROW;
2920  }
2921 
2922  if (!check_signal_macro(sender, signal, "disconnect", "unbind"))
2923  return false;
2924  signal++; // skip code
2925  }
2926 
2927  QByteArray method_name;
2928  const char *method_arg = method;
2929  int membcode = -1;
2930  bool method_found = false;
2931  if (method) {
2932  QT_TRY {
2933  method_name = QMetaObject::normalizedSignature(method);
2934  method = method_name.constData();
2935  } QT_CATCH(const std::bad_alloc &) {
2936  // if the method is already normalized, we can continue.
2937  if (receiver->metaObject()->indexOfMethod(method + 1) == -1)
2938  QT_RETHROW;
2939  }
2940 
2941  membcode = extract_code(method);
2942  if (!check_method_code(membcode, receiver, method, "disconnect"))
2943  return false;
2944  method++; // skip code
2945  }
2946 
2947  /* We now iterate through all the sender's and receiver's meta
2948  * objects in order to also disconnect possibly shadowed signals
2949  * and slots with the same signature.
2950  */
2951  bool res = false;
2952  const QMetaObject *smeta = sender->metaObject();
2953  do {
2954  int signal_index = -1;
2955  if (signal) {
2956  signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, false);
2957  if (signal_index < 0)
2958  signal_index = QMetaObjectPrivate::indexOfSignalRelative(&smeta, signal, true);
2959  if (signal_index < 0)
2960  break;
2961  signal_index = QMetaObjectPrivate::originalClone(smeta, signal_index);
2962  int signalOffset, methodOffset;
2963  computeOffsets(smeta, &signalOffset, &methodOffset);
2964  signal_index += signalOffset;
2965  signal_found = true;
2966  }
2967 
2968  if (!method) {
2969  res |= QMetaObjectPrivate::disconnect(sender, signal_index, receiver, -1);
2970  } else {
2971  const QMetaObject *rmeta = receiver->metaObject();
2972  do {
2973  int method_index = rmeta->indexOfMethod(method);
2974  if (method_index >= 0)
2975  while (method_index < rmeta->methodOffset())
2976  rmeta = rmeta->superClass();
2977  if (method_index < 0)
2978  break;
2979  res |= QMetaObjectPrivate::disconnect(sender, signal_index, receiver, method_index);
2980  method_found = true;
2981  } while ((rmeta = rmeta->superClass()));
2982  }
2983  } while (signal && (smeta = smeta->superClass()));
2984 
2985  if (signal && !signal_found) {
2986  err_method_notfound(sender, signal_arg, "disconnect");
2987  err_info_about_objects("disconnect", sender, receiver);
2988  } else if (method && !method_found) {
2989  err_method_notfound(receiver, method_arg, "disconnect");
2990  err_info_about_objects("disconnect", sender, receiver);
2991  }
2992  if (res)
2993  const_cast<QObject*>(sender)->disconnectNotify(signal ? (signal - 1) : 0);
2994  return res;
2995 }
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
static QByteArray normalizedSignature(const char *method)
Normalizes the signature of the given method.
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int *methodOffset)
Definition: qobject.cpp:225
static int indexOfSignalRelative(const QMetaObject **baseObject, const char *name, bool normalizeStringData)
Same as QMetaObject::indexOfSignal, but the result is the local offset to the base object...
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
static bool check_signal_macro(const QObject *sender, const char *signal, const char *func, const char *op)
Definition: qobject.cpp:2245
QObject * sender() const
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; othe...
Definition: qobject.cpp:2327
static void err_info_about_objects(const char *func, const QObject *sender, const QObject *receiver)
Definition: qobject.cpp:2293
static void err_method_notfound(const QObject *object, const char *method, const char *func)
Definition: qobject.cpp:2272
#define QT_RETHROW
Definition: qglobal.h:1539
static bool activateCallbacks(Callback, void **)
Definition: qglobal.cpp:3653
static bool check_method_code(int code, const QObject *object, const char *method, const char *func)
Definition: qobject.cpp:2261
Q_CORE_EXPORT void qWarning(const char *,...)
int indexOfSignal(const char *signal) const
Finds signal and returns its index; otherwise returns -1.
const QMetaObject * superClass() const
Returns the meta-object of the superclass, or 0 if there is no such object.
Definition: qobjectdefs.h:494
#define QT_CATCH(A)
Definition: qglobal.h:1537
static int originalClone(const QMetaObject *obj, int local_method_index)
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
virtual void disconnectNotify(const char *signal)
This virtual function is called when something has been disconnected from signal in this object...
Definition: qobject.cpp:3162
int indexOfMethod(const char *method) const
Finds method and returns its index; otherwise returns -1.
static bool disconnect(const QObject *sender, int signal_index, const QObject *receiver, int method_index, DisconnectType=DisconnectAll)
Definition: qobject.cpp:3342
static int extract_code(const char *member)
Definition: qobject.cpp:2228
#define QT_TRY
Definition: qglobal.h:1536
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ disconnect() [2/4]

bool QObject::disconnect ( const QObject sender,
const QMetaMethod signal,
const QObject receiver,
const QMetaMethod method 
)
static
Since
4.8

Disconnects signal in object sender from method in object receiver. Returns true if the connection is successfully broken; otherwise returns false.

This function provides the same possibilities like disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) but uses QMetaMethod to represent the signal and the method to be disconnected.

Additionally this function returnsfalse and no signals and slots disconnected if:

signal is not a member of sender class or one of its parent classes.

method is not a member of receiver class or one of its parent classes.

signal instance represents not a signal.

QMetaMethod() may be used as wildcard in the meaning "any signal" or "any slot in receiving object". In the same way 0 can be used for receiver in the meaning "any receiving object". In this case method should also be QMetaMethod(). sender parameter should be never 0.

See also
disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method)

Definition at line 3026 of file qobject.cpp.

3028 {
3029  if (sender == 0 || (receiver == 0 && method.mobj != 0)) {
3030  qWarning("Object::disconnect: Unexpected null parameter");
3031  return false;
3032  }
3033  if (signal.mobj) {
3034  if(signal.methodType() != QMetaMethod::Signal) {
3035  qWarning("Object::%s: Attempt to %s non-signal %s::%s",
3036  "disconnect","unbind",
3037  sender->metaObject()->className(), signal.signature());
3038  return false;
3039  }
3040  }
3041  if (method.mobj) {
3042  if(method.methodType() == QMetaMethod::Constructor) {
3043  qWarning("QObject::disconect: cannot use constructor as argument %s::%s",
3044  receiver->metaObject()->className(), method.signature());
3045  return false;
3046  }
3047  }
3048 
3049  QVarLengthArray<char> signalSignature;
3050  if (signal.mobj)
3051  QObjectPrivate::signalSignature(signal, &signalSignature);
3052 
3053  {
3054  QByteArray methodSignature;
3055  if (method.mobj) {
3056  methodSignature.reserve(qstrlen(method.signature())+1);
3057  methodSignature.append((char)(method.methodType() == QMetaMethod::Slot ? QSLOT_CODE
3058  : method.methodType() == QMetaMethod::Signal ? QSIGNAL_CODE : 0 + '0'));
3059  methodSignature.append(method.signature());
3060  }
3061  const void *cbdata[] = { sender, signal.mobj ? signalSignature.constData() : 0,
3062  receiver, method.mobj ? methodSignature.constData() : 0 };
3064  return true;
3065  }
3066 
3067  int signal_index;
3068  int method_index;
3069  {
3070  int dummy;
3071  QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
3072  QMetaObjectPrivate::memberIndexes(receiver, method, &dummy, &method_index);
3073  }
3074  // If we are here sender is not null. If signal is not null while signal_index
3075  // is -1 then this signal is not a member of sender.
3076  if (signal.mobj && signal_index == -1) {
3077  qWarning("QObject::disconect: signal %s not found on class %s",
3078  signal.signature(), sender->metaObject()->className());
3079  return false;
3080  }
3081  // If this condition is true then method is not a member of receeiver.
3082  if (receiver && method.mobj && method_index == -1) {
3083  qWarning("QObject::disconect: method %s not found on class %s",
3084  method.signature(), receiver->metaObject()->className());
3085  return false;
3086  }
3087 
3088  if (!QMetaObjectPrivate::disconnect(sender, signal_index, receiver, method_index))
3089  return false;
3090 
3091  const_cast<QObject*>(sender)->disconnectNotify(method.mobj ? signalSignature.constData() : 0);
3092  return true;
3093 }
const T * constData() const
static void signalSignature(const QMetaMethod &signal, QVarLengthArray< char > *result)
Definition: qobject_p.h:255
QByteArray & append(char c)
Appends the character ch to this byte array.
static void memberIndexes(const QObject *obj, const QMetaMethod &member, int *signalIndex, int *methodIndex)
This helper function calculates signal and method index for the given member in the specified class...
Definition: qobject.cpp:2468
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
QObject * sender() const
Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; othe...
Definition: qobject.cpp:2327
static bool activateCallbacks(Callback, void **)
Definition: qglobal.cpp:3653
Q_CORE_EXPORT void qWarning(const char *,...)
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
MethodType methodType() const
Returns the type of this method (signal, slot, or method).
#define QSIGNAL_CODE
Definition: qobjectdefs.h:244
uint qstrlen(const char *str)
Definition: qbytearray.h:79
virtual void disconnectNotify(const char *signal)
This virtual function is called when something has been disconnected from signal in this object...
Definition: qobject.cpp:3162
#define QSLOT_CODE
Definition: qobjectdefs.h:243
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
static bool disconnect(const QObject *sender, int signal_index, const QObject *receiver, int method_index, DisconnectType=DisconnectAll)
Definition: qobject.cpp:3342
const QMetaObject * mobj
Definition: qmetaobject.h:139
const char * signature() const
Returns the signature of this method (e.g., setValue(double)).
void reserve(int size)
Attempts to allocate memory for at least size bytes.
Definition: qbytearray.h:449
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ disconnect() [3/4]

bool QObject::disconnect ( const char *  signal = 0,
const QObject receiver = 0,
const char *  member = 0 
)
inline

Definition at line 248 of file qobject.h.

250  { return disconnect(this, signal, receiver, member); }
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895

◆ disconnect() [4/4]

bool QObject::disconnect ( const QObject receiver,
const char *  member = 0 
)
inline

Definition at line 251 of file qobject.h.

252  { return disconnect(this, 0, receiver, member); }
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895

◆ disconnectNotify()

void QObject::disconnectNotify ( const char *  signal)
protectedvirtual

This virtual function is called when something has been disconnected from signal in this object.

See connectNotify() for an example of how to compare signal with a specific signal.

Warning
This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.
See also
disconnect(), connectNotify()

Reimplemented in QOfonoSmsInterface, QOfonoPrimaryDataContextInterface, QConnmanAgentInterface, QOfonoDataConnectionManagerInterface, QConnmanTechnologyInterface, QOfonoSimInterface, QConnmanServiceInterface, QOfonoNetworkOperatorInterface, QOfonoNetworkRegistrationInterface, QConnmanProfileInterface, QOfonoModemInterface, QConnmanManagerInterface, QDBusAbstractInterface, QNetworkSession, QOfonoManagerInterface, QFutureWatcherBase, and QBuffer.

Definition at line 3162 of file qobject.cpp.

Referenced by disconnect(), and QNetworkSession::disconnectNotify().

3163 {
3164 }

◆ dumpObjectInfo()

void QObject::dumpObjectInfo ( )

Dumps information about signal connections, etc.

for this object to the debug output.

This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).

See also
dumpObjectTree()

Definition at line 3917 of file qobject.cpp.

3918 {
3919 #if defined(QT_DEBUG)
3920  qDebug("OBJECT %s::%s", metaObject()->className(),
3921  objectName().isEmpty() ? "unnamed" : objectName().toLocal8Bit().data());
3922 
3923  Q_D(QObject);
3924  QMutexLocker locker(signalSlotLock(this));
3925 
3926  // first, look for connections where this object is the sender
3927  qDebug(" SIGNALS OUT");
3928 
3929  if (d->connectionLists) {
3930  int offset = 0;
3931  int offsetToNextMetaObject = 0;
3932  for (int signal_index = 0; signal_index < d->connectionLists->count(); ++signal_index) {
3933  if (signal_index >= offsetToNextMetaObject) {
3934  const QMetaObject *mo = metaObject();
3935  int signalOffset, methodOffset;
3936  computeOffsets(mo, &signalOffset, &methodOffset);
3937  while (signalOffset > signal_index) {
3938  mo = mo->superClass();
3939  offsetToNextMetaObject = signalOffset;
3940  computeOffsets(mo, &signalOffset, &methodOffset);
3941  }
3942  offset = methodOffset - signalOffset;
3943  }
3944  const QMetaMethod signal = metaObject()->method(signal_index + offset);
3945  qDebug(" signal: %s", signal.signature());
3946 
3947  // receivers
3948  const QObjectPrivate::Connection *c =
3949  d->connectionLists->at(signal_index).first;
3950  while (c) {
3951  if (!c->receiver) {
3952  qDebug(" <Disconnected receiver>");
3953  c = c->nextConnectionList;
3954  continue;
3955  }
3956  const QMetaObject *receiverMetaObject = c->receiver->metaObject();
3957  const QMetaMethod method = receiverMetaObject->method(c->method());
3958  qDebug(" --> %s::%s %s",
3959  receiverMetaObject->className(),
3960  c->receiver->objectName().isEmpty() ? "unnamed" : qPrintable(c->receiver->objectName()),
3961  method.signature());
3962  c = c->nextConnectionList;
3963  }
3964  }
3965  } else {
3966  qDebug( " <None>" );
3967  }
3968 
3969  // now look for connections where this object is the receiver
3970  qDebug(" SIGNALS IN");
3971 
3972  if (d->senders) {
3973  for (QObjectPrivate::Connection *s = d->senders; s; s = s->next) {
3974  const QMetaMethod slot = metaObject()->method(s->method());
3975  qDebug(" <-- %s::%s %s",
3976  s->sender->metaObject()->className(),
3977  s->sender->objectName().isEmpty() ? "unnamed" : qPrintable(s->sender->objectName()),
3978  slot.signature());
3979  }
3980  } else {
3981  qDebug(" <None>");
3982  }
3983 #endif
3984 }
double d
Definition: qnumeric_p.h:62
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
unsigned char c[8]
Definition: qnumeric_p.h:62
static void computeOffsets(const QMetaObject *metaobject, int *signalOffset, int *methodOffset)
Definition: qobject.cpp:225
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
const char * className
Definition: qwizard.cpp:137
Q_CORE_EXPORT void qDebug(const char *,...)
static bool isEmpty(const char *str)
static const char * data(const QByteArray &arr)
const QMetaObject * superClass() const
Returns the meta-object of the superclass, or 0 if there is no such object.
Definition: qobjectdefs.h:494
static QMutex * signalSlotLock(const QObject *o)
Definition: qobject.cpp:103
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
QString objectName() const
QMetaMethod method(int index) const
Returns the meta-data for the method with the given index.
const char * signature() const
Returns the signature of this method (e.g., setValue(double)).
#define qPrintable(string)
Definition: qglobal.h:1750
The QMetaMethod class provides meta-data about a member function.
Definition: qmetaobject.h:56
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.

◆ dumpObjectTree()

void QObject::dumpObjectTree ( )

Dumps a tree of children to the debug output.

This function is useful for debugging, but does nothing if the library has been compiled in release mode (i.e. without debugging information).

See also
dumpObjectInfo()

Definition at line 3901 of file qobject.cpp.

3902 {
3903  dumpRecursive(0, this);
3904 }
static void dumpRecursive(int level, QObject *object)
Definition: qobject.cpp:3854

◆ dynamicPropertyNames()

QList< QByteArray > QObject::dynamicPropertyNames ( ) const

Returns the names of all properties that were dynamically added to the object using setProperty().

Since
4.2

Definition at line 3839 of file qobject.cpp.

Referenced by QScript::QObjectDelegate::getOwnPropertyNames().

3840 {
3841  Q_D(const QObject);
3842  if (d->extraData)
3843  return d->extraData->propertyNames;
3844  return QList<QByteArray>();
3845 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

◆ event()

bool QObject::event ( QEvent e)
virtual

This virtual function receives events to an object and should return true if the event e was recognized and processed.

The event() function can be reimplemented to customize the behavior of an object.

See also
installEventFilter(), timerEvent(), QApplication::sendEvent(), QApplication::postEvent(), QWidget::event()

Reimplemented in QMainWindowTabBar, QExceptionNotifier, QWriteNotifier, QReadNotifier, QCalendarView, QWidget, QGLWidget, QMdi::ControllerWidget, QMdi::ControlLabel, QTreeWidget, QApplication, QMessageBox, QAbstractItemView, QTableWidget, QSettings, QDeclarativePinchArea, QTextEdit, QDeclarativeTextEdit, QListWidget, QWorkspaceTitleBar, QTextControl, QGraphicsScene, QDeclarativeTextInput, QDeclarativeListView, QGraphicsView, QLineEdit, QPlainTextEdit, QComboBox, QAction, QGraphicsWidget, QMainWindow, QDeclarativeGridView, QCoreApplication, QHeaderView, QWizard, QTabBar, QDeclarativeWorkerScriptEnginePrivate, QMenu, QDeclarativePathView, QSplitterHandle, QStateMachine, QDeclarativeItem, QSystemTrayIconSys, QDeclarativeXmlQueryThreadObject, QCalendarPopup, QDateTimeEdit, QTabWidget, QDialogButtonBox, QFileSystemModel, QCalendarWidget, QMdiArea, QToolBar, QCompleter, QStyleSheetStyle, QMenuBar, QListView, QLabel, QAbstractSlider, QSidebar, QAbstractButton, QDeclarativePixmapReaderThreadObject, QAxHostWidget, QFrame, QScriptDebuggerBackendEventReceiver, QAbstractAnimation, QMacStyle, QAbstractSpinBox, QDockWidget, QX11EmbedContainer, QLCDNumber, QSplitter, QDeclarativePixmapReply, QProgressBar, QSystemTrayIcon, QMdiSubWindow, QDeclarativeListModelWorkerAgent, QDeclarativeWorkerScript, QToolButton, QDeclarativeSystemPalette, QTextBrowser, QDialog, QDnotifySignalThread, QClipboard, QState, QSpinBox, QWorkspace, QVariantAnimation, QStatusBar, QToolBox, QAbstractTransition, QMotifStyle, QEventDispatcherWin32, QAbstractScrollArea, QShortcut, QSlider, QProxyStyle, QMDIControl, QFontComboBox, QGraphicsSceneBspTreeIndex, QSoftKeyManager, QGroupBox, QPushButton, QWindowsVistaStyle, QDial, QNetworkReplyImpl, QStackedWidget, QScriptDebuggerCodeView, QScriptEditExtraArea, QFutureWatcherBase, QScrollArea, QSplashScreen, QWinEventNotifier, QGraphicsProxyWidget, QHistoryState, QAbstractState, QRubberBand, QCheckBox, QSocketNotifier, QX11EmbedWidget, QSequentialAnimationGroup, QEventTransition, QSignalTransition, QAnimationGroup, QPropertyAnimation, QSizeGrip, QScriptDebuggerFrontendEventReceiver, QWidgetAction, QCommandLinkButton, QPauseAnimation, QParallelAnimationGroup, QRadioButton, QScrollBar, QFinalState, QFocusFrame, and QMacNativeWidget.

Definition at line 1200 of file qobject.cpp.

Referenced by QWSServerPrivate::_q_newConnection(), QEventDispatcherUNIX::activateSocketNotifiers(), QDeclarativeDebugTrace::addEventImpl(), QDeclarativeState::apply(), clipboardData(), QGestureManager::deliverEvents(), QStyleSheetStyle::deref(), QBBBpsEventFilter::dispatcherEventFilter(), QStyledItemDelegate::editorEvent(), QItemDelegate::editorEvent(), QBBInputContext::endComposition(), QSocketNotifier::event(), QAbstractState::event(), QWinEventNotifier::event(), QFutureWatcherBase::event(), QNetworkReplyImpl::event(), QWindowsVistaStyle::event(), QGraphicsSceneBspTreeIndex::event(), QEventDispatcherWin32::event(), QAbstractTransition::event(), QMotifStyle::event(), QClipboard::event(), QDnotifySignalThread::event(), QDeclarativeSystemPalette::event(), QDeclarativeWorkerScript::event(), QDeclarativeListModelWorkerAgent::event(), QSystemTrayIcon::event(), QDeclarativePixmapReply::event(), QAbstractAnimation::event(), QDeclarativePixmapReaderThreadObject::event(), QStyleSheetStyle::event(), QCompleter::event(), QFileSystemModel::event(), QDeclarativeXmlQueryThreadObject::event(), QDeclarativeItem::event(), QDeclarativeWorkerScriptEnginePrivate::event(), QCoreApplication::event(), QGraphicsWidget::event(), QAction::event(), QGraphicsScene::event(), QTextControl::event(), QSettings::event(), QXlibScreen::eventDispatcher(), QBBInputContext::eventFilter(), QVistaHelper::eventFilter(), QScriptDebuggerLocalsItemDelegate::eventFilter(), QBBInputContext::filterEvent(), QBBEngine::filterEvent(), QApplicationPrivate::globalEventProcessor(), QDirectFbInput::handleEvents(), QBBInputContext::hasPhysicalKeyboard(), QAbstractItemDelegate::helpEvent(), QSystemTrayIcon::hide(), QmlJSDebugger::AbstractTool::inspector(), QGraphicsScene::invalidate(), QWSServerPrivate::invokeCreate(), QWSServerPrivate::invokeScreenTransform(), QBBInputContext::isComposing(), isProcessBeingDebugged(), QWSInputContext::language(), QCoreApplicationPrivate::notify_helper(), QApplicationPrivate::notify_helper(), QBBInputContext::onCommitText(), QBBInputContext::onDeleteSurroundingText(), QBBInputContext::onFinishComposingText(), QBBInputContext::onSetComposingRegion(), QShortcut::parentWidget(), QXlibScreen::physicalSize(), QKeyMapper::possibleKeys(), QEventDispatcherQPA::processEvents(), QEventDispatcherQWS::processEvents(), QEventDispatcherX11::processEvents(), QXcbConnection::processXcbEvents(), QExceptionNotifier::QExceptionNotifier(), QReadNotifier::QReadNotifier(), qt_x11_incr_event_filter(), QUIKitSoftwareInputHandler::QUIKitSoftwareInputHandler(), QWriteNotifier::QWriteNotifier(), QInotifyFileSystemWatcherEngine::readFromInotify(), QFactoryLoader::refreshAll(), QBBScreenEventThread::run(), QIntMouseListenThread::run(), QEventDispatcherBlackberry::select(), QWSClient::sendConnectedEvent(), QWSClient::sendEmbedEvent(), QWSServerPrivate::sendFontRemovedEvent(), QWSServer::sendIMEvent(), QWSServer::sendIMQuery(), QWSServerPrivate::sendKeyEventUnfiltered(), QWSClient::sendMaxWindowRectEvent(), QWSServerPrivate::sendMouseEventUnfiltered(), QWSClient::sendPropertyNotifyEvent(), QWSClient::sendPropertyReplyEvent(), QWSServerPrivate::sendQCopEvent(), QWSClient::sendRegionEvent(), QWSClient::sendSelectionClearEvent(), QWSClient::sendSelectionRequestEvent(), QBBInputContext::setComposingText(), QMacInputContext::setLastKeydownEvent(), QObjectPrivate::setThreadData_helper(), QBBScreenEventThread::shutdown(), QmlJSDebugger::AbstractViewInspector::slowDownFactor(), QTextControl::toHtml(), QSidebar::urls(), QmlJSDebugger::QDeclarativeViewInspector::viewWidget(), QXlibScreen::waitForClipboardEvent(), and QEventDispatcherBlackberry::wakeUp().

1201 {
1202  switch (e->type()) {
1203  case QEvent::Timer:
1204  timerEvent((QTimerEvent*)e);
1205  break;
1206 
1207 #ifdef QT3_SUPPORT
1208  case QEvent::ChildInsertedRequest:
1209  d_func()->sendPendingChildInsertedEvents();
1210  break;
1211 #endif
1212 
1213  case QEvent::ChildAdded:
1214  case QEvent::ChildPolished:
1215 #ifdef QT3_SUPPORT
1216  case QEvent::ChildInserted:
1217 #endif
1218  case QEvent::ChildRemoved:
1219  childEvent((QChildEvent*)e);
1220  break;
1221 
1223  qDeleteInEventHandler(this);
1224  break;
1225 
1226  case QEvent::MetaCall:
1227  {
1228 #ifdef QT_JAMBI_BUILD
1229  d_func()->inEventHandler = false;
1230 #endif
1231  QMetaCallEvent *mce = static_cast<QMetaCallEvent*>(e);
1232  QObjectPrivate::Sender currentSender;
1233  currentSender.sender = const_cast<QObject*>(mce->sender());
1234  currentSender.signal = mce->signalId();
1235  currentSender.ref = 1;
1236  QObjectPrivate::Sender * const previousSender =
1237  QObjectPrivate::setCurrentSender(this, &currentSender);
1238 #if defined(QT_NO_EXCEPTIONS)
1239  mce->placeMetaCall(this);
1240 #else
1241  QT_TRY {
1242  mce->placeMetaCall(this);
1243  } QT_CATCH(...) {
1244  QObjectPrivate::resetCurrentSender(this, &currentSender, previousSender);
1245  QT_RETHROW;
1246  }
1247 #endif
1248  QObjectPrivate::resetCurrentSender(this, &currentSender, previousSender);
1249  break;
1250  }
1251 
1252  case QEvent::ThreadChange: {
1253  Q_D(QObject);
1254  QThreadData *threadData = d->threadData;
1255  QAbstractEventDispatcher *eventDispatcher = threadData->eventDispatcher;
1256  if (eventDispatcher) {
1257  QList<QPair<int, int> > timers = eventDispatcher->registeredTimers(this);
1258  if (!timers.isEmpty()) {
1259  // set inThreadChangeEvent to true to tell the dispatcher not to release out timer ids
1260  // back to the pool (since the timer ids are moving to a new thread).
1261  d->inThreadChangeEvent = true;
1262  eventDispatcher->unregisterTimers(this);
1263  d->inThreadChangeEvent = false;
1264  QMetaObject::invokeMethod(this, "_q_reregisterTimers", Qt::QueuedConnection,
1265  Q_ARG(void*, (new QList<QPair<int, int> >(timers))));
1266  }
1267  }
1268  break;
1269  }
1270 
1271  default:
1272  if (e->type() >= QEvent::User) {
1273  customEvent(e);
1274  break;
1275  }
1276  return false;
1277  }
1278  return true;
1279 }
double d
Definition: qnumeric_p.h:62
static Sender * setCurrentSender(QObject *receiver, Sender *sender)
Definition: qobject_p.h:269
const QObject * sender() const
Definition: qobject_p.h:302
virtual void timerEvent(QTimerEvent *)
This event handler can be reimplemented in a subclass to receive timer events for the object...
Definition: qobject.cpp:1294
#define Q_ARG(type, data)
Definition: qobjectdefs.h:246
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
virtual QList< TimerInfo > registeredTimers(QObject *object) const =0
Returns a list of registered timers for object.
#define QT_RETHROW
Definition: qglobal.h:1539
virtual void childEvent(QChildEvent *)
This event handler can be reimplemented in a subclass to receive child events.
Definition: qobject.cpp:1332
static void resetCurrentSender(QObject *receiver, Sender *currentSender, Sender *previousSender)
Definition: qobject_p.h:277
#define QT_CATCH(A)
Definition: qglobal.h:1537
virtual void customEvent(QEvent *)
This event handler can be reimplemented in a subclass to receive custom events.
Definition: qobject.cpp:1346
The QChildEvent class contains event parameters for child object events.
Definition: qcoreevent.h:353
void qDeleteInEventHandler(QObject *o)
Definition: qobject.cpp:4348
The QTimerEvent class contains parameters that describe a timer event.
Definition: qcoreevent.h:341
virtual void placeMetaCall(QObject *object)
Definition: qobject.cpp:521
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.
Type type() const
Returns the event type.
Definition: qcoreevent.h:303
int signalId() const
Definition: qobject_p.h:303
QAbstractEventDispatcher * eventDispatcher
Definition: qthread_p.h:264
#define QT_TRY
Definition: qglobal.h:1536
virtual bool unregisterTimers(QObject *object)=0
Unregisters all the timers associated with the given object.
The QAbstractEventDispatcher class provides an interface to manage Qt&#39;s event queue.
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ eventFilter()

bool QObject::eventFilter ( QObject ,
QEvent  
)
virtual

Filters events if this object has been installed as an event filter for the watched object.

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.

Example:

class MainWindow : public QMainWindow
{
public:
MainWindow();
protected:
bool eventFilter(QObject *obj, QEvent *ev);
private:
QTextEdit *textEdit;
};
MainWindow::MainWindow()
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);
textEdit->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}

Notice in the example above that unhandled events are passed to the base class's eventFilter() function, since the base class might have reimplemented eventFilter() for its own internal purposes.

Warning
If you delete the receiver object in this function, be sure to return true. Otherwise, Qt will forward the event to the deleted object and the program might crash.
See also
installEventFilter()

Reimplemented in QWorkspaceChild, QWhatsThisPrivate, QAxServerBase, QGtkStyleFilter, QGraphicsScene, QComboBoxPrivateContainer, QScriptBreakpointsItemDelegate, QDragManager, QMacStylePrivate, QScriptDebuggerLocalsItemDelegate, QScriptDebugger, QStateMachine, QCalendarWidget, QMdiArea, QCompleter, QMenuBar, QmlJSDebugger::AbstractViewInspector, QVistaHelper, QTipLabel, QAxHostWidget, QFontDialog, QDialog, QX11EmbedContainer, QAbstractScrollAreaFilter, QMdiSubWindow, QItemDelegate, QMotifStyle, QDeclarativeSystemPalette, QWorkspace, QDeclarativeView, QPlastiqueStyle, QStyledItemDelegate, QWidgetResizeHandler, QWindowsStyle, QDeclarativeLoader, QMeeGoGraphicsSystemSwitchHandler, QScrollArea, QGraphicsProxyWidget, QCalendarTextNavigator, QmlJSDebugger::QDeclarativeViewInspector, QX11EmbedWidget, QAlphaWidget, QBBInputContext, QWidgetAction, QSizeGrip, QDeclarativeApplication, QFocusFrame, QWSEmbedWidget, and QUIKitSoftwareInputHandler.

Definition at line 1375 of file qobject.cpp.

Referenced by QWSEmbedWidget::eventFilter(), QSizeGrip::eventFilter(), QWidgetAction::eventFilter(), QBBInputContext::eventFilter(), QAlphaWidget::eventFilter(), QX11EmbedWidget::eventFilter(), QmlJSDebugger::QDeclarativeViewInspector::eventFilter(), QCalendarTextNavigator::eventFilter(), QGraphicsProxyWidget::eventFilter(), QDeclarativeLoader::eventFilter(), QWindowsStyle::eventFilter(), QDeclarativeView::eventFilter(), QWorkspace::eventFilter(), QDeclarativeSystemPalette::eventFilter(), QMotifStyle::eventFilter(), QMdiSubWindow::eventFilter(), QX11EmbedContainer::eventFilter(), QDialog::eventFilter(), QAxHostWidget::eventFilter(), QVistaHelper::eventFilter(), QmlJSDebugger::AbstractViewInspector::eventFilter(), QCompleter::eventFilter(), QCalendarWidget::eventFilter(), QMdiArea::eventFilter(), QComboBoxPrivateContainer::eventFilter(), QGtkStyleFilter::eventFilter(), QAxServerBase::eventFilter(), QWorkspaceChild::eventFilter(), QGraphicsScene::invalidate(), QCalendarWidget::isNavigationBarVisible(), QVistaHelper::leftMargin(), QApplication::notify(), QCoreApplicationPrivate::sendThroughApplicationEventFilters(), QCoreApplicationPrivate::sendThroughObjectEventFilters(), and QWidgetResizeHandler::setFrameWidth().

1376 {
1377  return false;
1378 }

◆ findChild()

template<typename T >
T * QObject::findChild ( const QString name = QString()) const
inline

Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object.

Omitting the name argument causes all object names to be matched. The search is performed recursively.

If there is more than one child matching the search, the most direct ancestor is returned. If there are several direct ancestors, it is undefined which one will be returned. In that case, findChildren() should be used.

This example returns a child QPushButton of parentWidget named "button1":

QPushButton *button = parentWidget->findChild<QPushButton *>("button1");

This example returns a QListWidget child of parentWidget:

See also
findChildren()

Definition at line 158 of file qobject.h.

Referenced by QDeclarativeVisualDataModelPrivate::data(), QPlastiqueStylePrivate::drawPartialFrame(), QWindowsVistaStyle::drawPrimitive(), embeddedWidget(), QStateMachinePrivate::goToState(), QWorkspacePrivate::maximizeWindow(), menuItemEntry(), QWorkspacePrivate::minimizeWindow(), QWorkspacePrivate::normalizeWindow(), QAxClientSite::OnPosRectChange(), QWindowsVistaStyle::polish(), qFindChild(), QScript::qobjectProtoFuncFindChild(), QPrintDialogPrivate::setupDestination(), QPrintDialogPrivate::setupOptions(), QPrintDialogPrivate::setupPaper(), QPrintDialogPrivate::setupPrinterSettings(), QMdiSubWindow::setWidget(), showNewMessageBox(), QWindowsStyle::styleHint(), QStyleSheetStyle::styleHint(), QMacStyle::unpolish(), and QWindowsVistaStyle::unpolish().

159  { return static_cast<T>(qt_qFindChild_helper(this, aName, reinterpret_cast<T>(0)->staticMetaObject)); }
static const QMetaObject staticMetaObject
This variable stores the meta-object for the class.
Definition: qobject.h:128
Q_CORE_EXPORT QObject * qt_qFindChild_helper(const QObject *parent, const QString &name, const QMetaObject &mo)
Definition: qobject.cpp:1924

◆ findChildren() [1/2]

template<typename T >
QList< T > QObject::findChildren ( const QString name = QString()) const
inline

Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.

Omitting the name argument causes all object names to be matched. The search is performed recursively.

The following example shows how to find a list of child QWidget of the specified parentWidget named widgetname:

This example returns all QPushButtons that are children of parentWidget:

See also
findChild()

Definition at line 162 of file qobject.h.

Referenced by QStateMachinePrivate::applyProperties(), QMetaObject::connectSlotsByName(), QWindowsStyle::eventFilter(), QEventDispatcherMac::flush(), qFindChildren(), QScript::qobjectProtoFuncFindChildren(), QAbstractButtonPrivate::queryButtonList(), QAccessibleApplication::relationTo(), QStyleSheetStyle::repolish(), QWorkspaceChild::setActive(), QWidget::setTabOrder(), and QStateMachinePrivate::unregisterAllTransitions().

163  {
164  QList<T> list;
165  union {
166  QList<T> *typedList;
167  QList<void *> *voidList;
168  } u;
169  u.typedList = &list;
170  qt_qFindChildren_helper(this, aName, 0, reinterpret_cast<T>(0)->staticMetaObject, u.voidList);
171  return list;
172  }
static const QMetaObject staticMetaObject
This variable stores the meta-object for the class.
Definition: qobject.h:128
quint16 u
Q_CORE_EXPORT void qt_qFindChildren_helper(const QObject *parent, const QString &name, const QRegExp *re, const QMetaObject &mo, QList< void *> *list)
Definition: qobject.cpp:1900
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ findChildren() [2/2]

template<typename T >
QList<T> QObject::findChildren ( const QRegExp re) const
inline

Definition at line 176 of file qobject.h.

177  {
178  QList<T> list;
179  union {
180  QList<T> *typedList;
181  QList<void *> *voidList;
182  } u;
183  u.typedList = &list;
184  qt_qFindChildren_helper(this, QString(), &re, reinterpret_cast<T>(0)->staticMetaObject, u.voidList);
185  return list;
186  }
static const QMetaObject staticMetaObject
This variable stores the meta-object for the class.
Definition: qobject.h:128
quint16 u
The QString class provides a Unicode character string.
Definition: qstring.h:83
Q_CORE_EXPORT void qt_qFindChildren_helper(const QObject *parent, const QString &name, const QRegExp *re, const QMetaObject &mo, QList< void *> *list)
Definition: qobject.cpp:1900
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ inherits()

bool QObject::inherits ( const char *  className) const
inline

Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.

A class is considered to inherit itself.

Example:

QTimer *timer = new QTimer; // QTimer inherits QObject
timer->inherits("QTimer"); // returns true
timer->inherits("QObject"); // returns true
timer->inherits("QAbstractButton"); // returns false
// QVBoxLayout inherits QObject and QLayoutItem
layout->inherits("QObject"); // returns true
layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)

If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.

See also
metaObject(), qobject_cast()

Definition at line 275 of file qobject.h.

Referenced by QMacStylePrivate::addWidget(), axc_FilterProc(), QX11Data::clipboardWaitForEvent(), QPlastiqueStyle::drawComplexControl(), QCleanlooksStyle::drawComplexControl(), QWindowsXPStyle::drawComplexControl(), QPlastiqueStyle::drawControl(), QWindowsCEStyle::drawPrimitive(), QWindowsMobileStyle::drawPrimitive(), QPlastiqueStyle::drawPrimitive(), QCleanlooksStyle::drawPrimitive(), QWindowsXPStyle::drawPrimitive(), QWindowsStyle::drawPrimitive(), QGtkStyle::drawPrimitive(), QApplication::font(), QToolButton::initStyleOption(), QWindowsXPStylePrivate::isItemViewDelegateLineEdit(), isTreeView(), killTimer(), QAccessibleMdiSubWindow::navigate(), QApplication::palette(), QWindowsXPStyle::pixelMetric(), QPlastiqueStyle::pixelMetric(), QWindowsStyle::pixelMetric(), QMacStyle::pixelMetric(), QWindowsXPStyle::polish(), QWindowsVistaStyle::polish(), QPlastiqueStyle::polish(), QCleanlooksStyle::polish(), qt_aqua_get_known_size(), qt_find_obj_child(), qt_set_x11_resources(), qt_x11_recreateWidget(), QMacStylePrivate::removeWidget(), QWidget::setAttribute(), QStyledItemDelegate::setEditorData(), QItemDelegate::setEditorData(), QWidget::setFocus(), QApplication::setFont(), setObjectName(), QApplicationPrivate::setPalette_helper(), QGraphicsView::setupViewport(), QFocusFrame::setWidget(), QStyleSheetStyle::sizeFromContents(), QCleanlooksStyle::styleHint(), QMacStyle::styleHint(), QCommonStyle::subControlRect(), QWindowsXPStyle::unpolish(), QPlastiqueStyle::unpolish(), QCleanlooksStyle::unpolish(), QAuthDevice::writeData(), and QApplicationPrivate::x11_apply_settings().

276  { return const_cast<QObject *>(this)->qt_metacast(classname) != 0; }
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111

◆ installEventFilter()

void QObject::installEventFilter ( QObject filterObj)

Installs an event filter filterObj on this object.

For example:

monitoredObj->installEventFilter(filterObj);

An event filter is an object that receives all events that are sent to this object. The filter can either stop the event or forward it to this object. The event filter filterObj receives events via its eventFilter() function. The eventFilter() function must return true if the event should be filtered, (i.e. stopped); otherwise it must return false.

If multiple event filters are installed on a single object, the filter that was installed last is activated first.

Here's a KeyPressEater class that eats the key presses of its monitored objects:

class KeyPressEater : public QObject
{
...
protected:
};
bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug("Ate key press %d", keyEvent->key());
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}

And here's how to install it on two widgets:

KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
QListView *listView = new QListView(this);
pushButton->installEventFilter(keyPressEater);
listView->installEventFilter(keyPressEater);

The QShortcut class, for example, uses this technique to intercept shortcut key presses.

Warning
If you delete the receiver object in your eventFilter() function, be sure to return true. If you return false, Qt sends the event to the deleted object and the program will crash.

Note that the filtering object must be in the same thread as this object. If filterObj is in a different thread, this function does nothing. If either filterObj or this object are moved to a different thread after calling this function, the event filter will not be called until both objects have the same thread affinity again (it is not removed).

See also
removeEventFilter(), eventFilter(), event()

Definition at line 2070 of file qobject.cpp.

Referenced by QDataWidgetMapper::addMapping(), QMeeGoGraphicsSystemSwitchHandler::addWidget(), QMacStylePrivate::addWidget(), QWorkspace::addWindow(), QMdiAreaPrivate::appendChild(), QAbstractItemView::commitData(), QAbstractItemViewPrivate::editor(), QScrollArea::event(), QDataWidgetMapperPrivate::flipEventFilters(), QMenuBarPrivate::handleReparent(), QDeclarativeLoaderPrivate::initResize(), QAxServerBase::internalActivate(), QWindowsStyle::polish(), QMotifStyle::polish(), QPlastiqueStyle::polish(), QBalloonTip::QBalloonTip(), QBBInputContext::QBBInputContext(), QMdiArea::QMdiArea(), QWidgetResizeHandler::QWidgetResizeHandler(), QWorkspaceChild::QWorkspaceChild(), QX11EmbedWidget::QX11EmbedWidget(), QStateMachinePrivate::registerEventTransition(), QWorkspaceChild::setActive(), QScriptDebugger::setCodeWidget(), QMenuBar::setCornerWidget(), QComboBoxPrivateContainer::setItemView(), QCalendarWidgetPrivate::setNavigatorEnabled(), QCompleter::setPopup(), QMdiSubWindowPrivate::setSizeGrip(), QFocusFrame::setWidget(), QScrollArea::setWidget(), QMdiSubWindow::setWidget(), QGraphicsProxyWidgetPrivate::setWidget_helper(), QMdiSubWindowPrivate::showButtonsInMenuBar(), QSizeGripPrivate::updateTopLevelWidget(), and QWSEmbedWidgetPrivate::updateWindow().

2071 {
2072  Q_D(QObject);
2073  if (!obj)
2074  return;
2075  if (d->threadData != obj->d_func()->threadData) {
2076  qWarning("QObject::installEventFilter(): Cannot filter events for objects in a different thread.");
2077  return;
2078  }
2079 
2080  // clean up unused items in the list
2081  d->eventFilters.removeAll((QObject*)0);
2082  d->eventFilters.removeAll(obj);
2083  d->eventFilters.prepend(obj);
2084 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)

◆ isWidgetType()

bool QObject::isWidgetType ( ) const
inline

Returns true if the object is a widget; otherwise returns false.

Calling this function is equivalent to calling inherits("QWidget"), except that it is much faster.

Definition at line 146 of file qobject.h.

Referenced by QGroupBoxPrivate::_q_setChildrenEnabled(), QGroupBox::childEvent(), QSplitter::childEvent(), classIDL(), QScriptEnginePrivate::convertValue(), CompatAccessibleFactory::create(), AccessibleFactory::create(), QPanGestureRecognizer::create(), QWinNativePanGestureRecognizer::create(), QPinchGestureRecognizer::create(), QSwipeGestureRecognizer::create(), QTapGestureRecognizer::create(), QTapAndHoldGestureRecognizer::create(), QGestureManager::deliverEvents(), QWidget::destroy(), do_size_hints(), dumpRecursive(), effectiveState(), QWidget::ensurePolished(), QScrollArea::eventFilter(), QWindowsStyle::eventFilter(), QWhatsThisPrivate::eventFilter(), getNamedAttribute(), QGestureManager::getState(), QWindowsAccessible::GetWindow(), QAccessibleApplication::indexOfChild(), QWidgetPrivate::isBackgroundInherited(), QAxServerBase::isPropertyExposed(), isServerProcess(), killTimer(), make_win_eventUPP(), QCoreApplication::notify(), QApplication::notify(), QApplicationPrivate::notify_helper(), QAction::parentWidget(), parseGeometry(), q_createNativeChildrenAndSetParent(), qSmartSpacing(), qt_grab_cursor(), qt_mac_unregister_widget(), qt_mac_update_widget_position(), qt_set_windows_updateScrollBar(), QMacSwipeGestureRecognizer::recognize(), QMacPinchGestureRecognizer::recognize(), QDeclarativeVME::run(), sendResizeEvents(), QWidget::setLayout(), setObjectName(), QLayout::update(), QAccessible::updateAccessibility(), and QLayout::widgetEvent().

146 { return d_ptr->isWidget; }
uint isWidget
Definition: qobject.h:95
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320

◆ killTimer()

void QObject::killTimer ( int  id)

Kills the timer with timer identifier, id.

The timer identifier is returned by startTimer() when a timer event is started.

See also
timerEvent(), startTimer()

Definition at line 1650 of file qobject.cpp.

Referenced by QUnixSocket::abort(), QStateMachine::cancelDelayedEvent(), QDBusConnectionPrivate::customEvent(), QAxHostWidget::event(), QStateMachine::event(), QPlastiqueStyle::eventFilter(), QMotifStyle::eventFilter(), QTestEventLoop::exitLoop(), findRealWindow(), QAxHostWidget::focusOutEvent(), QFontCache::increaseCost(), QGLBlurTextureCache::insertBlurTextureInfo(), QLineControl::internalInsert(), QMenu::mouseMoveEvent(), QLineControl::processEvent(), QLineControl::processMouseEvent(), qDBusRemoveTimeout(), QTapAndHoldGestureRecognizer::recognize(), QTapAndHoldGestureRecognizer::reset(), QLineControl::resetCursorBlinkTimer(), QMdiSubWindow::resizeEvent(), restartXdndDropExpiryTimer(), QLineControl::setCursorBlinkPeriod(), QTimer::setInterval(), QTimeLine::setPaused(), QMacAnimateCursor::start(), QMacAnimateCursor::stop(), QTimer::stop(), QTimeLine::stop(), QWindowsStylePrivate::stopAnimation(), QBalloonTip::timerEvent(), QMdiSubWindow::timerEvent(), QAbstractSpinBox::timerEvent(), QTableView::timerEvent(), QMdiArea::timerEvent(), QCoreFuriCuri::timerEvent(), QMenu::timerEvent(), QScriptDebugger::timerEvent(), QTreeView::timerEvent(), QPMCache::timerEvent(), QMacStylePrivate::timerEvent(), QFontCache::timerEvent(), QSingleShotTimer::timerEvent(), QGLBlurTextureCache::timerEvent(), QLineControl::timerEvent(), QDeclarativePixmapStore::timerEvent(), QClipboardINCRTransaction::x11Event(), and QSingleShotTimer::~QSingleShotTimer().

1651 {
1652  Q_D(QObject);
1653  if (d->threadData->eventDispatcher)
1654  d->threadData->eventDispatcher->unregisterTimer(id);
1655 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

◆ metaObject()

QMetaObject * QObject::metaObject ( ) const
virtual

Returns a pointer to the meta-object of this object.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have no pointer to an actual object instance but still want to access the meta-object of a class, you can use staticMetaObject .

Example:

QObject *obj = new QPushButton;
obj->metaObject()->className(); // returns "QPushButton"
QPushButton::staticMetaObject.className(); // returns "QPushButton"
See also
staticMetaObject

Reimplemented in QScript::QObjectConnectionManager, QDBusInterface, QSignalEventGenerator, QAxWidget, and QAxObject.

Referenced by QLayout::activate(), QMetaObject::activate(), ActiveObject::ActiveObject(), QAxServerBase::ActiveXProc(), QDBusAdaptorConnector::addAdaptor(), QGraphicsLayoutPrivate::addChildLayoutItem(), QLayout::addChildWidget(), QAccessibleWidget::addControllingSignal(), QGraphicsScene::addItem(), QAxScriptManager::addObject(), QScript::QObjectConnectionManager::addSignalHandler(), QState::addTransition(), QDeclarativeWatcher::addWatch(), QGridLayout::addWidget(), QDeclarativeListReference::append(), QMacStylePrivate::aquaSizeConstrain(), QStyleSheetStyleSelector::attribute(), QDeclarativePropertyPrivate::binding(), QDeclarativeEngineDebugService::buildObjectDump(), QDeclarativeCompiler::buildValueTypeProperty(), QDeclarativeEnginePrivate::cache(), QDeclarativeObjectMethodScriptClass::callOverloaded(), QDeclarativeObjectMethodScriptClass::callPrecise(), QDBusAbstractInterface::callWithArgumentList(), QMetaObject::cast(), check_method_code(), check_parent_thread(), check_signal_macro(), QCoreApplicationPrivate::checkReceiverThread(), checkWidget(), QAxFactory::classID(), QDeclarativeCompiler::compileAlias(), QDeclarativeObjectMethodScriptClass::connect(), QDeclarativePropertyPrivate::connect(), connect(), QMetaObject::connect(), QDeclarativeVMEMetaObject::connectAlias(), QDBusAdaptorConnector::connectAllSignals(), QDeclarativeProperty::connectNotifySignal(), ShaderEffectItem::connectPropertySignals(), QMetaObject::connectSlotsByName(), QDeclarativeContext::contextProperty(), QDeclarativeEnginePrivate::createCache(), QLayoutPrivate::createSpacerItem(), QDeclarativeItemPrivate::data_append(), QDeclarativeMetaType::defaultMethod(), QDeclarativeMetaType::defaultProperty(), QDeclarativeNotifierEndpoint::disconnect(), QDeclarativeObjectMethodScriptClass::disconnect(), disconnect(), QMetaObject::disconnect(), QDBusAdaptorConnector::disconnectAllSignals(), QMetaObject::disconnectOne(), QWindowsStyle::drawPrimitive(), dumpObjectInfo(), dumpRecursive(), QProxyStylePrivate::ensureBaseStyle(), QWidget::ensurePolished(), QApplicationPrivate::enterModal_sys(), err_method_notfound(), QAxFactory::eventsID(), QCoreApplication::exec(), QScript::QtFunction::execute(), QScript::QtPropertyFunction::execute(), QAxFactory::exposeToSuperClass(), QDeclarativePropertyPrivate::findAliasTarget(), QDeclarativeCompiledBindingsPrivate::findproperty(), QDBusConnectionPrivate::findSlot(), QApplication::font(), fromScriptValue(), QScript::QObjectDelegate::getOwnPropertyNames(), QApplicationPrivate::globalEventProcessor(), QStateMachinePrivate::handleTransitionSignal(), QDeclarativeProperty::hasNotifySignal(), QAxFactory::hasStockEvents(), hasValidSignal(), QNetworkReply::ignoreSslErrors(), QDeclarativeBoundSignal::init(), QNetworkReplyImplPrivate::initCacheSaveDevice(), QDeclarativeVisualDataModelDataMetaObject::initialValue(), QDeclarativePropertyPrivate::initProperty(), QAxFactory::interfaceID(), QAxServerBase::internalActivate(), QMetaObject::invokeMethod(), QTest::invokeMethod(), QDeclarativeProperty::isDesignable(), QAxServerBase::isPropertyExposed(), QDeclarativeKeysAttached::keyPressed(), keyTypeForObject(), QStyle::layoutSpacing(), QApplicationPrivate::leaveModal_sys(), make_widget_eventUPP(), QDataWidgetMapper::mappedPropertyName(), QMetaObjectPrivate::memberIndexes(), QDeclarativeProxyMetaObject::metaCall(), QDeclarativeVMEMetaObject::metaCall(), QScript::QtFunction::metaObject(), QDeclarativeProperty::method(), QDeclarativeProperty::name(), QDeclarativePropertyCache::Data::name(), QStyleSheetStyle::nativeFrameWidth(), QDeclarativeEngineDebugService::objectData(), QDeclarativeDebugService::objectToString(), operator<<(), QDeclarativeBindingCompilerPrivate::Result::operator==(), QApplication::palette(), parentWidget(), QStyleSheetStyle::polish(), QDeclarativeValueTypeScriptClass::property(), QDeclarativeObjectMethodScriptClass::property(), QDeclarativeProperty::property(), QDeclarativeObjectScriptClass::property(), QDeclarativePropertyCache::property(), property(), QDeclarativeEngineDebugService::propertyData(), QDeclarativeObjectScriptClass::propertyNames(), QDeclarativeProperty::propertyTypeName(), ptr(), qax_generateDocumentation(), QAxServerBase::QAxServerBase(), qDBusInterfaceInObject(), qDBusIntrospectObject(), qDBusPropertyGet(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), QDeclarativeOpenMetaObject::QDeclarativeOpenMetaObject(), QDeclarativeVMEMetaObject::QDeclarativeVMEMetaObject(), QTest::qExec(), QTest::qInvokeTestMethods(), QIODevice::QIODevice(), QLayout::QLayout(), qmlExecuteDeferred(), QScript::qobjectProtoFuncToString(), QTest::qPrintDataTags(), QTest::qPrintTestSlots(), QRenderRule::QRenderRule(), QScriptDBusInterfaceConstructor::QScriptDBusInterfaceConstructor(), QScriptDBusMessageConstructor::QScriptDBusMessageConstructor(), QTest::qSignalDumperCallback(), QTest::qSignalDumperCallbackEndSignal(), QTest::qSignalDumperCallbackSlot(), QSignalSpy::QSignalSpy(), qt_adopted_thread_watcher_function(), qt_aqua_get_known_size(), qt_mac_send_modifiers_changed(), QDBusAbstractInterfaceBase::qt_metacall(), qt_nograb(), QTest::qtest_qParseArgs(), QDeclarativeValueTypeScriptClass::queryProperty(), queued_activate(), QVariantToVARIANT(), QDeclarativePropertyPrivate::readValueProperty(), QAxFactory::registerActiveObject(), QStateMachinePrivate::registerSignalTransition(), QDBusAdaptorConnector::relay(), QDBusAdaptorConnector::relaySlot(), QCoreApplicationPrivate::removePostedEvent(), QScript::QObjectConnectionManager::removeSignalHandler(), QGraphicsLayoutPrivate::reparentChildItems(), QDeclarativeEngineDebugService::resetBinding(), QDeclarativeCompiledBindingsPrivate::run(), QScriptEnginePrivate::scriptConnect(), QScriptEnginePrivate::scriptDisconnect(), QKeyMapper::sendKeyEvent(), QDBusAbstractAdaptor::setAutoRelaySignals(), QDeclarativePropertyPrivate::setBinding(), QDeclarativeData::setBindingBit(), QDeclarativePropertyPrivate::setBindingNoEnable(), QNetworkReplyImplPrivate::setCachingEnabled(), QDeclarativeContext::setContextProperty(), QStyledItemDelegate::setEditorData(), QItemDelegate::setEditorData(), QWidget::setFocusProxy(), QGraphicsWidget::setLayout(), QWidget::setLayout(), QStyledItemDelegate::setModelData(), QItemDelegate::setModelData(), QStyleSheetStyle::setProperties(), QDeclarativeValueTypeScriptClass::setProperty(), setProperty(), QDBusPendingCallPrivate::setReplyCallback(), QDeclarativeAbstractAnimation::setRunning(), QNetworkReply::setSslConfiguration(), QDeclarativeBehavior::setTarget(), setupDBusInterface(), QNetworkReply::sslConfiguration(), QThreadPrivate::start(), QmlJSDebugger::AbstractLiveEditTool::titleForItem(), QDeclarativeObjectScriptClass::tostring(), QAxServerBase::UIDeactivate(), QAccessible::updateAccessibility(), QPropertyAnimationPrivate::updateMetaProperty(), QGLContext::updatePaintDevice(), QAxFactory::validateLicenseKey(), QDeclarativeValueTypeFactory::valueType(), VARIANTToQVariant(), QGraphicsView::viewportEvent(), QDeclarativePropertyPrivate::write(), writeProperty(), and QDeclarativeInfo::~QDeclarativeInfo().

◆ moveToThread()

void QObject::moveToThread ( QThread targetThread)

Changes the thread affinity for this object and its children.

The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives. For example:

myObject->moveToThread(QApplication::instance()->thread());

If targetThread is zero, all event processing for this object and its children stops.

Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread.

Warning
This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.
See also
thread()

Definition at line 1458 of file qobject.cpp.

Referenced by QDBusConnectionPrivate::checkThread(), connManager(), QAdoptedThread::createThreadForAdoption(), QCoreApplication::init(), QNetworkConfigurationManagerPrivate::initialize(), QGLSignalProxy::instance(), QScriptDebuggerBackendPrivate::postEvent(), QNetworkAccessHttpBackend::postRequest(), QDBusDefaultConnection::QDBusDefaultConnection(), QDeclarativePixmapReader::QDeclarativePixmapReader(), QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(), QDnotifySignalThread::QDnotifySignalThread(), QFactoryLoader::QFactoryLoader(), QFileSystemWatcherEngine::QFileSystemWatcherEngine(), QHostInfoLookupManager::QHostInfoLookupManager(), QInotifyFileSystemWatcherEngine::QInotifyFileSystemWatcherEngine(), QPollingFileSystemWatcherEngine::QPollingFileSystemWatcherEngine(), QWaylandScreen::QWaylandScreen(), QWindowsFileSystemWatcherEngineThread::QWindowsFileSystemWatcherEngineThread(), QDBusConnectionPrivate::sendWithReplyAsync(), and QNetworkConfigurationManagerPrivate::updateConfigurations().

1459 {
1460  Q_D(QObject);
1461 
1462  if (d->threadData->thread == targetThread) {
1463  // object is already in this thread
1464  return;
1465  }
1466 
1467  if (d->parent != 0) {
1468  qWarning("QObject::moveToThread: Cannot move objects with a parent");
1469  return;
1470  }
1471  if (d->isWidget) {
1472  qWarning("QObject::moveToThread: Widgets cannot be moved to a new thread");
1473  return;
1474  }
1475 
1476  QThreadData *currentData = QThreadData::current();
1477  QThreadData *targetData = targetThread ? QThreadData::get2(targetThread) : new QThreadData(0);
1478  if (d->threadData->thread == 0 && currentData == targetData) {
1479  // one exception to the rule: we allow moving objects with no thread affinity to the current thread
1480  currentData = d->threadData;
1481  } else if (d->threadData != currentData) {
1482  qWarning("QObject::moveToThread: Current thread (%p) is not the object's thread (%p).\n"
1483  "Cannot move to target thread (%p)\n",
1484  currentData->thread, d->threadData->thread, targetData->thread);
1485 
1486 #ifdef Q_WS_MAC
1487  qWarning("On Mac OS X, you might be loading two sets of Qt binaries into the same process. "
1488  "Check that all plugins are compiled against the right Qt binaries. Export "
1489  "DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded.");
1490 #endif
1491 
1492  return;
1493  }
1494 
1495  // prepare to move
1496  d->moveToThread_helper();
1497 
1498  QOrderedMutexLocker locker(&currentData->postEventList.mutex,
1499  &targetData->postEventList.mutex);
1500 
1501  // keep currentData alive (since we've got it locked)
1502  currentData->ref();
1503 
1504  // move the object
1505  d_func()->setThreadData_helper(currentData, targetData);
1506 
1507  locker.unlock();
1508 
1509  // now currentData can commit suicide if it wants to
1510  currentData->deref();
1511 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
void deref()
Definition: qthread.cpp:125
static QThreadData * get2(QThread *thread)
Definition: qthread_p.h:219
QMutex mutex
Definition: qthread_p.h:109
Q_CORE_EXPORT void qWarning(const char *,...)
QPostEventList postEventList
Definition: qthread_p.h:266
void ref()
Definition: qthread.cpp:117
static QThreadData * current()
QThread * thread
Definition: qthread_p.h:260

◆ objectName()

QString QObject::objectName ( ) const

Referenced by QLayout::activate(), QLayout::addChildLayout(), QGraphicsLayoutPrivate::addChildLayoutItem(), QLayout::addChildWidget(), QDockAreaLayout::addDockWidget(), QFileSystemWatcher::addPaths(), QGridLayout::addWidget(), QMacStylePrivate::aquaSizeConstrain(), QDeclarativeEngineDebugService::buildObjectList(), checkWidget(), childWidgets(), QGLShaderPrivate::compile(), AccessibleFactory::create(), QLayoutPrivate::createSpacerItem(), DllCanUnloadNow(), dumpObjectInfo(), QAccessibleAbstractScrollArea::elementType(), QApplicationPrivate::enterModal_sys(), QGLEngineSharedShaders::findProgramInCache(), QApplicationPrivate::globalEventProcessor(), QFormLayout::insertRow(), QSplitterPrivate::insertWidget(), QStyleSheetStyle::isNaturalChild(), QApplicationPrivate::leaveModal_sys(), QGLShaderProgram::link(), make_widget_eventUPP(), QDeclarativeEngineDebugService::messageReceived(), QDeclarativeDebugService::objectToString(), operator<<(), QAccessibleItemView::QAccessibleItemView(), QAxHostWidget::QAxHostWidget(), QLayout::QLayout(), QMainWindowLayout::QMainWindowLayout(), QPlaceHolderItem::QPlaceHolderItem(), qt_adopted_thread_watcher_function(), qt_nograb(), QtWndProc(), QDBusAdaptorConnector::relaySlot(), QGraphicsLayoutPrivate::reparentChildItems(), QDockAreaLayout::restoreDockWidget(), QDockAreaLayoutInfo::restoreState(), QToolBarAreaLayout::restoreState(), QToolBarAreaLayout::saveState(), QKeyMapper::sendKeyEvent(), QLCDNumber::setDigitCount(), QStateMachinePrivate::setError(), QWidget::setFocusProxy(), QGraphicsWidget::setLayout(), QWidget::setLayout(), QWSDisplay::setWindowCaption(), QDockAreaLayout::splitDockWidget(), QThreadPrivate::start(), QDockAreaLayout::tabifyDockWidget(), QmlJSDebugger::AbstractLiveEditTool::titleForItem(), QGLContext::updatePaintDevice(), QWSWindowSurface::winId(), QObjectPrivate::Connection::~Connection(), and ~QObject().

◆ parent()

QObject * QObject::parent ( ) const
inline

Returns a pointer to the parent object.

See also
children()

Definition at line 273 of file qobject.h.

Referenced by QColumnViewPrivate::_q_clicked(), QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(), QLayout::addChildLayout(), QDnotifyFileSystemWatcherEngine::addPaths(), QFileSystemModelPrivate::addVisibleFiles(), QPushButtonPrivate::adjustedMenuPosition(), QWidgetPrivate::adjustFlags(), QLayout::adoptLayout(), QDeclarativeParticleMotionWander::advance(), ancestorOf(), QAbstractTextDocumentLayout::anchorAt(), QDeclarativeGraphicsWidget::anchors(), QDirModelPrivate::appendChild(), QMdiAreaPrivate::appendChild(), QPlainTextEditControl::canInsertFromMimeData(), QTextEditControl::canInsertFromMimeData(), QRubberBand::changeEvent(), QMdiSubWindow::changeEvent(), QNativeSocketEnginePrivate::checkProxy(), QToolBarLayout::checkUsePopupMenu(), QDirModelPrivate::children(), QMenu::clear(), QAbstractItemViewPrivate::clearOrRemove(), QColumnViewPrivate::closeColumns(), QDeclarativeComponentPrivate::complete(), QPanGestureRecognizer::create(), QDeclarativeBinding::createBinding(), QGraphicsScene::createItemGroup(), QPlainTextEditControl::createMimeDataFromSelection(), QTextEditControl::createMimeDataFromSelection(), QUrlModel::dataChanged(), QDeclarativeCompiledBindingsPrivate::Binding::destroy(), QDeclarativeCompiledBindingsPrivate::Binding::disconnect(), QApplicationPrivate::dispatchEnterLeave(), QGraphicsScenePrivate::dispatchHoverEvent(), QTextObject::docHandle(), QTextObject::document(), QTreeView::doItemsLayout(), QTreeView::drawBranches(), QWindowsCEStyle::drawPrimitive(), QWindowsMobileStyle::drawPrimitive(), QMacStyle::drawPrimitive(), QTreeView::drawRow(), QTreeWidget::dropEvent(), QDirModel::dropMimeData(), QListModel::dropMimeData(), QTableModel::dropMimeData(), QScriptEditExtraArea::editor(), QAbstractItemViewPrivate::editor(), QLineControl::emitCursorPositionChanged(), QWinInputContext::enablePopupChild(), QTreeModel::ensureSorted(), QTreeWidgetItemIteratorPrivate::ensureValidIterator(), QRadioButton::event(), QCheckBox::event(), QStatusBar::event(), QMdiSubWindow::event(), QGraphicsScene::event(), QWorkspace::eventFilter(), QMdiSubWindow::eventFilter(), QMenuBar::eventFilter(), QScriptDebuggerLocalsItemDelegate::eventFilter(), QCompletionEngine::filter(), findRealWindow(), QTextHtmlExporter::findUrlForImage(), QSplitterPrivate::findWidget(), QGLWindowSurface::flush(), QGraphicsWidget::focusNextPrevChild(), QDeclarativeItem::forceActiveFocus(), QAbstractTextDocumentLayout::format(), QAbstractTextDocumentLayout::formatIndex(), QGraphicsScenePrivate::gestureEventHandler(), getImage(), getPixmap(), QInputDialog::getText(), QPushButtonPrivate::hitButton(), QTableModel::index(), QDirModel::index(), QSortedModelEngine::indexHint(), QTreeView::indexRowSizeHint(), QCoreApplication::init(), QListModel::insert(), QPlainTextEditControl::insertFromMimeData(), QTextEditControl::insertFromMimeData(), QListModel::insertRows(), QModelIndex::internalId(), QWorkspaceChild::internalRaise(), QLineControl::internalSetText(), isAncestor(), QWidgetPrivate::isBackgroundInherited(), isEmbeddedTabBar(), isStandaloneTabBar(), QStandardItemModel::itemFromIndex(), QAbstractItemView::keyboardSearch(), QDeclarativeKeyNavigationAttached::keyPressed(), QMdiSubWindow::keyPressEvent(), QTreeView::keyPressEvent(), QDeclarativeKeyNavigationAttached::keyReleased(), QTreeViewPrivate::layout(), QGraphicsScenePrivate::leaveScene(), QTextDocumentWithImageResources::loadResource(), QTextControl::loadResource(), QTextDocument::loadResource(), QCompletionEngine::lookupCache(), QAbstractStatePrivate::machine(), QCompletionModel::mapToSource(), QScript::QObjectConnection::mark(), QAbstractItemModel::match(), QCompletionEngine::matchHint(), QScriptDebuggerPrivate::maybeDelete(), QMdiSubWindow::mdiArea(), QListModel::mimeData(), QTableModel::mimeData(), QListModel::mimeTypes(), QTableModel::mimeTypes(), QMdiSubWindow::minimumSizeHint(), QColumnViewGrip::mouseDoubleClickEvent(), QMdiSubWindow::mouseDoubleClickEvent(), QMdiSubWindow::mouseMoveEvent(), QWorkspaceTitleBar::mouseMoveEvent(), QMdiSubWindow::mousePressEvent(), QGroupBox::mouseReleaseEvent(), QMdiSubWindow::mouseReleaseEvent(), QMdiSubWindow::moveEvent(), QColumnViewGrip::moveGrip(), QWidget::nativeParentWidget(), QAccessibleWidget::navigate(), QDeclarativeObjectScriptClass::newQObject(), QTreeWidgetItemIteratorPrivate::next(), QDirModelPrivate::node(), QFileSystemModelPrivate::node(), QDeclarativeEngineDebugService::objectCreated(), QDeclarativeEngineDebugService::objectData(), QWidgetPrivate::paintBackground(), QToolBoxButton::paintEvent(), QMdiSubWindow::paintEvent(), CloseButton::paintEvent(), QTreeModel::parent(), parent(), QAccessibleWidget::parentObject(), QAbstractState::parentState(), QShortcut::parentWidget(), QAction::parentWidget(), QWidget::parentWidget(), QNlaThread::parseBlob(), QNlaThread::parseQuerySet(), QCompleter::pathFromIndex(), QMacStyle::pixelMetric(), QWindowsXPStyle::polish(), QPlastiqueStyle::polish(), QDBusAdaptorConnector::polish(), QToolButtonPrivate::popupTimerDone(), QTreeWidgetItemIteratorPrivate::previous(), QThread::priority(), QAction::QAction(), QBoxLayout::QBoxLayout(), QColorShower::QColorShower(), QComboBox::QComboBox(), QCopChannel::QCopChannel(), qDBusFindAdaptorConnector(), qDBusNewConnection(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), QDeclarativeDebugClient::QDeclarativeDebugClient(), QDeclarativeKeysAttached::QDeclarativeKeysAttached(), QDeclarativeListModel::QDeclarativeListModel(), QDefaultItemEditorFactory::QDefaultItemEditorFactory(), QDial::QDial(), QDialog::QDialog(), QExceptionNotifier::QExceptionNotifier(), QFrame::QFrame(), QFtp::QFtp(), QGLOverlayWidget::QGLOverlayWidget(), QGridLayout::QGridLayout(), QHttpNetworkConnection::QHttpNetworkConnection(), QLabel::QLabel(), QLineEdit::QLineEdit(), QMainWindow::QMainWindow(), QMenuBar::QMenuBar(), QMessageBoxPrivate::QMessageBoxPrivate(), QAxObject::qObject(), QAxWidget::qObject(), QObject(), QReadNotifier::QReadNotifier(), QScrollBar::QScrollBar(), QSignalMapper::QSignalMapper(), QSizeGrip::QSizeGrip(), QSlider::QSlider(), qSmartSpacing(), QSocketNotifier::QSocketNotifier(), QSound::QSound(), QSpinBox::QSpinBox(), QSplitterHandle::QSplitterHandle(), QSignalEventGenerator::qt_metacall(), QTabWidget::QTabWidget(), QTextBrowser::QTextBrowser(), QTextEdit::QTextEdit(), QTimer::QTimer(), QToolBar::QToolBar(), QToolBarLayout::QToolBarLayout(), QToolButton::QToolButton(), QTranslator::QTranslator(), QTreeModel::QTreeModel(), QTreeWidgetItemIterator::QTreeWidgetItemIterator(), QAbstractButtonPrivate::queryButtonList(), QUnixPrintWidgetPrivate::QUnixPrintWidgetPrivate(), QValidator::QValidator(), QWhatsThis::QWhatsThis(), QWidget::QWidget(), QWorkspace::QWorkspace(), QWriteNotifier::QWriteNotifier(), QWSServer::QWSServer(), QSplitterPrivate::recalc(), QAccessibleWidget::relationTo(), QDBusAdaptorConnector::relay(), QDBusAdaptorConnector::relaySlot(), QDirModel::remove(), QFileSystemModelPrivate::removeNode(), QFileSystemModelPrivate::removeVisibleFile(), QTextDocumentWithImageResources::requestFinished(), QMdiSubWindow::resizeEvent(), QExpandingLineEdit::resizeToContents(), QBBScreen::resizeWindows(), QDirModel::rmdir(), QAbstractItemView::rowsAboutToBeRemoved(), QCompletionEngine::saveInCache(), QTreeView::scrollTo(), QTreeViewPrivate::select(), QColumnView::selectAll(), QItemSelectionModel::selectedColumns(), QItemSelectionModel::selectedRows(), QPrintDialogPrivate::selectPrinter(), QInputContext::sendEvent(), QDBusContextPrivate::set(), QGraphicsScene::setActiveWindow(), QDBusAbstractAdaptor::setAutoRelaySignals(), QPrintPropertiesDialog::setCups(), QStackedLayout::setCurrentIndex(), QFileSystemModel::setData(), QTableModel::setData(), QAction::setFont(), QTableModel::setHorizontalHeaderItem(), QAbstractButton::setIconSize(), QTableModel::setItem(), QTableModel::setItemData(), QWidget::setLayout(), QPageSetupWidget::setRightMargin(), QApplication::setStyle(), QMdiSubWindow::setSystemMenu(), QTableModel::setVerticalHeaderItem(), QGraphicsProxyWidgetPrivate::setWidget_helper(), QMessageBox::setWindowModality(), QMdiSubWindow::showEvent(), QWidget::showFullScreen(), QWidget::showMaximized(), QWidget::showMinimized(), QWidget::showNormal(), QMdiSubWindow::showShaded(), QAbstractItemModel::sibling(), QMacStyle::sizeFromContents(), QStateMachinePrivate::stateEntryLessThan(), QStateMachinePrivate::stateExitLessThan(), QListModel::supportedDropActions(), QTableModel::supportedDropActions(), QTableModel::tableIndex(), QBoxLayout::takeAt(), QFormLayout::takeAt(), QGridLayoutPrivate::takeAt(), QWidget::testAttribute(), QPlastiqueStyle::unpolish(), QLayout::update(), QDeclarativeCompiledBindingsPrivate::Binding::update(), QAbstractItemViewPrivate::updateEditorData(), QMenuBarPrivate::updateGeometries(), QWidgetPrivate::updateGeometry_helper(), QDeclarativeGradientStop::updateGradient(), QStyleSheetStyle::updateStyleSheetFont(), QTreeModel::view(), QMdiArea::viewportEvent(), QHeaderViewPrivate::viewSectionSizeHint(), QListView::visualRegionForSelection(), QTreeView::visualRegionForSelection(), QAxScriptSite::window(), QX11EmbedWidgetPrivate::xEmbedWidget(), ObjectData::~ObjectData(), QApplication::~QApplication(), QComboBoxPrivate::~QComboBoxPrivate(), QDeclarativeConnections::~QDeclarativeConnections(), QDeclarativePackageAttached::~QDeclarativePackageAttached(), QScript::QObjectDelegate::~QObjectDelegate(), QObjectPrivate::~QObjectPrivate(), and QPPDOptionsEditor::~QPPDOptionsEditor().

273 { return d_ptr->parent; }
QObject * parent
Definition: qobject.h:92
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320

◆ property()

QVariant QObject::property ( const char *  name) const

Returns the value of the object's name property.

If no such property exists, the returned variant is invalid.

Information about all available properties is provided through the metaObject() and dynamicPropertyNames().

See also
setProperty(), QVariant::isValid(), metaObject(), dynamicPropertyNames()

Definition at line 3807 of file qobject.cpp.

Referenced by QNetworkManagerInterfaceDeviceWireless::activeAccessPoint(), QNetworkManagerInterface::activeConnections(), QSocks5SocketEngine::bind(), QNetworkManagerInterfaceDeviceWireless::bitrate(), QNetworkManagerInterfaceDeviceWired::carrier(), ShaderEffectItem::changeSource(), QX11Data::clipboardWaitForEvent(), QDataWidgetMapperPrivate::commit(), QDeclarativeCompiledBindings::configBinding(), QNetworkManagerConnectionActive::connection(), QFtpDTP::connectToHost(), QFtpPI::connectToHost(), QDeclarativeContext::contextProperty(), QAccessibleAbstractSpinBox::currentValue(), QNetworkManagerConnectionActive::defaultRoute(), QDeclarativeAction::deleteFromBinding(), QNetworkManagerConnectionActive::devices(), QNetworkManagerInterfaceDevice::deviceType(), QNetworkManagerIp4Config::domains(), QWindowsVistaStyle::drawComplexControl(), QWindowsVistaStyle::drawControl(), QWindowsVistaStyle::drawPrimitive(), QWizard::field(), QDeclarativeCompiledBindingsPrivate::findproperty(), QNetworkManagerInterfaceAccessPoint::flags(), QNetworkManagerInterfaceAccessPoint::frequency(), QXlibClipboard::getDataInFormat(), QOfonoManagerInterface::getProperty(), QConnmanManagerInterface::getProperty(), QOfonoModemInterface::getProperty(), QOfonoNetworkRegistrationInterface::getProperty(), QOfonoNetworkOperatorInterface::getProperty(), QOfonoSimInterface::getProperty(), QOfonoDataConnectionManagerInterface::getProperty(), QOfonoPrimaryDataContextInterface::getProperty(), QOfonoSmsInterface::getProperty(), QApplicationPrivate::globalEventProcessor(), QNetworkManagerInterfaceAccessPoint::hwAddress(), QNetworkManagerInterfaceDeviceWired::hwAddress(), QNetworkManagerInterfaceDeviceWireless::hwAddress(), QWizardPrivate::init(), QHttpSocketEngine::initialize(), QDeclarativeVisualDataModelDataMetaObject::initialValue(), QDBusAbstractInterface::internalPropGet(), QAxServerBase::Invoke(), QNetworkManagerInterfaceDevice::ip4Address(), QNetworkManagerInterfaceDevice::ip4config(), QWizardPage::isComplete(), QAxServerBase::isPropertyExposed(), QInputDialogSpinBox::keyPressEvent(), QInputDialogDoubleSpinBox::keyPressEvent(), QTcpServer::listen(), QAxServerBase::Load(), QHostInfo::lookupHost(), QNetworkManagerInterfaceAccessPoint::maxBitrate(), QAccessibleAbstractSpinBox::maximumValue(), QDeclarativeEngineDebugService::messageReceived(), QJSDebugService::messageReceived(), QAccessibleAbstractSpinBox::minimumValue(), QNetworkManagerInterfaceAccessPoint::mode(), QNetworkManagerInterfaceDeviceWireless::mode(), QNetworkManagerInterfaceDevice::networkInterface(), QAxEventSink::OnChanged(), QNetworkAccessFtpBackend::open(), parentWidget(), QNetworkAccessHttpBackend::postRequest(), QTextControlPrivate::rectForPosition(), QStateMachinePrivate::registerRestorable(), QTextEditPrivate::relayoutDocument(), QDeclarativeEngineDebugService::resetBinding(), QTextEdit::resizeEvent(), QNetworkManagerInterfaceAccessPoint::rsnFlags(), QAxServerBase::Save(), send_targets_selection(), QWSServer::sendIMQuery(), QWSClient::sendPropertyNotifyEvent(), QWSClient::sendPropertyReplyEvent(), QNetworkManagerConnectionActive::serviceName(), QDeclarativeEngineDebugService::setBinding(), QStyledItemDelegate::setEditorData(), QItemDelegate::setEditorData(), QDeclarativeKeyNavigationAttached::setFocusNavigation(), QStyleSheetStyle::setGeometry(), QStyledItemDelegate::setModelData(), QItemDelegate::setModelData(), QStyleSheetStyle::setPalette(), QStyleSheetStyle::setProperties(), QTcpServer::setSocketDescriptor(), QAbstractSocket::setSocketDescriptor(), QDeclarativeBehavior::setTarget(), QFtpDTP::setupListener(), QHttpSocketEngine::slotSocketConnected(), QNetworkManagerConnectionActive::specificObject(), QNetworkManagerInterfaceDeviceWired::speed(), QNetworkManagerInterfaceAccessPoint::ssid(), QNetworkManagerInterface::state(), QNetworkManagerInterfaceDevice::state(), QNetworkManagerConnectionActive::state(), QNetworkManagerInterfaceAccessPoint::strength(), QDeclarativeVisualDataModel::stringValue(), QMacStylePrivate::timerEvent(), QNetworkManagerInterfaceDevice::udi(), QStyleSheetStyle::unsetPalette(), ShaderEffectItem::updateEffectState(), QDeclarativeQtScriptExpression::updateGuards(), ShaderEffectItem::updateProperties(), QWizardHeader::vistaDisabled(), QAbstractSocket::waitForConnected(), QNetworkManagerInterfaceDeviceWireless::wirelessCapabilities(), QNetworkManagerInterface::wirelessEnabled(), QNetworkManagerInterface::wirelessHardwareEnabled(), and QNetworkManagerInterfaceAccessPoint::wpaFlags().

3808 {
3809  Q_D(const QObject);
3810  const QMetaObject* meta = metaObject();
3811  if (!name || !meta)
3812  return QVariant();
3813 
3814  int id = meta->indexOfProperty(name);
3815  if (id < 0) {
3816  if (!d->extraData)
3817  return QVariant();
3818  const int i = d->extraData->propertyNames.indexOf(name);
3819  return d->extraData->propertyValues.value(i);
3820  }
3821  QMetaProperty p = meta->property(id);
3822 #ifndef QT_NO_DEBUG
3823  if (!p.isReadable())
3824  qWarning("%s::property: Property \"%s\" invalid or does not exist",
3825  metaObject()->className(), name);
3826 #endif
3827  return p.read(this);
3828 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
double d
Definition: qnumeric_p.h:62
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
int indexOfProperty(const char *name) const
Finds property name and returns its index; otherwise returns -1.
const char * name
Q_CORE_EXPORT void qWarning(const char *,...)
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
QVariant read(const QObject *obj) const
Reads the property&#39;s value from the given object.
bool isReadable() const
Returns true if this property is readable; otherwise returns false.
The QMetaProperty class provides meta-data about a property.
Definition: qmetaobject.h:176
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.
QMetaProperty property(int index) const
Returns the meta-data for the property with the given index.

◆ receivers()

int QObject::receivers ( const char *  signal) const
protected

Returns the number of receivers connected to the signal.

Since both slots and signals can be used as receivers for signals, and the same connections can be made many times, the number of receivers is the same as the number of connections made from this signal.

When calling this function, you can use the SIGNAL() macro to pass a specific signal:

if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
get_the_value(&data); // expensive operation
emit valueChanged(data);
}

As the code snippet above illustrates, you can use this function to avoid emitting a signal that nobody listens to.

Warning
This function violates the object-oriented principle of modularity. However, it might be useful when you need to perform expensive initialization only if something is connected to a signal.

Definition at line 2406 of file qobject.cpp.

Referenced by QToolButtonPrivate::popupTimerDone(), and qt_mac_watchingAboutToShow().

2407 {
2408  Q_D(const QObject);
2409  int receivers = 0;
2410  if (signal) {
2411  QByteArray signal_name = QMetaObject::normalizedSignature(signal);
2412  signal = signal_name;
2413 #ifndef QT_NO_DEBUG
2414  if (!check_signal_macro(this, signal, "receivers", "bind"))
2415  return 0;
2416 #endif
2417  signal++; // skip code
2418  int signal_index = d->signalIndex(signal);
2419  if (signal_index < 0) {
2420 #ifndef QT_NO_DEBUG
2421  err_method_notfound(this, signal-1, "receivers");
2422 #endif
2423  return false;
2424  }
2425 
2426  Q_D(const QObject);
2427  QMutexLocker locker(signalSlotLock(this));
2428  if (d->connectionLists) {
2429  if (signal_index < d->connectionLists->count()) {
2430  const QObjectPrivate::Connection *c =
2431  d->connectionLists->at(signal_index).first;
2432  while (c) {
2433  receivers += c->receiver ? 1 : 0;
2434  c = c->nextConnectionList;
2435  }
2436  }
2437  }
2438  }
2439  return receivers;
2440 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
static QByteArray normalizedSignature(const char *method)
Normalizes the signature of the given method.
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
static bool check_signal_macro(const QObject *sender, const char *signal, const char *func, const char *op)
Definition: qobject.cpp:2245
#define Q_D(Class)
Definition: qglobal.h:2482
static void err_method_notfound(const QObject *object, const char *method, const char *func)
Definition: qobject.cpp:2272
int receivers(const char *signal) const
Returns the number of receivers connected to the signal.
Definition: qobject.cpp:2406
static QMutex * signalSlotLock(const QObject *o)
Definition: qobject.cpp:103
Connection * nextConnectionList
Definition: qobject_p.h:120
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101

◆ registerUserData()

uint QObject::registerUserData ( )
static
Warning
This function is not part of the public interface.

Definition at line 3989 of file qobject.cpp.

3990 {
3991  static int user_data_registration = 0;
3992  return user_data_registration++;
3993 }

◆ removeEventFilter()

void QObject::removeEventFilter ( QObject obj)

Removes an event filter object obj from this object.

The request is ignored if such an event filter has not been installed.

All event filters for this object are automatically removed when this object is destroyed.

It is always safe to remove an event filter, even during event filter activation (i.e. from the eventFilter() function).

See also
installEventFilter(), eventFilter(), event()

Definition at line 2099 of file qobject.cpp.

Referenced by QDataWidgetMapper::clearMapping(), QAbstractItemView::closeEditor(), QAbstractItemView::commitData(), QMdiAreaPrivate::disconnectSubWindow(), QScrollArea::event(), QDataWidgetMapperPrivate::flipEventFilters(), QMenuBarPrivate::handleReparent(), QAbstractItemViewPrivate::releaseEditor(), QMdiSubWindowPrivate::removeBaseWidget(), QMdiSubWindowPrivate::removeButtonsFromMenuBar(), QDataWidgetMapper::removeMapping(), QWorkspaceChild::setActive(), QComboBoxPrivateContainer::setItemView(), QCalendarWidgetPrivate::setNavigatorEnabled(), QFocusFrame::setWidget(), QGraphicsProxyWidgetPrivate::setWidget_helper(), QAxServerBase::UIDeactivate(), QWindowsStyle::unpolish(), QMotifStyle::unpolish(), QPlastiqueStyle::unpolish(), QSizeGripPrivate::updateTopLevelWidget(), QWSEmbedWidgetPrivate::updateWindow(), and QBBInputContext::~QBBInputContext().

2100 {
2101  Q_D(QObject);
2102  for (int i = 0; i < d->eventFilters.count(); ++i) {
2103  if (d->eventFilters.at(i) == obj)
2104  d->eventFilters[i] = 0;
2105  }
2106 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

◆ sender()

QObject * QObject::sender ( ) const
protected

Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0.

The pointer is valid only during the execution of the slot that calls this function from this object's thread context.

The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal.

Warning
This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.
As mentioned above, the return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.
See also
senderSignalIndex(), QSignalMapper

Definition at line 2327 of file qobject.cpp.

Referenced by QApplicationPrivate::_q_alertTimeOut(), QWSServerPrivate::_q_clientClosed(), QTabBarPrivate::_q_closeTab(), QWSServerPrivate::_q_doClient(), QWizardPrivate::_q_emitCustomButtonClicked(), QColumnViewPrivate::_q_gripMoved(), QDialogButtonBoxPrivate::_q_handleButtonDestroyed(), QTabBarPrivate::_q_scrollTabs(), QMetaObject::activate(), QScript::QObjectConnectionManager::addSignalHandler(), QWidgetAnimator::animationFinished(), QmlJSDebugger::QmlToolBar::changeAnimationSpeed(), QMetaObjectPrivate::connect(), connect(), QmlJSDebugger::LiveSelectionTool::contextMenuElementSelected(), QMetaObjectPrivate::disconnect(), disconnect(), QVGFontEngineCleaner::fontEngineDestroyed(), QSignalMapper::map(), QUnicodeControlCharacterMenu::menuActionTriggered(), QDeclarativeDataLoader::networkReplyFinished(), QDeclarativeDataLoader::networkReplyProgress(), QDeclarativePixmapReaderThreadObject::networkRequestDone(), QNetworkManagerEngine::newConnection(), QSignalTransition::QSignalTransition(), QSignalEventGenerator::qt_metacall(), QAxServerBase::qt_metacall(), QNetworkManagerEngine::removeConnection(), QScript::QObjectConnectionManager::removeSignalHandler(), QAxScriptManager::scriptError(), QSoftKeyManager::sendKeyEvent(), QSignalTransition::setSenderObject(), QGLShaderProgram::shaderDestroyed(), QMainWindowLayout::tabChanged(), QNetworkManagerEngine::updateAccessPoint(), QNetworkConfigurationManagerPrivate::updateConfigurations(), QNetworkManagerEngine::updateConnection(), QScriptBreakpointsItemDelegate::validateInput(), and ~QObject().

2328 {
2329  Q_D(const QObject);
2330 
2331  QMutexLocker locker(signalSlotLock(this));
2332  if (!d->currentSender)
2333  return 0;
2334 
2335  for (QObjectPrivate::Connection *c = d->senders; c; c = c->next) {
2336  if (c->sender == d->currentSender->sender)
2337  return d->currentSender->sender;
2338  }
2339 
2340  return 0;
2341 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
static QMutex * signalSlotLock(const QObject *o)
Definition: qobject.cpp:103
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101

◆ senderSignalIndex()

int QObject::senderSignalIndex ( ) const
protected
Since
4.8

Returns the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender(). If called outside of a slot activated by a signal, -1 is returned.

For signals with default parameters, this function will always return the index with all parameters, regardless of which was used with connect(). For example, the signal {destroyed(QObject *obj = 0)} will have two different indexes (with and without the parameter), but this function will always return the index with a parameter. This does not apply when overloading signals with different parameters.

Warning
This function violates the object-oriented principle of modularity. However, getting access to the signal index might be useful when many signals are connected to a single slot.
The return value of this function is not valid when the slot is called via a Qt::DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.
See also
sender(), QMetaObject::indexOfSignal(), QMetaObject::method()

Definition at line 2368 of file qobject.cpp.

2369 {
2370  Q_D(const QObject);
2371 
2372  QMutexLocker locker(signalSlotLock(this));
2373  if (!d->currentSender)
2374  return -1;
2375 
2376  for (QObjectPrivate::Connection *c = d->senders; c; c = c->next) {
2377  if (c->sender == d->currentSender->sender)
2378  return d->currentSender->signal;
2379  }
2380 
2381  return -1;
2382 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
static QMutex * signalSlotLock(const QObject *o)
Definition: qobject.cpp:103
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101

◆ setObjectName()

void QObject::setObjectName ( const QString name)

Definition at line 1112 of file qobject.cpp.

Referenced by QWorkspace::addWindow(), QX11Data::clipboardReadIncrementalProperty(), QFtpDTP::connectToHost(), QFileDialogPrivate::createMenuActions(), QCalendarWidgetPrivate::createNavigationBar(), QLineEdit::createStandardContextMenu(), QScriptDebugger::createStandardToolBar(), QFileDialogPrivate::createWidgets(), QWizardPrivate::ensureButton(), QMdiSubWindowPrivate::enterRubberBandMode(), QRadioButton::event(), QCheckBox::event(), QGLEngineSharedShaders::findProgramInCache(), QSplitterPrivate::findWidget(), QMainWindowLayout::getSeparatorWidget(), QGestureManager::getState(), QMdiAreaPrivate::highlightNextSubWindow(), QPushButtonPrivate::hitButton(), QWorkspaceChild::iconWidget(), QDockWidgetPrivate::init(), QAbstractSpinBoxPrivate::init(), QMessageBoxPrivate::init(), QTabWidgetPrivate::init(), QDateTimeEditPrivate::initCalendarPopup(), QToolBox::insertItem(), QSplitterPrivate::insertWidget(), QGroupBox::mouseReleaseEvent(), QPageSetupDialogPrivate::openCarbonPageLayout(), QPrintDialogPrivate::openCarbonPrintPanel(), QToolBoxButton::paintEvent(), QAuBucketQWS::QAuBucketQWS(), QAuServerNAS::QAuServerNAS(), QAuServerQWS::QAuServerQWS(), qax_create_object_wrapper(), QAxHostWidget::QAxHostWidget(), QAxScriptEngine::QAxScriptEngine(), QBoxLayout::QBoxLayout(), QCleanlooksStyle::QCleanlooksStyle(), QComboBox::QComboBox(), QCopChannel::QCopChannel(), QDesktopWidget::QDesktopWidget(), QDial::QDial(), QDialog::QDialog(), QDoubleValidator::QDoubleValidator(), QFrame::QFrame(), QFtp::QFtp(), QFtpDTP::QFtpDTP(), QFtpPI::QFtpPI(), QGridLayout::QGridLayout(), QHBoxLayout::QHBoxLayout(), QIntValidator::QIntValidator(), QLabel::QLabel(), QLineEdit::QLineEdit(), QLinuxInputKeyboardHandler::QLinuxInputKeyboardHandler(), QLinuxInputMouseHandler::QLinuxInputMouseHandler(), QMainWindow::QMainWindow(), QMainWindowLayout::QMainWindowLayout(), QMDIControl::QMDIControl(), QMenuBar::QMenuBar(), QMenuBarExtension::QMenuBarExtension(), QObject(), QPlastiqueStyle::QPlastiqueStyle(), QRegExpValidator::QRegExpValidator(), QScrollBar::QScrollBar(), QSessionManager::QSessionManager(), QSignalMapper::QSignalMapper(), QSizeGrip::QSizeGrip(), QSlider::QSlider(), QSocketNotifier::QSocketNotifier(), QSound::QSound(), QSpinBox::QSpinBox(), QSpinBoxValidator::QSpinBoxValidator(), qt_tablet_init(), qt_tablet_init_wce(), QTabWidget::QTabWidget(), QTextBrowser::QTextBrowser(), QTextEdit::QTextEdit(), QTimer::QTimer(), QToolBar::QToolBar(), QToolBarExtension::QToolBarExtension(), QToolButton::QToolButton(), QTranslator::QTranslator(), QTsLibMouseHandler::QTsLibMouseHandler(), QValidator::QValidator(), QVBoxLayout::QVBoxLayout(), QVNCIntegration::QVNCIntegration(), QWidget::QWidget(), QWorkspace::QWorkspace(), QWSLinuxInputKbPrivate::QWSLinuxInputKbPrivate(), QWSLinuxInputMousePrivate::QWSLinuxInputMousePrivate(), QWSServer::QWSServer(), QWSTtyKbPrivate::QWSTtyKbPrivate(), QAction::setFont(), QAbstractButton::setIconSize(), QMessageBox::setInformativeText(), setupOwner(), QFtpDTP::setupSocket(), QMessageBox::setWindowModality(), QWorkspacePrivate::showMaximizeControls(), QToolTip::showText(), QScriptEngineDebugger::standardWindow(), and QThreadPoolPrivate::startThread().

1113 {
1114  Q_D(QObject);
1115  bool objectNameChanged = d->declarativeData && d->objectName != name;
1116 
1117  d->objectName = name;
1118 
1119  if (objectNameChanged)
1120  d->declarativeData->objectNameChanged(d->declarativeData, this);
1121 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
const char * name

◆ setParent()

void QObject::setParent ( QObject parent)

Makes the object a child of parent.

See also
QWidget::setParent()

Definition at line 1950 of file qobject.cpp.

Referenced by QLocalServerPrivate::_q_onNewConnection(), QToolBar::actionEvent(), QLayout::addChildLayout(), QStateMachine::addState(), QState::addTransition(), QDeclarativeWatcher::addWatch(), QDeclarativeComponentPrivate::createObject(), QGraphicsProxyWidget::createProxyForChildWidget(), QDeclarativeEnginePrivate::createQmlObject(), QNetworkAccessManager::createRequest(), QLayoutPrivate::createSpacerItem(), QNetworkDiskCache::data(), QDeclarativeItemPrivate::data_append(), QDeclarativeFlickablePrivate::data_append(), QDeclarativeFlickablePrivate::data_clear(), effectiveState(), QProxyStylePrivate::ensureBaseStyle(), QGestureManager::getState(), inherits(), QLineEditPrivate::init(), QDeclarativeVisualDataModelPartsMetaObject::initialValue(), QAnimationGroup::insertAnimation(), QNetworkReplyImplPrivate::migrateBackend(), QNetworkAccessFtpBackend::open(), QNetworkAccessManager::post(), QNetworkAccessHttpBackend::postRequest(), QNetworkAccessManager::put(), QAbstractAnimation::QAbstractAnimation(), QDeclarativeBinding::QDeclarativeBinding(), QHBoxLayout::QHBoxLayout(), QLayout::QLayout(), QMainWindowLayout::QMainWindowLayout(), QObject(), QProxyStyle::QProxyStyle(), QStateMachine::QStateMachine(), QVBoxLayout::QVBoxLayout(), QWizardPrivate::recreateLayout(), QStateMachine::removeState(), QState::removeTransition(), QDeclarativeItemPrivate::resources_append(), QDeclarativeItemPrivate::resources_clear(), QNetworkAccessCacheBackend::sendCacheContents(), QNetworkAccessHttpBackend::sendCacheContents(), QDeclarativeAbstractAnimation::setGroup(), QApplication::setInputContext(), QWidget::setLayout(), QDeclarativeGraphics_DerivedObject::setParent_noEvent(), QFileDialog::setProxyModel(), QApplication::setStyle(), QApplication::setStyleSheet(), QHttpThreadDelegate::startRequest(), QApplication::style(), QAnimationGroup::takeAnimation(), QBoxLayout::takeAt(), QFormLayout::takeAt(), QGridLayoutPrivate::takeAt(), QWidget::takeLayout(), QCoreFuriCuri::timerEvent(), QDeclarativePackage::~QDeclarativePackage(), and QSingleDesktopWidget::~QSingleDesktopWidget().

1951 {
1952  Q_D(QObject);
1953  Q_ASSERT(!d->isWidget);
1954  d->setParent_helper(parent);
1955 }
double d
Definition: qnumeric_p.h:62
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

◆ setProperty()

bool QObject::setProperty ( const char *  name,
const QVariant value 
)

Sets the value of the object's name property to value.

If the property is defined in the class using ) and;.

Dynamic properties can be queried again using property() and can be removed by setting the property value to an invalid QVariant. Changing the value of a dynamic property causes a QDynamicPropertyChangeEvent to be sent to the object.

Note: Dynamic properties starting with "_q_" are reserved for internal purposes.

See also
property(), metaObject(), dynamicPropertyNames()

Definition at line 3755 of file qobject.cpp.

Referenced by QStateMachinePrivate::_q_animationFinished(), QStateMachinePrivate::applyProperties(), QSocks5SocketEngine::bind(), QWizardPage::cleanupPage(), QStyleSheetStyle::clearWidgetFont(), QFtpDTP::connectToHost(), QFtpPI::connectToHost(), QWSDisplay::convertSelection(), QSslSocketPrivate::createPlainSocket(), QDirectFBWindowSurface::createWindow(), QWindowsVistaStyle::drawComplexControl(), QWindowsVistaStyle::drawControl(), QWindowsVistaStyle::drawPrimitive(), QHttpNetworkConnectionChannel::ensureConnection(), QHttpNetworkConnectionChannel::init(), QSocks5SocketEnginePrivate::initialize(), QAbstractSocketPrivate::initSocketLayer(), QDBusAbstractInterface::internalPropSet(), QInputDialogSpinBox::keyPressEvent(), QInputDialogDoubleSpinBox::keyPressEvent(), QScriptEngine::newFunction(), QNetworkAccessFtpBackend::open(), QTipLabel::placeTip(), QDataWidgetMapperPrivate::populate(), QStyleSheetStyle::saveWidgetFont(), QAccessibleAbstractSpinBox::setCurrentValue(), QStyledItemDelegate::setEditorData(), QItemDelegate::setEditorData(), QWizard::setField(), QDirectFBWindowSurface::setGeometry(), QStyleSheetStyle::setGeometry(), QStyleSheetStyle::setProperties(), QFtpDTP::setupListener(), QNetworkAccessBackend::start(), QTipLabel::styleSheetParentDestroyed(), QStyleSheetStyle::unpolish(), and QPropertyAnimationPrivate::updateProperty().

3756 {
3757  Q_D(QObject);
3758  const QMetaObject* meta = metaObject();
3759  if (!name || !meta)
3760  return false;
3761 
3762  int id = meta->indexOfProperty(name);
3763  if (id < 0) {
3764  if (!d->extraData)
3765  d->extraData = new QObjectPrivate::ExtraData;
3766 
3767  const int idx = d->extraData->propertyNames.indexOf(name);
3768 
3769  if (!value.isValid()) {
3770  if (idx == -1)
3771  return false;
3772  d->extraData->propertyNames.removeAt(idx);
3773  d->extraData->propertyValues.removeAt(idx);
3774  } else {
3775  if (idx == -1) {
3776  d->extraData->propertyNames.append(name);
3777  d->extraData->propertyValues.append(value);
3778  } else {
3779  d->extraData->propertyValues[idx] = value;
3780  }
3781  }
3782 
3784  QCoreApplication::sendEvent(this, &ev);
3785 
3786  return false;
3787  }
3788  QMetaProperty p = meta->property(id);
3789 #ifndef QT_NO_DEBUG
3790  if (!p.isWritable())
3791  qWarning("%s::setProperty: Property \"%s\" invalid,"
3792  " read-only or does not exist", metaObject()->className(), name);
3793 #endif
3794  return p.write(this, value);
3795 }
double d
Definition: qnumeric_p.h:62
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
bool isWritable() const
Returns true if this property is writable; otherwise returns false.
The QDynamicPropertyChangeEvent class contains event parameters for dynamic property change events...
Definition: qcoreevent.h:380
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
int indexOfProperty(const char *name) const
Finds property name and returns its index; otherwise returns -1.
const char * name
Q_CORE_EXPORT void qWarning(const char *,...)
static bool sendEvent(QObject *receiver, QEvent *event)
Sends event event directly to receiver receiver, using the notify() function.
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
The QMetaProperty class provides meta-data about a property.
Definition: qmetaobject.h:176
bool write(QObject *obj, const QVariant &value) const
Writes value as the property&#39;s value to the given object.
bool isValid() const
Returns true if the storage type of this variant is not QVariant::Invalid; otherwise returns false...
Definition: qvariant.h:485
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.
QMetaProperty property(int index) const
Returns the meta-data for the property with the given index.

◆ setUserData()

void QObject::setUserData ( uint  id,
QObjectUserData data 
)
Warning
This function is not part of the public interface.

Definition at line 4003 of file qobject.cpp.

Referenced by QTextBlock::operator<().

4004 {
4005  Q_D(QObject);
4006  if (!d->extraData)
4007  d->extraData = new QObjectPrivate::ExtraData;
4008 
4009  if (d->extraData->userData.size() <= (int) id)
4010  d->extraData->userData.resize((int) id + 1);
4011  d->extraData->userData[id] = data;
4012 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
static const char * data(const QByteArray &arr)

◆ signalsBlocked()

bool QObject::signalsBlocked ( ) const
inline

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

See also
blockSignals()

Definition at line 148 of file qobject.h.

Referenced by QTreeModel::emitDataChanged(), QAxEventSink::Invoke(), QAxEventSink::OnChanged(), QTreeModel::removeRows(), QColSpinBox::setValue(), and QBuffer::writeData().

148 { return d_ptr->blockSig; }
uint blockSig
Definition: qobject.h:97
QScopedPointer< QObjectData > d_ptr
Definition: qobject.h:320

◆ startTimer()

int QObject::startTimer ( int  interval)

Starts a timer and returns a timer identifier, or returns zero if it could not start a timer.

A timer event will occur every interval milliseconds until killTimer() is called. If interval is 0, then the timer event occurs once every time there are no more window system events to process.

The virtual timerEvent() function is called with the QTimerEvent event parameter class when a timer event occurs. Reimplement this function to get timer events.

If multiple timers are running, the QTimerEvent::timerId() can be used to find out which timer was activated.

Example:

class MyObject : public QObject
{
public:
MyObject(QObject *parent = 0);
protected:
};
MyObject::MyObject(QObject *parent)
: QObject(parent)
{
startTimer(50); // 50-millisecond timer
startTimer(1000); // 1-second timer
startTimer(60000); // 1-minute timer
}
void MyObject::timerEvent(QTimerEvent *event)
{
qDebug() << "Timer ID:" << event->timerId();
}

Note that QTimer's accuracy depends on the underlying operating system and hardware. Most platforms support an accuracy of 20 milliseconds; some provide more. If Qt is unable to deliver the requested number of timer events, it will silently discard some.

The QTimer class provides a high-level programming interface with single-shot timers and timer signals instead of events. There is also a QBasicTimer class that is more lightweight than QTimer and less clumsy than using timer IDs directly.

See also
timerEvent(), killTimer(), QTimer::singleShot()

Definition at line 1623 of file qobject.cpp.

Referenced by QBalloonTip::balloon(), QUnixSocket::close(), QTableView::columnResized(), QTreeView::columnResized(), QX11Data::dndEnable(), QComboBoxPrivateScroller::enterEvent(), QTestEventLoop::enterLoop(), QPlastiqueStyle::eventFilter(), QMotifStyle::eventFilter(), QAxHostWidget::focusInEvent(), QClipboardWatcher::getDataInFormat(), QFontCache::increaseCost(), QPMCache::insert(), QGLBlurTextureCache::insertBlurTextureInfo(), QLineControl::internalInsert(), QMenu::mouseMoveEvent(), QStateMachine::postDelayedEvent(), QLineControl::processKeyEvent(), QLineControl::processMouseEvent(), QClipboardINCRTransaction::QClipboardINCRTransaction(), QCoreFuriCuri::QCoreFuriCuri(), qDBusRealAddTimeout(), QSingleShotTimer::QSingleShotTimer(), qt_check_clipboard_sentinel(), qt_check_selection_sentinel(), QTapAndHoldGestureRecognizer::recognize(), QPMCache::replace(), QLineControl::resetCursorBlinkTimer(), QMdiSubWindow::resizeEvent(), restartXdndDropExpiryTimer(), QTimeLine::resume(), QTableView::rowResized(), QLineControl::setCursorBlinkPeriod(), QTimer::setInterval(), QTimeLine::setPaused(), QBasicTimer::start(), QMacAnimateCursor::start(), QTimer::start(), QTimeLine::start(), QWindowsStylePrivate::startAnimation(), QMacStylePrivate::startAnimationTimer(), QAbstractSpinBox::timerEvent(), QCoreFuriCuri::timerEvent(), QPMCache::timerEvent(), QFontCache::timerEvent(), QDeclarativePixmapStore::unreferencePixmap(), and QClipboardINCRTransaction::x11Event().

1624 {
1625  Q_D(QObject);
1626 
1627  if (interval < 0) {
1628  qWarning("QObject::startTimer: QTimer cannot have a negative interval");
1629  return 0;
1630  }
1631 
1632  d->pendTimer = true; // set timer flag
1633 
1634  if (!d->threadData->eventDispatcher) {
1635  qWarning("QObject::startTimer: QTimer can only be used with threads started with QThread");
1636  return 0;
1637  }
1638  return d->threadData->eventDispatcher->registerTimer(interval, this);
1639 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)

◆ thread()

QThread * QObject::thread ( ) const

Returns the thread in which the object lives.

See also
moveToThread()

Definition at line 1419 of file qobject.cpp.

Referenced by QDBusConnectionPrivate::activateCall(), QEventDispatcherUNIX::activateTimers(), QWindowsFileSystemWatcherEngine::addPaths(), QDBusAbstractInterface::callWithArgumentList(), QCoreApplicationPrivate::checkReceiverThread(), QDBusConnectionPrivate::checkThread(), QNetworkConfigurationManagerPrivate::cleanup(), QDBusConnectionPrivate::deleteYourself(), QDBusConnectionPrivate::deliverCall(), QNetworkSession::disconnectNotify(), QEventLoop::exec(), QDBusConnectionPrivate::handleObjectCall(), QDeclarativeEnginePrivate::init(), QGLSignalProxy::instance(), QMetaMethod::invoke(), QRawFontPrivate::isValid(), QBBScreen::newWindowCreated(), operator<<(), QScriptDebuggerBackendPrivate::postEvent(), QNetworkAccessHttpBackend::postRequest(), QStateMachinePrivate::processEvents(), qDBusAddTimeout(), qDBusAddWatch(), QDBusDefaultConnection::QDBusDefaultConnection(), qDBusIntrospectObject(), qDBusPropertyGet(), qDBusPropertyGetAll(), qDBusPropertySet(), qDBusRemoveTimeout(), qDBusRemoveWatch(), qDBusToggleWatch(), QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(), QObject(), QSocks5BindStore::QSocks5BindStore(), QWaylandScreen::QWaylandScreen(), QEventDispatcherWin32::registerEventNotifier(), QEventDispatcherGlib::registerSocketNotifier(), QEventDispatcherWin32::registerSocketNotifier(), QEventDispatcherMac::registerSocketNotifier(), QEventDispatcherUNIX::registerSocketNotifier(), QEventDispatcherGlib::registerTimer(), QEventDispatcherWin32::registerTimer(), QEventDispatcherMac::registerTimer(), QEventDispatcherUNIX::registerTimer(), QDBusAdaptorConnector::relaySlot(), QWindowsFileSystemWatcherEngine::removePaths(), QSocks5BindStore::retrieve(), QDBusConnectionPrivate::sendWithReplyAsync(), QNetworkAccessManager::setCookieJar(), QEventDispatcherUNIX::setSocketNotifierPending(), QWindowsFileSystemWatcherEngine::stop(), thread(), QEventDispatcherWin32::unregisterEventNotifier(), QEventDispatcherGlib::unregisterSocketNotifier(), QEventDispatcherWin32::unregisterSocketNotifier(), QEventDispatcherMac::unregisterSocketNotifier(), QEventDispatcherUNIX::unregisterSocketNotifier(), QEventDispatcherGlib::unregisterTimer(), QEventDispatcherWin32::unregisterTimer(), QEventDispatcherUNIX::unregisterTimer(), QEventDispatcherGlib::unregisterTimers(), QEventDispatcherWin32::unregisterTimers(), QEventDispatcherMac::unregisterTimers(), QEventDispatcherUNIX::unregisterTimers(), QBBScreen::windowClosed(), QDBusConnectionPrivate::~QDBusConnectionPrivate(), and QWindowsFileSystemWatcherEngine::~QWindowsFileSystemWatcherEngine().

1420 {
1421  return d_func()->threadData->thread;
1422 }

◆ timerEvent()

void QObject::timerEvent ( QTimerEvent event)
protectedvirtual

This event handler can be reimplemented in a subclass to receive timer events for the object.

QTimer provides a higher-level interface to the timer functionality, and also more general information about timers. The timer event is passed in the event parameter.

See also
startTimer(), killTimer(), event()

Reimplemented in QUnixSocketPrivate, QWSSoundServerPrivate, QDeclarativePixmapStore, QLineControl, QAbstractItemView, QSocks5BindStore, QWSServer, QGLBlurTextureCache, QSingleShotTimer, QTextEdit, QFontCache, QTextControl, QDBusConnectionPrivate, QComboBoxPrivateContainer, QPlainTextEdit, QDragManager, QMacStylePrivate, QDeclarativeMouseArea, QUnifiedTimer, QPMCache, QDeclarativeFlickable, QTreeView, QScriptDebugger, QMenu, QMainWindowLayout, QComboBoxPrivateScroller, QCoreFuriCuri, QListView, QMdiArea, QTableView, QAbstractSpinBox, QFileSystemModel, QAbstractSlider, QTreeModel, QTipLabel, QAbstractButton, QMenuBar, QTimeLine, QCoeFepInputContext, QDefaultAnimationDriver, QMdiSubWindow, QToolButton, QBalloonTip, QMotifStyle, QTextDocumentLayout, QNetworkAccessCache, QDeclarativeView, QPlastiqueStyle, QWindowsStyle, QTimer, QMacAnimateCursor, QTestEventLoop, and QCalendarTextNavigator.

Definition at line 1294 of file qobject.cpp.

Referenced by event(), QTextDocumentLayout::timerEvent(), QBalloonTip::timerEvent(), QMenuBar::timerEvent(), QTreeModel::timerEvent(), QAbstractSpinBox::timerEvent(), QMainWindowLayout::timerEvent(), QScriptDebugger::timerEvent(), QWSServer::timerEvent(), QTextControl::toHtml(), and QPlainTextEdit::toPlainText().

1295 {
1296 }

◆ tr()

QString QObject::tr ( const char *  sourceText,
const char *  disambiguation = 0,
int  n = -1 
)
static
Note
This class or function is reentrant.

Returns a translated version of sourceText, optionally based on a disambiguation string and value of n for strings containing plurals; otherwise returns sourceText itself if no appropriate translated string is available.

Example:

void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));

...

If the same sourceText is used in different roles within the same context, an additional identifying string may be passed in disambiguation (0 by default). In Qt 4.4 and earlier, this was the preferred way to pass comments to translators.

Example:

MyWindow::MyWindow()
{
QLabel *senderLabel = new QLabel(tr("Name:"));
QLabel *recipientLabel = new QLabel(tr("Name:", "recipient"));

...

See Writing Source Code for Translation for a detailed description of Qt's translation mechanisms in general, and the Writing Source Code for Translation::Disambiguation{Disambiguation} section for information on disambiguation.

Warning
This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.
See also
trUtf8(), QApplication::translate(), QTextCodec::setCodecForTr(), {Internationalization with Qt}

Referenced by QAbstractSocketPrivate::_q_abortConnectionAttempt(), QUnixPrintWidgetPrivate::_q_btnBrowseClicked(), QProcessPrivate::_q_canReadStandardError(), QProcessPrivate::_q_canReadStandardOutput(), QProcessPrivate::_q_canWrite(), QPrintDialogPrivate::_q_collapseOrExpandDialog(), QAbstractSocketPrivate::_q_connectToNextAddress(), QFileDialogPrivate::_q_createDirectory(), QFileDialogPrivate::_q_deleteCurrent(), QFileDialogPrivate::_q_goToDirectory(), QScriptDebuggerPrivate::_q_goToLine(), QPrintDialogPrivate::_q_okClicked(), QUnixPrintWidgetPrivate::_q_printerChanged(), QProcessPrivate::_q_processDied(), QDeclarativeLoaderPrivate::_q_sourceLoaded(), QAbstractSocketPrivate::_q_startConnecting(), QWorkspacePrivate::_q_updateActions(), QFileDialogPrivate::_q_updateOkButton(), QNetworkReplyImpl::abort(), QHttp::abort(), QMessageBox::aboutQt(), QAccessibleButton::actionText(), QAccessibleMenu::actionText(), QAccessibleMenuBar::actionText(), QAccessibleToolButton::actionText(), QAccessibleMenuItem::actionText(), QAccessibleApplication::actionText(), QAccessibleTabBar::actionText(), QAccessibleComboBox::actionText(), QAccessibleTitleBar::actionText(), QPrintPropertiesDialog::addItemToOptions(), addKey(), QDeclarativeListModel::append(), QDeclarativeXmlListModelPrivate::append_role(), QSharedMemoryPrivate::attach(), QSQLiteDriver::beginTransaction(), QSQLite2Driver::beginTransaction(), QMYSQLDriver::beginTransaction(), QPSQLDriver::beginTransaction(), QODBCDriver::beginTransaction(), buttonDefaultText(), QMessageBox::buttonText(), QDeclarativeAnchorsPrivate::centerInChanged(), QUnixPrintWidgetPrivate::checkFields(), QDeclarativeAnchorsPrivate::checkHAnchorValid(), QDeclarativeAnchorsPrivate::checkHValid(), AVMediaObject::checkPlayer(), QDeclarativeAnchorsPrivate::checkVAnchorValid(), QDeclarativeAnchorsPrivate::checkVValid(), QScriptDebugger::clearConsoleAction(), QScriptDebugger::clearDebugOutputAction(), QScriptDebugger::clearErrorLogAction(), QNetworkReplyImpl::close(), QSQLiteDriver::close(), CloseButton::CloseButton(), QDB2Driver::commitTransaction(), QSQLiteDriver::commitTransaction(), QSQLite2Driver::commitTransaction(), QMYSQLDriver::commitTransaction(), QPSQLDriver::commitTransaction(), QODBCDriver::commitTransaction(), QDeclarativeGestureAreaParser::compile(), QDeclarativeConnectionsParser::compile(), QDeclarativeListModelParser::compile(), QDeclarativePropertyChangesParser::compileList(), QDeclarativeListModelParser::compileProperty(), QDeclarativeConnections::connectSignals(), QAbstractSocket::connectToHostImplementation(), QScrollBar::contextMenuEvent(), QDialog::contextMenuEvent(), QAbstractSpinBox::contextMenuEvent(), QScriptDebugger::continueAction(), QFile::copy(), QSharedMemory::create(), QSharedMemoryPrivate::create(), QDialogButtonBoxPrivate::createButton(), QProcessPrivate::createChannel(), QmlJSDebugger::LiveSelectionTool::createContextMenu(), QDeclarativeTextInput::createCursor(), QDeclarativeComponent::createObject(), QDeclarativeAbstractAnimationPrivate::createProperty(), QUndoGroup::createRedoAction(), QUndoStack::createRedoAction(), QTextControl::createStandardContextMenu(), QLineEdit::createStandardContextMenu(), QScriptDebugger::createStandardMenu(), QMdiSubWindowPrivate::createSystemMenu(), QUndoGroup::createUndoAction(), QUndoStack::createUndoAction(), QMessageBox::critical(), QKeySequencePrivate::decodeString(), QDeclarativeItemModule::defineModule(), QDeclarativeUtilModule::defineModule(), QDeclarativeItemModule::defineModuleCompat(), QDeclarativeUtilModule::defineModuleCompat(), QMultiInputContextPlugin::description(), QInputContextFactory::description(), QLocalSocketPrivate::destroyPipeHandles(), QSharedMemoryPrivate::detach(), QMultiInputContextPlugin::displayName(), QInputContextFactory::displayName(), QDeclarativeParentChangePrivate::doChange(), QUdpSocketPrivate::doEnsureInitialized(), QDeclarativeTypeData::done(), QMotifStyle::drawComplexControl(), QCommonStyle::drawControl(), QMotifStyle::drawControl(), QFtpPI::dtpConnectState(), QKeySequencePrivate::encodeString(), QODBCDriver::endTrans(), QInputDialogPrivate::ensureLayout(), QFtpPI::error(), QPluginLoader::errorString(), QLibrary::errorString(), QNetworkSession::errorString(), QSslError::errorString(), QIODevice::errorString(), QNetworkSessionPrivateImpl::errorString(), QMDIControl::event(), QWorkspace::eventFilter(), QDialog::exec(), QScriptEdit::extraAreaMouseEvent(), QDeclarativeAnchorsPrivate::fillChanged(), QScriptDebugger::findInScriptAction(), QScriptDebugger::findNextInScriptAction(), QScriptDebugger::findPreviousInScriptAction(), QNetworkReplyImplPrivate::finished(), QNetworkSessionManagerPrivate::forceSessionClose(), QHostInfoAgent::fromName(), QNetworkAccessFtpBackend::ftpDone(), QDateTimeEditPrivate::getAmPmText(), getFullPath(), QScriptDebugger::goToLineAction(), QSystemSemaphorePrivate::handle(), QSharedMemoryPrivate::handle(), QDirModel::headerData(), QFileSystemModel::headerData(), QBBInputContext::identifierName(), QColorDialogPrivate::init(), QFontDialogPrivate::init(), QLocalSocketPrivate::init(), QPrintPreviewDialogPrivate::init(), QWorkspacePrivate::init(), QSharedMemoryPrivate::initKey(), QAbstractSocketPrivate::initSocketLayer(), QSslSocketBackendPrivate::initSslContext(), QDeclarativeListModel::insert(), QScriptDebugger::interruptAction(), QLibraryPrivate::isPlugin(), QDeclarativeVisualDataModel::item(), jump(), DetailButton::label(), QTcpServer::listen(), QLocalServer::listen(), QLibraryPrivate::load_sys(), QDeclarativeComponent::loadUrl(), QAccessibleGroupBox::localizedName(), QSharedMemory::lock(), QGraphicsView::mapFromScene(), QGraphicsView::mapToScene(), QGraphicsViewPrivate::mapToScene(), QDeclarativeListModel::move(), QFileSystemModelPrivate::myComputer(), QNetworkAccessFtpBackend::open(), QSQLite2Driver::open(), QSQLiteDriver::open(), QOCIDriver::open(), QTDSDriver::open(), QDB2Driver::open(), QMYSQLDriver::open(), QPSQLDriver::open(), QODBCDriver::open(), QPrintDialogPrivate::openWindowsPrintDialogModally(), QProcessPrivate::pipeWriterBytesToWrite(), AVMediaObject::play(), populatePaperSizes(), QNetworkAccessHttpBackend::postRequest(), QFtpPI::processReply(), QDeclarativePropertyChangesPrivate::property(), QBooleanComboBox::QBooleanComboBox(), QDeclarativeLayoutMirroringAttached::QDeclarativeLayoutMirroringAttached(), qExtractSecurityPolicyFromString(), QFtp::QFtp(), qmlsqldatabase_change_version(), qmlsqldatabase_executeSql_outsidetransaction(), qmlsqldatabase_executeSql_readonly(), qmlsqldatabase_open_sync(), qmlsqldatabase_transaction_shared(), QmlJSDebugger::QmlToolBar::QmlToolBar(), QMultiInputContext::QMultiInputContext(), QOCIDriver::QOCIDriver(), QPageSetupWidget::QPageSetupWidget(), QScriptBreakpointsWidget::QScriptBreakpointsWidget(), QScriptDebuggerCodeFinderWidget::QScriptDebuggerCodeFinderWidget(), QScriptNewBreakpointWidget::QScriptNewBreakpointWidget(), qt_create_commandline(), qt_create_pipe(), qt_detectRTLLanguage(), qt_getLprPrinters(), qt_mac_make_filters_list(), qt_mac_menu_merge_action(), qt_mac_menu_merge_text(), qt_parse_pattern(), qt_parseEtcLpMember(), qt_parsePrinterDesc(), qt_parsePrintersConf(), qt_perhapsAddPrinter(), qt_setWindowTitle_helperHelper(), qt_terminateApp(), qt_win_make_filters_list(), QTgaFile::QTgaFile(), QDeclarativeXmlListModel::queryError(), QUndoModel::QUndoModel(), QUnicodeControlCharacterMenu::QUnicodeControlCharacterMenu(), QDeclarativeListModel::remove(), QFile::rename(), QLibraryPrivate::resolve_sys(), QDeclarativeTypeData::resolveTypes(), QColorDialogPrivate::retranslateStrings(), QProgressDialogPrivate::retranslateStrings(), QErrorMessagePrivate::retranslateStrings(), QFontDialogPrivate::retranslateStrings(), QFileDialogPrivate::retranslateStrings(), QDialogButtonBoxPrivate::retranslateStrings(), QColorShower::retranslateStrings(), QFileDialogPrivate::retranslateWindowTitle(), QDB2Driver::rollbackTransaction(), QSQLiteDriver::rollbackTransaction(), QSQLite2Driver::rollbackTransaction(), QMYSQLDriver::rollbackTransaction(), QPSQLDriver::rollbackTransaction(), QODBCDriver::rollbackTransaction(), QScriptDebugger::runToCursorAction(), QScriptDebugger::runToNewScriptAction(), QFtpPI::sendCommands(), QDeclarativeListModel::set(), QDeclarativeBehavior::setAnimation(), QDB2Driver::setAutoCommit(), QDeclarativeFlipable::setBack(), QDeclarativeAnchors::setCenterIn(), QFileSystemModel::setData(), QDeclarativePauseAnimation::setDuration(), QDeclarativePropertyAnimation::setDuration(), QDeclarativeAnchorAnimation::setDuration(), QLocalServerPrivate::setError(), QStateMachinePrivate::setError(), QNativeSocketEnginePrivate::setError(), QSocks5SocketEnginePrivate::setErrorState(), QLocalSocketPrivate::setErrorString(), QSharedMemoryPrivate::setErrorString(), QPluginLoader::setFileName(), QDeclarativeAnchors::setFill(), QDeclarativeFlipable::setFront(), QFileDialog::setNameFilters(), QMdiSubWindowPrivate::setNewWindowTitle(), QDeclarativeListModel::setProperty(), QTcpServer::setSocketDescriptor(), QAbstractSocket::setSocketDescriptor(), AVMediaObject::setSource(), QPrintDialogPrivate::setupOptions(), QPrintDialogPrivate::setupPaper(), QSidebar::showContextMenu(), QWorkspacePrivate::showMaximizeControls(), QMessageBoxPrivate::showOldMessageBox(), QFileDialogComboBox::showPopup(), showToolTip(), QDirModelPrivate::size(), QFileSystemModelPrivate::size(), QHttpSocketEngine::slotSocketError(), QHttpSocketEngine::slotSocketReadNotification(), QSoftKeyManager::standardSoftKeyText(), QScriptEngineDebugger::standardWindow(), QProcess::start(), QDeclarativeTextInputPrivate::startCreatingCursor(), QSslSocketBackendPrivate::startHandshake(), QProcessPrivate::startProcess(), QScriptDebugger::stepIntoAction(), QScriptDebugger::stepOutAction(), QScriptDebugger::stepOverAction(), QCommonStyle::subElementRect(), QMotifStyle::subElementRect(), QPSQLDriver::subscribeToNotificationImplementation(), QCommonStylePrivate::tabLayout(), tabTextFor(), QAccessibleAbstractSpinBox::text(), QAccessibleDoubleSpinBox::text(), QAccessibleScrollBar::text(), QAccessibleSlider::text(), QAccessibleDial::text(), QAccessibleTabBar::text(), QAccessibleComboBox::text(), QScriptDebugger::toggleBreakpointAction(), QmlJSDebugger::ToolBarColorBox::ToolBarColorBox(), QDeclarativeParentAnimation::transition(), translateWSAError(), QSslSocketBackendPrivate::transmit(), QSharedMemoryPrivate::tryLocker(), QPluginLoader::unload(), QLibraryPrivate::unload_sys(), QSharedMemory::unlock(), QFile::unmap(), QPSQLDriver::unsubscribeFromNotificationImplementation(), QDeclarativeBinding::update(), QDeclarativeAnchorsPrivate::updateHorizontalAnchors(), QDeclarativeAnchorsPrivate::updateVerticalAnchors(), QUnixPrintWidgetPrivate::updateWidget(), QProcessPrivate::waitForBytesWritten(), QAbstractSocket::waitForConnected(), QProcessPrivate::waitForFinished(), QProcessPrivate::waitForReadyRead(), QProcessPrivate::waitForStarted(), QAbstractSocket::writeData(), QProcess::writeData(), and QmlJSDebugger::ZoomTool::ZoomTool().

◆ trUtf8()

QString QObject::trUtf8 ( const char *  sourceText,
const char *  disambiguation = 0,
int  n = -1 
)
static
Note
This class or function is reentrant.

Returns a translated version of sourceText, or QString::fromUtf8(sourceText) if there is no appropriate version. It is otherwise identical to tr(sourceText, disambiguation, n).

Note that using the Utf8 variants of the translation functions is not required if CODECFORTR is already set to UTF-8 in the qmake project file and QTextCodec::setCodecForTr("UTF-8") is used.

Warning
This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will probably result in crashes or other undesirable behavior.
For portability reasons, we recommend that you use escape sequences for specifying non-ASCII characters in string literals to trUtf8(). For example:
label->setText(tr("F\374r \310lise"));
See also
tr(), QApplication::translate(), {Internationalization with Qt}

◆ userData()

QObjectUserData * QObject::userData ( uint  id) const
Warning
This function is not part of the public interface.

Definition at line 4016 of file qobject.cpp.

Referenced by hb_canRender(), hb_getAdvances(), hb_getFontMetric(), hb_getGlyphMetrics(), hb_getPointInOutline(), hb_stringToGlyphs(), QScriptSyntaxHighlighter::highlightBlock(), and QTextBlock::operator<().

4017 {
4018  Q_D(const QObject);
4019  if (!d->extraData)
4020  return 0;
4021  if ((int)id < d->extraData->userData.size())
4022  return d->extraData->userData.at(id);
4023  return 0;
4024 }
double d
Definition: qnumeric_p.h:62
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
#define Q_D(Class)
Definition: qglobal.h:2482

Friends and Related Functions

◆ QApplication

friend class QApplication
friend

Definition at line 325 of file qobject.h.

◆ QApplicationPrivate

friend class QApplicationPrivate
friend

Definition at line 326 of file qobject.h.

◆ QCoreApplication

friend class QCoreApplication
friend

Definition at line 327 of file qobject.h.

◆ QCoreApplicationPrivate

Definition at line 328 of file qobject.h.

Referenced by QCoreApplication::QCoreApplication().

◆ qFindChildqFindChildren()

T qFindChildqFindChildren ( const QObject obj,
const QString name,
const QObject obj,
const QString name 
)
related

This function is equivalent to {obj}->findChild<T>(name).

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QObject::findChild()

◆ qFindChildrenqFindChildren() [1/2]

QList< T > qFindChildrenqFindChildren ( const QObject obj,
const QString name,
const QObject obj,
const QString name 
)
related

This function is equivalent to {obj}->findChildren<T>(name).

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QObject::findChildren()

◆ qFindChildrenqFindChildren() [2/2]

QList< T > qFindChildrenqFindChildren ( const QObject obj,
const QRegExp regExp,
const QObject obj,
const QRegExp regExp 
)
related

This function is equivalent to {obj}->findChildren<T>(regExp).

Note
This function was provided as a workaround for MSVC 6 which did not support member template functions. It is advised to use the other form in new code.
See also
QObject::findChildren()

◆ QMetaObject

friend struct QMetaObject
friend

Definition at line 324 of file qobject.h.

◆ qobject_cast()

T * qobject_cast< T *> ( QObject object)
related

Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.

The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.

A class is considered to inherit itself.

Example:

QObject *obj = new QTimer; // QTimer inherits QObject
// timer == (QObject *)obj
// button == 0

The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.

qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details.

Warning
If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.
See also
QObject::inherits()

Definition at line 375 of file qobject.h.

Referenced by QMenuPrivate::_q_actionTriggered(), QToolBoxPrivate::_q_buttonClicked(), QWSServerPrivate::_q_doClient(), _q_paintItem(), QNetworkAccessManagerPrivate::_q_replyFinished(), QNetworkAccessManagerPrivate::_q_replySslErrors(), QHttpPrivate::_q_slotSendRequest(), QDeclarativeLoaderPrivate::_q_sourceLoaded(), QParallelAnimationGroupPrivate::_q_uncontrolledAnimationFinished(), QFontComboBoxPrivate::_q_updateModel(), QToolBar::actionEvent(), QWidgetPrivate::activateChildLayoutsRecursively(), QMdiArea::addSubWindow(), QMacStylePrivate::addWidget(), QPushButtonPrivate::adjustedMenuPosition(), QDeclarativeParticleMotionWander::advance(), QAbstractTextDocumentLayout::anchorAt(), QWidgetAnimator::animationFinished(), QMainWindowLayout::animationFinished(), QPlainTextEditPrivate::append(), QDeclarativeAnimationGroupPrivate::append_animation(), QDeclarativeXmlListModelPrivate::append_role(), ShaderEffectSource::attachSourceItem(), QScriptEngine::availableExtensions(), axc_FilterProc(), QPlainTextEditControl::blockBoundingRect(), QPlainTextEdit::blockBoundingRect(), QScriptBreakpointsWidget::breakpointsModel(), buddyString(), QDeclarativeContents::calcHeight(), QDeclarativeContents::calcWidth(), QPlainTextEditControl::canInsertFromMimeData(), QTextEditControl::canInsertFromMimeData(), QDeclarativeBoundSignal::cast(), QmlJSDebugger::QmlToolBar::changeAnimationSpeed(), QDockWidget::changeEvent(), QWorkspaceChild::changeEvent(), QX11EmbedWidgetPrivate::checkActivateWindow(), QToolBarLayout::checkUsePopupMenu(), QWidgetPrivate::childAt_helper(), QWidgetPrivate::childAtRecursiveHelper(), QStatePrivate::childStates(), childWidgets(), QDeclarativeAnimationGroupPrivate::clear_animation(), QDeclarativeContents::complete(), AVBackend::connectNodes(), AccessibleFactory::create(), QDeclarativeListViewPrivate::createComponentItem(), QDeclarativeTextInput::createCursor(), QScriptDebuggerLocalsItemDelegate::createEditor(), QScriptBreakpointsItemDelegate::createEditor(), QDeclarativePathViewPrivate::createHighlight(), QToolBarLayout::createItem(), QPlainTextEditControl::createMimeDataFromSelection(), QTextEditControl::createMimeDataFromSelection(), QWidgetPrivate::createRecursively(), QDeclarativeListViewPrivate::createSection(), QWidgetPrivate::createWinId(), QScriptDebuggerCodeWidget::currentView(), QDeclarativeFlickablePrivate::data_append(), defaultWidgetAction(), QGLWindowSurface::deleted(), ShaderEffectSource::detachSourceItem(), QAudioInputPrivate::deviceReady(), AVBackend::disconnectNodes(), do_dbus_call(), QWindowsVistaStyle::drawComplexControl(), QCommonStyle::drawComplexControl(), QWindowsCEStyle::drawComplexControl(), QWindowsVistaStyle::drawControl(), QMacStyle::drawControl(), QTextDocumentLayout::drawInlineObject(), QGraphicsScenePrivate::drawItemHelper(), QGraphicsScene::drawItems(), QWindowsVistaStyle::drawPrimitive(), QMacStyle::drawPrimitive(), QListModel::dropMimeData(), QTableModel::dropMimeData(), QScriptEditExtraArea::editor(), QAbstractItemView::editorDestroyed(), QHttpNetworkConnectionChannel::ensureConnection(), QIODevice::errorString(), QFontComboBox::event(), QDockWidget::event(), QLabel::event(), QToolBar::event(), QDialogButtonBox::event(), QWidget::event(), QX11EmbedWidget::eventFilter(), QStyledItemDelegate::eventFilter(), QPlastiqueStyle::eventFilter(), QItemDelegate::eventFilter(), QAxHostWidget::eventFilter(), QCompleter::eventFilter(), QMdiArea::eventFilter(), QScriptDebuggerLocalsItemDelegate::eventFilter(), QToolBarLayout::expandedSize(), QToolBarLayout::expandingDirections(), QAudioInputPrivate::feedback(), QCompletionEngine::filterHistory(), find_child(), findMenuBar(), fixToolBarOrientation(), QPushButton::focusInEvent(), QPushButton::focusOutEvent(), QAbstractTextDocumentLayout::format(), QAbstractTextDocumentLayout::formatIndex(), QAudioOutputPrivate::freeBlocks(), QGraphicsScenePrivate::gestureEventHandler(), getEngineFromId(), getImage(), QWidgetPrivate::getOpaqueChildren(), getPixmap(), QMacInputContext::globalEventProcessor(), QApplicationPrivate::globalEventProcessor(), QCalendarView::handleMouseEvent(), QWidgetPrivate::hideChildren(), QStatePrivate::historyStates(), QPlainTextEditControl::hitTest(), if(), QHttp::ignoreSslErrors(), QScriptEngine::importExtension(), QWidgetPrivate::inheritStyle(), QHttpNetworkConnectionChannel::init(), QToolBar::initStyleOption(), InputPrivate::InputPrivate(), QListModel::insert(), QPlainTextEditControl::insertFromMimeData(), QTextEditControl::insertFromMimeData(), QListModel::insertRows(), QDeclarativeFlickablePrivate::isOutermostPressDelay(), QWidgetPrivate::isOverlapped(), isTreeView(), QDeclarativeVisualDataModel::item(), QListWidget::items(), QTableWidget::items(), QToolBarLayout::layoutActions(), QGraphicsScenePrivate::leaveScene(), QDeclarativeTextEdit::loadCursorDelegate(), QDeclarativeInspectorService::loadInspectorPlugin(), QTextDocument::loadResource(), QScriptDebuggerLocalsWidget::localsModel(), QDeclarativeItem::mapFromItem(), QDeclarativeItem::mapToItem(), ShaderEffectSource::markSourceItemDirty(), QUnicodeControlCharacterMenu::menuActionTriggered(), QMainWindow::menuBar(), QDeclarativeEngineDebugService::messageReceived(), QListModel::mimeData(), QTableModel::mimeData(), QListModel::mimeTypes(), QTableModel::mimeTypes(), QDockWidgetLayout::minimumSize(), QDockWidgetLayout::minimumTitleWidth(), QCalendarView::mouseDoubleClickEvent(), QCalendarView::mouseMoveEvent(), QSizeGrip::mousePressEvent(), QCalendarPopup::mousePressEvent(), QCalendarView::mousePressEvent(), QCalendarView::mouseReleaseEvent(), QToolBarLayout::movable(), QCalendarView::moveCursor(), QAbstractButtonPrivate::moveFocus(), QNetworkManagerEngine::newConnection(), QApplication::notify(), QTextFrame::iterator::operator++(), QTextFrame::iterator::operator--(), OutputPrivate::OutputPrivate(), QTextEditPrivate::paint(), QScriptDebuggerLocalsItemDelegate::paint(), QGraphicsTextItem::paint(), QWidgetPrivate::paintBackground(), QDockWidget::paintEvent(), QWidgetPrivate::paintSiblingsRecursive(), QGraphicsWidget::paintWindowFrame(), QDeclarativeItem::parentItem(), QAbstractState::parentState(), QFSCompleter::pathFromIndex(), QCompleter::pathFromIndex(), QMacStyle::pixelMetric(), QStyleSheetStyle::pixelMetric(), QMainWindowLayout::plug(), QPlastiqueStyle::polish(), QStyleSheetStyle::polish(), QGtkStyle::polish(), QDBusAdaptorConnector::polish(), QMenu::popup(), QToolButtonPrivate::popupTimerDone(), QTextDocumentLayout::positionInlineObject(), QHttpPrivate::postMoreData(), QWidgetPrivate::propagatePaletteChange(), q_createNativeChildrenAndSetParent(), QAction::QAction(), qDBusFindAdaptorConnector(), QDeclarativeKeysAttached::QDeclarativeKeysAttached(), QFontComboBox::QFontComboBox(), qgraphicsobject_autoParent(), QIODevice::QIODevice(), qmlxmlhttprequest_abort(), qmlxmlhttprequest_getAllResponseHeaders(), qmlxmlhttprequest_getResponseHeader(), qmlxmlhttprequest_onreadystatechange(), qmlxmlhttprequest_open(), qmlxmlhttprequest_readyState(), qmlxmlhttprequest_responseText(), qmlxmlhttprequest_responseXML(), qmlxmlhttprequest_send(), qmlxmlhttprequest_setRequestHeader(), qmlxmlhttprequest_status(), qmlxmlhttprequest_statusText(), QScriptDBusInterfaceConstructor::qscript_call(), qt_aqua_get_known_size(), qt_guiPlatformPlugin(), qt_mac_buttonIsRenderedFlat(), QSignalEventGenerator::qt_metacall(), QToolBarLayout::QToolBarLayout(), QtWndProc(), QWidgetResizeHandler::QWidgetResizeHandler(), QWinEventNotifier::QWinEventNotifier(), QAbstractTextDocumentLayout::registerHandler(), QTextEditPrivate::relayoutDocument(), QPlainTextEditPrivate::relayoutDocument(), QNetworkManagerEngine::removeConnection(), QMacStylePrivate::removeWidget(), QmlJSDebugger::QDeclarativeViewInspector::reparentQmlObject(), QTextDocumentLayout::resizeInlineObject(), QDeclarativeParentChange::saveCurrentValues(), QAxScriptManager::scriptError(), QScriptDebuggerScriptsWidget::scriptsModel(), QDeclarativeWorkerScriptEnginePrivate::scriptValueToVariant(), QInputContext::sendEvent(), QSoftKeyManager::sendKeyEvent(), QDeclarativePathView::sendMouseEvent(), QDeclarativeMouseArea::sendMouseEvent(), QDeclarativeFlickable::sendMouseEvent(), QDeclarativePinchArea::sendMouseEvent(), QDeclarativeTextInputPrivate::sendMouseEventToInputContext(), QHttpNetworkConnectionChannel::sendRequest(), QWidget::setAttribute(), QGraphicsScene::setBspTreeDepth(), QCalendarPopup::setCalendarWidget(), QTableModel::setData(), QMessageBox::setDetailedText(), QWidget::setDisabled(), QPlainTextEdit::setDocument(), QWinEventNotifier::setEnabled(), QWidgetPrivate::setEnabled_helper(), QToolBarLayout::setExpanded(), QDockWidget::setFeatures(), QAction::setFont(), QToolBarLayout::setGeometry(), QDockWidgetLayout::setGeometry(), QTableModel::setHorizontalHeaderItem(), QToolBar::setIconSize(), QTableModel::setItem(), QTableModel::setItemData(), QGraphicsScene::setItemIndexMethod(), QComboBoxPrivateContainer::setItemView(), QWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLocale_helper(), QMainWindow::setMenuBar(), QCompleter::setModel(), QComboBox::setModelColumn(), QScriptDebuggerLocalsItemDelegate::setModelData(), QScriptBreakpointsItemDelegate::setModelData(), ShaderEffectItem::setSource(), QWidgetPrivate::setStyle_helper(), QApplication::setStyleSheet(), QWidget::setStyleSheet(), QDockWidget::setTitleBarWidget(), QWidgetPrivate::setUpdatesEnabled_helper(), QTableModel::setVerticalHeaderItem(), QDialog::setVisible(), QDockWidget::setWidget(), QWidgetPrivate::setWindowIcon_helper(), QFontComboBox::setWritingSystem(), QGLShaderProgram::shaderDestroyed(), QMdi::ControlContainer::showButtonsInMenuBar(), QWidgetPrivate::showChildren(), QWidget::showFullScreen(), QWidget::showMaximized(), QWidget::showNormal(), QComboBox::showPopup(), QDockWidgetLayout::sizeFromContent(), QMacStyle::sizeFromContents(), QPushButton::sizeHint(), QDockWidgetLayout::sizeHint(), QComboBoxPrivateContainer::spacing(), QFSCompleter::splitPath(), QCompleter::splitPath(), QMainWindowLayout::statusBar(), QWindowsXPStyle::styleHint(), QWindowsStyle::styleHint(), QCommonStyle::subElementRect(), QMacStyle::subElementRect(), QWidgetPrivate::subtractOpaqueSiblings(), QListModel::supportedDropActions(), QTableModel::supportedDropActions(), QScriptDebuggerLocalsModel::sync(), QMainWindowLayout::tabChanged(), QTableWidgetPrivate::tableModel(), QToolBarLayout::takeAt(), QTextBlock::textList(), QDeclarativeFlickable::timerEvent(), QDockWidget::titleBarWidget(), QmlJSDebugger::AbstractLiveEditTool::titleForItem(), QDockWidgetLayout::titleHeight(), toolbarInUnifiedToolBar(), QmlJSDebugger::AbstractLiveEditTool::toQDeclarativeItem(), QDeclarativeItemPrivate::transform_append(), QDeclarativeItemPrivate::transform_at(), QDeclarativeItemPrivate::transform_clear(), QDeclarativeItemPrivate::transform_count(), QStatePrivate::transitions(), QTreeWidgetPrivate::treeModel(), QPlastiqueStyle::unpolish(), QNetworkManagerEngine::updateAccessPoint(), QNetworkConfigurationManagerPrivate::updateConfigurations(), QNetworkManagerEngine::updateConnection(), QMenuBarPrivate::updateCornerWidgetToolBar(), QFactoryLoader::updateDir(), QWidgetPrivate::updateFont(), QToolBarLayout::updateGeomArray(), QToolBarLayout::updateMarginAndSpacing(), QWorkspaceChild::updateMask(), QMessageBoxPrivate::updateSize(), QStyleSheetStyle::updateStyleSheetFont(), QComboBoxPrivateContainer::updateTopBottomMargin(), QScriptBreakpointsItemDelegate::validateInput(), QPlainTextEditPrivate::verticalOffset(), QTreeModel::view(), QMdiArea::viewportEvent(), QHeaderView::viewportEvent(), QWizardHeader::vistaDisabled(), waitForPopup(), QDockWidget::widget(), QWorkspace::windowList(), QDeclarativeContents::~QDeclarativeContents(), QToolBar::~QToolBar(), and QWorkspaceChild::~QWorkspaceChild().

376 {
377 #if !defined(QT_NO_QOBJECT_CHECK)
378  reinterpret_cast<T>(object)->qt_check_for_QOBJECT_macro(*reinterpret_cast<T>(object));
379 #endif
380  return static_cast<T>(reinterpret_cast<T>(object)->staticMetaObject.cast(object));
381 }
static const QMetaObject staticMetaObject
This variable stores the meta-object for the class.
Definition: qobject.h:128
QObject * cast(QObject *obj) const
Returns obj if object obj inherits from this meta-object; otherwise returns 0.

◆ QObjectList()

QObjectList
related

Synonym for QList<QObject *>.

◆ qt_find_obj_child()

void * qt_find_obj_child ( QObject parent,
const char *  type,
const QString name 
)
related

Returns a pointer to the object named name that inherits type and with a given parent.

Returns 0 if there is no such child.

QLineEdit *lineEdit = static_cast<QLineEdit *>(
qt_find_obj_child(myWidget, "QLineEdit", "my line edit"));
if (lineEdit)
lineEdit->setText("Default");

Definition at line 700 of file qobject.cpp.

701 {
702  QObjectList list = parent->children();
703  if (list.size() == 0) return 0;
704  for (int i = 0; i < list.size(); ++i) {
705  QObject *obj = list.at(i);
706  if (name == obj->objectName() && obj->inherits(type))
707  return obj;
708  }
709  return 0;
710 }
int type
Definition: qmetatype.cpp:239
QString objectName
the name of this object
Definition: qobject.h:114
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
bool inherits(const char *classname) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass t...
Definition: qobject.h:275
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
const QObjectList & children() const
Returns a list of child objects.
Definition: qobject.h:197

◆ QThreadData

friend class QThreadData
friend

Definition at line 330 of file qobject.h.

Referenced by moveToThread().

◆ QWidget

friend class QWidget
friend

Properties

◆ d_ptr

QScopedPointer<QObjectData> QObject::d_ptr
protected

◆ objectName

QString QObject::objectName
private

◆ staticMetaObject

QObject::staticMetaObject
static

This variable stores the meta-object for the class.

A meta-object contains information about a class that inherits QObject, e.g. class name, superclass name, properties, signals and slots. Every class that contains the Q_OBJECT macro will also have a meta-object.

The meta-object information is required by the signal/slot connection mechanism and the property system. The inherits() function also makes use of the meta-object.

If you have a pointer to an object, you can use metaObject() to retrieve the meta-object associated with that object.

Example:

QPushButton::staticMetaObject.className(); // returns "QPushButton"
QObject *obj = new QPushButton;
obj->metaObject()->className(); // returns "QPushButton"
See also
metaObject()

Definition at line 128 of file qobject.h.

Referenced by QDeclarativeCompiler::buildObject(), QDeclarativeCompiler::buildPropertyObjectAssignment(), QDBusAbstractInterface::callWithArgumentList(), QFontDialogPrivate::canBeNativeDialog(), QFileDialogPrivate::canBeNativeDialog(), QDeclarativePropertyPrivate::canConvert(), classIDL(), QDeclarativeListModelParser::compileProperty(), QDBusConnectionPrivate::connectRelay(), QDeclarativePathView::createdItem(), QDeclarativeItemPrivate::data_append(), QMetaObjectBuilder::deserialize(), QDBusConnectionPrivate::disconnectRelay(), findSlot(), QDeclarativeCompiler::genObject(), QDeclarativePathViewPrivate::getItem(), QDeclarativeRectanglePrivate::getPen(), QDeclarativeBorderImagePrivate::getScaleGrid(), QDeclarativeFlickablePrivate::init(), QDeclarativePathViewPrivate::init(), QtDBusScriptPlugin::initialize(), QAxServerBase::isPropertyExposed(), QDeclarativeKeysAttached::keyPressed(), QDeclarativeBorderImage::load(), QDeclarativeImageBase::load(), QSignalEventGenerator::metaObject(), QDBusInterface::metaObject(), QAxObject::parentMetaObject(), QAxWidget::parentMetaObject(), QStyleSheetStyle::polish(), QBBButtonEventNotifier::QBBButtonEventNotifier(), qDBusInterfaceInObject(), qDBusIntrospectObject(), qDBusUpdateDispatchStatus(), QDeclarativeBoundSignalParameters::QDeclarativeBoundSignalParameters(), QDeclarativeCompiledBindings::QDeclarativeCompiledBindings(), QDeclarativeExpression::QDeclarativeExpression(), QDeclarativeFastProperties::QDeclarativeFastProperties(), QDeclarativePixmapReply::QDeclarativePixmapReply(), QDeclarativeWatchProxy::QDeclarativeWatchProxy(), QMetaObjectBuilderPrivate::QMetaObjectBuilderPrivate(), QScript::qobjectProtoFuncToString(), QSignalSpy::QSignalSpy(), QtWndProc(), readAllProperties(), QDBusAdaptorConnector::relay(), QDBusAdaptorConnector::relaySignal(), QDBusConnectionPrivate::relaySignal(), resolveClassName(), QDeclarativePixmapReader::run(), QDBusAbstractAdaptor::setAutoRelaySignals(), QDBusConnectionPrivate::setConnection(), QTextControlPrivate::setContent(), QDeclarativeRectangle::setGradient(), QDeclarativeBorderImage::setGridScaledImage(), QDeclarativeVisualDataModel::setModel(), QmlJSDebugger::InspectorProtocol::toString(), QPropertyAnimation::updateState(), QGraphicsView::viewportEvent(), and QDBusMetaObjectGenerator::write().

◆ staticQtMetaObject

const QMetaObject QObject::staticQtMetaObject
staticprotected

The documentation for this class was generated from the following files: