Qt logo

QObject Class Reference


The QObject class is the base class of all Qt objects that can deal with signals, slots and events. More...

#include <qobject.h>

Inherited by QAccel, QApplication, QClipboard, QDataPump, QDragManager, QDragObject, QFileIconProvider, QGManager, QLayout, QNPInstance, QSenderObject, QSignal, QSignalMapper, QSocketNotifier, QTimer, QToolTipGroup, QValidator and QWidget.

List of all member functions.

Public Members

Signals

Static Public Members

Protected Members

Static Protected Members

Related Functions

(Note that these are not member functions.)

Detailed Description

The QObject class is the base class of all Qt objects that can deal with signals, slots and events.

Qt provides a very powerful mechanism for seamless object communication; signal/slot connections. The signal/slot mechanism is an advanced way of making traditional callback routines.

Example:

    //
    // The Mandelbrot class uses a QTimer to calculate the mandelbrot
    // set one scanline at a time without blocking the CPU.
    // It inherits QObject to use signals and slots.
    // Calling start() starts the calculation. The done() signal is
    // emitted when it has finished.
    // Note that this example is not complete. Feel free to complete it.
    //

    class Mandelbrot : public QObject
    {
        Q_OBJECT                                // required for signals/slots
    public:
        Mandelbrot( QObject *parent=0, const char *name );
        ...
    public slots:
        void    start();
    signals:
        void    done();
    private slots:
        void    calculate();
    private:
        QTimer  timer;
        ...
    };

    //
    // Constructs and initializes a Mandelbrot object.
    //

    Mandelbrot::Mandelbrot( QObject *parent=0, const char *name )
        : QObject( parent, name )
    {
        connect( &timer, SIGNAL(timeout()), SLOT(calculate()) );
        ...
    }

    //
    // Starts the calculation task. The internal calculate() slot
    // will be activated every 10 milliseconds.
    //

    void Mandelbrot::start()
    {
        if ( !timer.isActive() )                // not already running
            timer.start( 10 );                  // timeout every 10 ms
    }

    //
    // Calculates one scanline at a time.
    // Emits the done() signal when finished.
    //

    void Mandelbrot::calculate()
    {
        ...                     // perform the calculation for a scanline
        if ( finished ) {       // no more scanlines
           timer.stop();
           emit done();
        }
    }

When an object has changed in some way that might be interesting for the outside world, it emits a signal to tell whoever is listening. All slots that are connected to this signal will be activated (called). It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)

There is no limitation on how many slots that can be connected to a signal. The slots will be activated in the order they were connected to the signal.

Notice that the Q_OBJECT macro is mandatory for any object that implement signals or slots. You also need to run the moc program (Meta Object Compiler) on the source file.

The signal/slot mechanism allows objects to easily reused, because the object that emits a signal does not need to know what the signals are connected to.

All Qt widgets inherit QObject and use signals and slots. A QScrollBar, for example, emits valueChanged() whenever the scroll bar value changes.

Meta objects are useful for doing more than connecting signals to slots. They also allow the programmer to obtain information about the class to which an object is instantiated from (see isA() and inherits()) or to produce a list of child objects that inherit a particular class (see queryList()).

Examples: widgets/widgets.cpp


Member Function Documentation

QObject::QObject ( QObject * parent=0, const char * name=0 )

Constructs an object with the parent object parent and a name.

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 inside it.

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.

The object name is a text that can be used to identify this QObject. It is not very useful in the current version of Qt, but it will become increasingly important in the future.

The queryList() function searches the object tree for objects that matches a particular object name.

See also: parent(), name() and queryList().

QObject::~QObject () [virtual]

Destroys the object and all its children 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, your program will sooner or later 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.

bool QObject::activate_filters ( QEvent * e ) [protected]

For internal use only.

void QObject::activate_signal ( const char * signal ) [protected]

For internal use only.

void QObject::activate_signal ( const char * signal, const char * ) [protected]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void QObject::activate_signal ( const char * signal, int ) [protected]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void QObject::activate_signal ( const char * signal, long ) [protected]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void QObject::activate_signal ( const char * signal, short ) [protected]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void QObject::badSuperclassWarning ( const char * className, const char * superclassName ) [static protected]

Internal function, called from initMetaObject(). Used to emit a warning when a class containing the macro Q_OBJECT inherits from a class that does not contain it.

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

Examples: xform/xform.cpp

bool QObject::checkConnectArgs ( const char * signal, const QObject * receiver, const char * member ) [virtual protected]

Returns TRUE if the signal and the member arguments are compatible, otherwise FALSE.

Warning: We recommend that you do not reimplement this function but use the default implementation.

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 qobjcoll.h header file.

The latest child added is the first object in the list and the first child is added is the last object in the list.

Note that the list order might change when widget children are raised or lowered. A widget that is raised becomes the last object in the list. A widget that is lowered becomes the first object in the list.

See also: queryList(), parent(), insertChild() and removeChild().

const char * QObject::className () const [virtual]

Returns the class name of this object.

This function is generated by the Meta Object Compiler.

Warning: This function will return an invalid name if the class definition lacks the Q_OBJECT macro.

See also: name(), inherits(), isA() and isWidgetType().

Examples: widgets/widgets.cpp

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

Connects signal from the sender object to member in object receiver.

You must use the SIGNAL() and SLOT() macros when specifying the signal and the member.

Example:

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

This example connects the scroll bar's valueChanged() signal to the label's setNum() slot. It makes the label always display the current scroll bar value.

A signal can even be connected to another signal, i.e. member is a SIGNAL().

    class MyWidget : public QWidget
    {
    public:
        MyWidget();
    ...
    signals:
        void aSignal(int);
    ...
    private:
    ...
        QPushButton *aButton;
    };

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

In its constructor, MyWidget creates a private button and connects the clicked() signal to relay clicked() to the outside world. You can achieve the same effect by connecting the clicked() signal to a private slot and emitting aSignal() in this slot, but that takes a few lines of extra code and is not quite as clear, of course.

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

If a signal is connected to several slots, the slots are activated in arbitrary order when the signal is emitted.

See also: disconnect().

Examples: tictac/tictac.cpp grapher/grapher.cpp drawdemo/drawdemo.cpp hello/hello.cpp movies/main.cpp xform/xform.cpp aclock/aclock.cpp menu/menu.cpp pref/pref.cpp qmag/qmag.cpp showimg/showimg.cpp widgets/widgets.cpp

bool QObject::connect ( const QObject * sender, const char * signal, const char * member ) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Connects signal from the sender object to member in this object.

Equivalent to: QObject::connect(sender, signal, this, member).

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

Reimplemented in QClipboard.

void QObject::destroyed () [signal]

This signal is emitted immediately before the object is destroyed.

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

Examples: xform/xform.cpp

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

  1. Disconnect everything connected to an object's signals:
        disconnect( myObject );
    

  2. Disconnect everything connected to a signal:
        disconnect( myObject, SIGNAL(mySignal()) );
    

  3. Disconnect a specific receiver.
        disconnect( myObject, 0, myReceiver, 0 );
    

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

The sender has no default and may never be 0. (You cannot disconnect signals from more than one object.)

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.

See also: connect().

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Disconnects all signals in this object from member of receiver.

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

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 differs from the above function only in what argument(s) it accepts.

Disconnects signal from member of receiver.

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.

void QObject::dumpObjectTree ()

Dumps a tree of children to the debug output.

This function is useful for debugging.

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

This virtual function receives events to an object and should return TRUE if the event 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().

Reimplemented in QToolBar, QClipboard, QTimer, QSocketNotifier, QLineEdit, QWidget, QMainWindow, QWidgetStack and QSplitter.

bool QObject::eventFilter ( QObject *, QEvent * ) [virtual]

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

The reimplementation of this virtual function must return TRUE if the event should be stopped, or FALSE if the event should be dispatched normally.

See also: installEventFilter().

Reimplemented in QSpinBox, QListView, QMainWindow, QFileDialog, QAccel, QScrollView, QMenuBar, QGManager and QComboBox.

bool QObject::highPriority () const

Returns TRUE if the object is a high priority object, or FALSE if it is a standard priority object.

High priority objects are placed first in list of children, on the assumption that they will be referenced very often.

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

Returns TRUE if this object is an instance of a class that inherits clname, and clname inherits QObject.

(A class is considered to inherit itself.)

Example:

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

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

See also: isA() and metaObject().

void QObject::initMetaObject () [virtual protected]

Initializes the meta object of this object. This method is automatically executed on demand from the QObject constructor.

See also: metaObject().

void QObject::insertChild ( QObject * obj )

Inserts an object obj into the list of child objects.

Warning: This function cannot be used to make a widget a child widget of another. Child widgets can be created only by setting the parent widget in the constructor or by calling QWidget::recreate().

See also: removeChild() and QWidget::recreate().

void QObject::installEventFilter ( const QObject * obj )

Installs an event filter object for this object.

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 object receives events via the eventFilter() function. The eventFilter() function must return TRUE if the event should be stopped, or FALSE if the event should be dispatched normally.

If multiple event filters are installed for a single object, the filter that was installed last will be activated first.

Example:

    #include <qwidget.h>

    class MyWidget : public QWidget
    {
    public:
        MyWidget::MyWidget( QWidget *parent=0, const char *name=0 );
    protected:
        bool  eventFilter( QObject *, QEvent * );
    };

    MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
    {
        if ( parent )                           // has a child widget
            parent->installEventFilter( this ); // then install filter
    }

    bool MyWidget::eventFilter( QObject *, QEvent *e )
    {
        if ( e->type() == Event_KeyPress ) {    // key press
            QKeyEvent *k = (QKeyEvent*)e;
            debug( "Ate key press %d", k->key() );
            return TRUE;                        // eat event
        }
        return FALSE;                           // standard event processing
    }

The QAccel class was implemented using this technique.

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::isA ( const char * clname ) const

Returns TRUE if this object is an instance of a specified class, otherwise FALSE.

Example:

    QTimer *t = new QTimer;             // QTimer inherits QObject
    t->isA("QTimer");                   // returns TRUE
    t->isA("QObject");                  // returns FALSE

See also: inherits() and metaObject().

bool QObject::isWidgetType () const

Returns TRUE if the object is a widget, or FALSE if not.

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

void QObject::killTimer ( int id )

Kills the timer with the identifier id.

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

See also: timerEvent(), startTimer() and killTimers().

Examples: dclock/dclock.cpp grapher/grapher.cpp

void QObject::killTimers ()

Kills all timers that this object has started.

Using this function makes it harder to subclass your class (it kills timers started by subclasses as well as those started by you), so it is generally better to use killTimer().

See also: timerEvent(), startTimer() and killTimer().

Examples: qmag/qmag.cpp

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: class name, super class name, 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. The functions isA() and inherits() also make use of the meta object.

The meta object is created by the initMetaObject() function, which is generated by the meta object compiler and called from the QObject constructor.

const char * QObject::name () const

Returns the name of this object, or 0 if the object does not have a name.

The object name is set by the constructor or by the setName() function. The object name is not very useful in the current version of Qt, but will become increasingly important in the future.

The queryList() function searches the object tree for objects that matches a particular object name.

See also: setName(), className() and queryList().

Examples: widgets/widgets.cpp

const char * QObject::name ( const char * defaultName ) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns the name of this object, or defaultName if the object does not have a name.

This version of name() is particularly useful for debug() calls such as:

    debug( "MyClass::setPrecision(): (%s) unable to set precision to %f",
            name( "unnamed" ), newPrecision );

name( "unnamed" ) is used here so that printf() (used in debug()) will not be asked to output a null pointer.

QObject * QObject::parent () const

Returns a pointer to the parent object.

See also: children().

QObjectList * QObject::queryList ( const char * inheritsClass = 0, const char * objName = 0, bool regexpMatch = TRUE, bool recursiveSearch = TRUE )

Returns a list of child objects found by a query.

The query is specified by:

Arguments:

Example:
    //
    // Sets a Courier 24 point fonts for all children in myWidget that
    // inherit QButton (i.e. QPushButton, QCheckBox, QRadioButton).
    //
    QObjectList *list = myWidget->queryList( "QButton" );
    QObjectListIt it( *list );          // iterate over the buttons
    QFont newFont( "Courier", 24 );
    QObject * obj;
    while ( (obj=it.current()) != 0 ) { // for each found object...
        ++it;
        ((QButton*)obj)->setFont( newFont );
    }
    delete list;                        // delete the list, not the objects

The QObjectList class is defined in the qobjcoll.h header file.

Warning: Delete the list away as soon you have finished using it. You can get in serious trouble if you for instance try to access an object that has been deleted.

See also: children(), parent(), inherits(), name() and QRegExp.

QConnectionList * QObject::receivers ( const char * signal ) const [protected]

Returns a list of objects/slot pairs that are connected to the signal, or 0 if nothing is connected to it.

This function is for internal use.

void QObject::removeChild ( QObject * obj )

Removes the child object obj from the list of children.

Warning: This function will not remove a child widget from the screen. It will only remove it from the parent widget's list of children.

See also: insertChild() and QWidget::recreate().

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

const QObject * QObject::sender () [protected]

Returns a pointer to the object that sent the last signal received by this object.

Warning: This function violates the object-oriented principle of modularity, However, getting access to the sender might be practical 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::setName ( const char * name )

Sets the name of this object to name. The default name is the one assigned by the constructor.

The object name is not very useful in the current version of Qt, but it will become increasingly important in the future.

The queryList() function searches the object tree for objects that matches a particular object name.

See also: name(), className() and queryList().

bool QObject::signalsBlocked () const

Returns TRUE if signals are blocked, or FALSE if signals are not blocked.

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() or killTimers() is called. If interval is 0, then 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, const char *name=0 );
    protected:
        void  timerEvent( QTimerEvent * );
    };

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

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

There is practically no upper limit for the interval value (more than one year). The accuracy depends on the underlying operating system. Windows 95 has 55 millisecond (18.2 times per second) accuracy; other systems that we have tested (UNIX X11, Windows NT and OS/2) can handle 1 millisecond intervals.

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

See also: timerEvent(), killTimer() and killTimers().

Examples: forever/forever.cpp qmag/qmag.cpp biff/biff.cpp

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

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

The default implementation does nothing.

QTimer provides a higher-level interface to the timer functionality, and also more general information about timers.

See also: startTimer(), killTimer(), killTimers() and event().

Reimplemented in QListBox, QMultiLineEdit, QPopupMenu, QScrollBar and QLineEdit.

const char * QObject::tr ( const char * text ) const

Returns a translated version of text, or text if there is no appropriate translated version.


Related Functions

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

Returns a pointer to the child named name of QObject parent which inherits type type.

Returns 0 if there is no such child.

The CHILD macro (defined in qwindowdefs.h) does all this, and also casts the returt type to type *.

Examples:

    QListBox * c = CHILD(myWidget,QListBox,"listboxname");
    if ( c )
        c->insertItem( "another string" );

    QListBox * c = (QListBox *)::qt_find_obj_child(myWidget,QListBox,
                                                   "listboxname");
    if ( c )
        c->insertItem( "another string" );

Search the documentation, FAQ, qt-interest archive and more (uses www.troll.no):


This file is part of the Qt toolkit, copyright © 1995-98 Troll Tech, all rights reserved.

It was generated from the following files:


Copyright İ 1998 Troll TechTrademarks
Qt version 1.42