Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# QObject Class Reference

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

    #include <QObject>

Inherited by QCanvas, Q3FileIconProvider, Q3Dns, QServerSocket, QSocket, QAccel, QNetworkProtocol, QNetworkOperation, QUrlOperator, QEditorFactory, QSqlForm, QStyleSheet, Q3Signal, Q3Action, Q3WhatsThis, QTextCodecPlugin, QCoreSettings, QFile, QCoreApplication, QEventLoop, QObjectCleanupHandler, QProcess, QSignalMapper, QSocketNotifier, QTimer, QTranslator, QLibrary, QPluginLoader, QThread, QAccessiblePlugin, QCopChannel, QDecorationPlugin, QGfxDriverPlugin, QKbdDriverPlugin, QMouseDriverPlugin, QWSServer, QWSInputMethod, QImageFormatPlugin, QWSKeyboardHandler, QPictureFormatPlugin, QAbstractItemDelegate, QAbstractItemModel, QItemSelectionModel, QAction, QActionGroup, QClipboard, QDragObject, QLayout, QSessionManager, QShortcut, QSound, QWidget, QStyle, QStylePlugin, QAbstractTextDocumentLayout, QTextDocument, QTextObject, QButtonGroup, QValidator, QWidgetPlugin, QAbstractSocket, QFtp, QHttp, QTcpServer, QSqlDriver, and QSqlDriverPlugin.

Note: All the functions in this class are reentrant, except connect(), connect(), disconnect(), and disconnect().

- List of all members, including inherited members
- Obsolete members
- Compatibility members

### Writable Properties

- objectName : QString

### Public Functions

- QObject ( QObject * parent = 0 )
- virtual ~QObject ()
- bool blockSignals ( bool block )
- const QObjectList & children () const
- 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 ()
- void dumpObjectTree ()
- QObject * findChild ( const QString & name ) const
- QObjectList findChildren ( const QString & name ) const
- QObjectList findChildren ( const QRegExp & re ) const
- bool inherits ( const char * clname ) const
- void installEventFilter ( const QObject * filterObj )
- bool isAncestorOf ( const QObject * child ) const
- bool isWidgetType () const
- void killTimer ( int id )
- virtual const QMetaObject * metaObject () const
- QObject * parent () const
- QCoreVariant property ( const char * name ) const
- void removeEventFilter ( const QObject * obj )
- void setParent ( QObject * parent )
- bool setProperty ( const char * name, const QCoreVariant & value )
- bool signalsBlocked () const
- int startTimer ( int interval )
- QThread * thread () const

### Public Slots

- void deleteLater ()

### Signals

- void destroyed ( QObject * obj = 0 )

### Static Public Members

- bool connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member, Qt::ConnectionType type = Qt::AutoConnection )
- bool disconnect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member )
- QString tr ( const char * sourceText, const char * comment )
- QString trUtf8 ( const char * sourceText, const char * comment )

### Protected Functions

- virtual void childEvent ( QChildEvent * event )
- virtual void connectNotify ( const char * signal )
- virtual void customEvent ( QCustomEvent * event )
- virtual void disconnectNotify ( const char * signal )
- virtual bool event ( QEvent * e )
- virtual bool eventFilter ( QObject * watched, QEvent * e )
- int receivers ( const char * signal ) const
- QObject * sender () const
- virtual void timerEvent ( QTimerEvent * event )

### Related Non-Members

- T qt_cast ( QObject * o )

## Detailed Description

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

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. 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(), and get the list of tree roots using objectTrees().

Every object has an objectName() and can report its className() and whether it inherits() another class in the QObject inheritance hierarchy.

When an object is deleted, it emits a destroyed() signal. You can catch this signal to avoid dangling references to QObjects. The QPointer class provides an elegant way to use this feature.

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 moc program (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 undefined behavior.

All Qt widgets inherit QObject. The convenience function isWidgetType() returns whether an object is actually a widget. It is much faster than inherits("QWidget").

Some QObject functions, e.g. children(), objectTrees() and findChildren() return a QObjectList. A QObjectList is a QList of QObjects.

## Property Documentation

### objectName : QString

This property holds the name of this object.

You can find an object by name (and type) using findChild(). You can find a set of objects with findChildren().

        qDebug("MyClass::setPrecision(): (%s) invalid precision %f",
                objectName().local8Bit(), newPrecision);

Access functions:

- QString objectName () const
- void setObjectName ( const QString & name )

See also className().

## Member Function Documentation

### QObject::QObject ( QObject * parent = 0 )

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(), and findChildren().

### QObject::~QObject () `[virtual]`

Destroys the object, deleting all its child objects.

All signals to and from the object are automatically disconnected.

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 QObject::destroyed() signal gives you an opportunity to detect when an object is destroyed.

Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly from a thread that is not the GUI thread. Use the QObject::deleteLater() method instead, which will cause the event loop to delete the object after all pending events have been delivered to the object.

### bool QObject::blockSignals ( bool block )

Blocks signals if block is true, or unblocks signals if block is false.

Emitted signals disappear into hyperspace if signals are blocked. Note that the destroyed() signals will be emitted even if the signals for this object have been blocked.

### void QObject::childEvent ( QChildEvent * event ) `[virtual protected]`

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.

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

The polished 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() and QChildEvent.

### const QObjectList & QObject::children () const

Returns a list of child objects, or 0 if this object has no children.

The QObjectList class is defined in the `qobjectlist.h` header file.

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(), and setParent().

### bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member, Qt::ConnectionType type = Qt::AutoConnection ) `[static]`

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

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

        QLabel     *label  = new QLabel;
        QScrollBar *scroll = new QScrollBar;
        QObject::connect(scroll, 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: QObject::connect(scroll, SIGNAL(valueChanged(int v)), label, SLOT(setNum(int v)));

A signal can also be connected to another signal:

        class MyWidget : public QWidget
        {
            Q_OBJECT
        public:
            MyWidget();

        signals:
            void myUsefulSignal();

        private:
            QPushButton *aButton;
        };

        MyWidget::MyWidget()
        {
            aButton = new QPushButton(this);
            connect(aButton, SIGNAL(clicked()), SIGNAL(myUsefulSignal()));
        }

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 an arbitrary order 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 member, or if their signatures aren't compatible.

A signal is emitted for every connection you make, so if you duplicate a connection, two signals will be emitted. You can always break a connection using `disconnect()`.

Note: function is thread-safe.

See also disconnect().

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

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Connects signal from the sender object to this object's member.

Equivalent to connect(sender, signal, `this`, member, type).

Note: function is thread-safe.

See also disconnect().

### void QObject::connectNotify ( const char * signal ) `[virtual protected]`

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

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() and disconnectNotify().

### void QObject::customEvent ( QCustomEvent * event ) `[virtual protected]`

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 `User` item of the QEvent::Type enum, and is typically a QCustomEvent or QCustomEvent subclass. The event is passed in the event parameter.

See also event() and QCustomEvent.

### void QObject::deleteLater () `[slot]`

Performs a deferred deletion of this object.

Instead of an immediate deletion this function schedules a deferred delete event for processing when Qt returns to the main event loop.

### void 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.

### bool QObject::disconnect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member ) `[static]`

Disconnects signal in object sender from member in object receiver.

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

Note: function is thread-safe.

See also connect().

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

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Disconnects signal from member of receiver.

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

Note: function is thread-safe.

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

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Disconnects all signals in this object from receiver's member.

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

### void QObject::disconnectNotify ( const char * signal ) `[virtual protected]`

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

Warning: This function violates the object-oriented principle of modularity. However, it might be useful for optimizing access to expensive resources.

See also disconnect() and connectNotify().

### 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).

### 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).

### bool QObject::event ( QEvent * e ) `[virtual protected]`

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(), and QWidget::event().

### bool QObject::eventFilter ( QObject * watched, QEvent * e ) `[virtual protected]`

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 e, out, i.e. stop it being handled further, return true; otherwise return false.

Example:

        class MyMainWindow : public QMainWindow
        {
        public:
            MyMainWindow(QWidget *parent = 0, const char *name = 0);

        protected:
            bool eventFilter(QObject *obj, QEvent *ev);

        private:
            QTextEdit *textEdit;
        };

        MyMainWindow::MyMainWindow(QWidget *parent, const char *name)
            : QMainWindow(parent, name)
        {
            textEdit = new QTextEdit(this);
            setCentralWidget(textEdit);
            textEdit->installEventFilter(this);
        }

        bool MyMainWindow::eventFilter(QObject *obj, QEvent *ev)
        {
            if (obj == textEdit) {
                if (e->type() == QEvent::KeyPress) {
                    qDebug("Ate key press %d", k->key());
                    return true;
                } else {
                    return false;
                }
            } else {
                // pass the event on to the parent class
                return QMainWindow::eventFilter(obj, ev);
            }
        }

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().

### QObject * QObject::findChild ( const QString & name ) const

Returns the child of this object that is called name, or 0 if there is no such object. The search is performed recursively.

See also findChildren().

### QObjectList QObject::findChildren ( const QString & name ) const

Returns the children of this object that are called name, or an empty list if there are no such objects. The search is performed recursively.

See also findChild().

### QObjectList QObject::findChildren ( const QRegExp & re ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the children of this object that have names matching the regular expression re, or an empty list if there are no such objects. The search is performed recursively.

See also findChild().

### bool QObject::inherits ( const char * clname ) const

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

A class is considered to inherit itself.

Consider using qt_cast<Type *>(object) instead. The method is both faster and safer.

Example:

        QTimer *t = new QTimer;         // QTimer inherits QObject
        t->inherits("QTimer");        // returns true
        t->inherits("QObject");       // returns true
        t->inherits("QButton");       // returns false

        // QScrollBar inherits QWidget and QRangeControl
        QScrollBar *s = new QScrollBar(0);
        s->inherits("QWidget");       // returns true
        s->inherits("QRangeControl"); // returns true

(QRangeControl is not a QObject.)

See also isA(), metaObject(), and qt_cast.

### void QObject::installEventFilter ( const 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 eventFilter(QObject *o, QEvent *e);
        };

        bool KeyPressEater::eventFilter(QObject *o, QEvent *e)
        {
            if (e->type() == QEvent::KeyPress) {
                // special processing for key press
                QKeyEvent *k = (QKeyEvent *)e;
                qDebug("Ate key press %d", k->key());
                return true; // eat event
            } else {
                // standard event processing
                return false;
            }
        }

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.

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

### bool QObject::isAncestorOf ( const QObject * child ) const

Returns true if this object is an parent, (or grandparent and so on to any level), of the given child; otherwise returns false.

### bool QObject::isWidgetType () const

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.

### 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() and startTimer().

### const 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 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 functions isA() and inherits() also make use of the meta object.

### QObject * QObject::parent () const

Returns a pointer to the parent object.

See also children().

### QCoreVariant 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().

See also setProperty(), QCoreVariant::isValid(), and metaObject().

### int QObject::receivers ( const char * signal ) const `[protected]`

Returns the number of receivers connect to the signal.

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.

### void QObject::removeEventFilter ( const 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(), and event().

### 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.

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. The sender is undefined if the slot is called as a normal C++ function.

### void QObject::setParent ( QObject * parent )

Makes the object a child of parent.

See also QWidget::setParent().

### bool QObject::setProperty ( const char * name, const QCoreVariant & value )

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

Returns true if the operation was successful; otherwise returns false.

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

See also property() and metaObject().

### bool QObject::signalsBlocked () const

Returns true if signals are blocked; otherwise returns false.

Signals are not blocked by default.

See also blockSignals().

### 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
        {
            Q_OBJECT
        public:
            MyObject(QObject *parent = 0, const char *name = 0);

        protected:
            void timerEvent(QTimerEvent *);
        };

        MyObject::MyObject(QObject *parent, const char *name)
            : QObject(parent, name)
        {
            startTimer(50);    // 50-millisecond timer
            startTimer(1000);  // 1-second timer
            startTimer(60000); // 1-minute timer
        }

        void MyObject::timerEvent(QTimerEvent *e)
        {
            qDebug("timer event, id %d", e->timerId());
        }

There is practically no upper limit for the interval value (more than one year is possible). Note that QTimer's accuracy depends on the underlying operating system and hardware. Most platforms support an accuracy of 20ms; some provide more. If Qt is unable to deliver the requested number of timer clicks, it will silently discard some.

The QTimer class provides a high-level programming interface with one-shot timers and timer signals instead of events.

See also timerEvent() and killTimer().

### QThread * QObject::thread () const

### void QObject::timerEvent ( QTimerEvent * event ) `[virtual protected]`

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(), and event().

### QString QObject::tr ( const char * sourceText, const char * comment ) `[static]`

Returns a translated version of sourceText, or sourceText itself if there is no appropriate translated version. The translation context is Object with comment (0 by default). All Object subclasses using the Q_OBJECT macro automatically have a reimplementation of this function with the subclass name as context.

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.

Internationalization with Qt

See also trUtf8() and QApplication::translate().

### QString QObject::trUtf8 ( const char * sourceText, const char * comment ) `[static]`

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

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 tr() and QApplication::translate().

## Related Non-Members

### T qt_cast ( QObject * o )

Returns the object o cast to Type if the object is of type Type, otherwise returns 0.