Signals, slots and the Meta Object Compiler

Signals and slots are used for communication between objects. The signal/slot mechanism is a central feature of Qt, and is implemented using the moc (Meta Object Compiler) and some preprocessor defines.

All classes that contain signals and/or slots must inherit from QObject or one of its subclasses, and must mention Q_OBJECT in its declaration.

Usage

Syntactically, signals and slots are categories. A minimal C++ class declaration might read:
    class Foo : public Bar
    {
    public:
        Foo();
        void setSomethig(int);
        int something();
    private:
        int internal;
    };
This little class has an internal state and public methods to access that state. A small Qt class might read:
    class QFoo : public QObject
    {
        Q_OBJECT;
    public:
        Foo( QObject *parent=0, const char *name=0);
        int something() { returns internal; }
    signals:
        void somethingChanged(int)
    public slots:
        void setSomething(int);
    private:
        int internal;
    };
This class has the same internal state, and also public methods to access the state, but in addition it has some support for component programming using signals and slots: This class can tell someone that its state has changed by emitting a signal, somethingChanged(), and it has a slot which other objects may send signals to.

To emit a signal, you say emit signal(arguments). The next code fragment shows this.

Slots are implemented by the application programmer (that's you). Here is a possible implementation of QFoo::setSomething():

    void QFoo::setSomething(int s) {
        if (s != internal) {
            internal = s;
            emit somethingChanged(s);
        }
    }
The example may appear useless, but anyway, here is one way to connect two of these already useless objects together:
    QFoo yo, go;

    connect(&yo, SIGNAL(somethingChanged(int)), &go, SLOT(setSomething(int)));
Then a call to yo.setSomething() will make yo emit a signal, which go will receive and act on. Since this action changes go's internal state, it too emits a signal, which nobody receives, so it disappears into hyperspace.

In this way two objects can work together without knowing each other, as long as there is someone around to set up a connection between them initially.

The preprocessor changes or removes the signals, slots and emit keywords so the compiler won't see anything it can't digest.

Each meta object requires one additional Makefile rule per class and one additional C++ source file (generated by the meta object compiler). Inside Qt, we have chosen to name the meta-source files m*.cpp, the * is derived from the header file name. So for QLCDNumber we have one header file, qlcdnum.h, one moc-generated C++ file, mlcdnum.cpp and one real source file, qlcdnum.cpp. mlcdnum.cpp is generated by this rule:

    mlcdnum.cpp: qlcdnum.h
        ..somewhere../bin/moc qlcdnum.h -o mlcdnum.cpp
Both C++ files are compiled and linked in the usual way.

Signals

Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Only the class that defines a signal and its subclasses can emit the signal.

A list box, for instance, emits both highlighted() and activated() signals. Most object will probably only be interested in activated() but some may want to know about which item in the list box is currently highlighted. If the signal is interesting to two different objects you just connect the signal to slots in both widgets.

Signals are automatically implemented by the moc and must not be implemented in the .cpp file. They can never have return types.

Slots

A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them. Since slots are normal member functions with just a little extra spice, they have access rights like everyone else. A slot's access right determines who can connect to it. A slot's arguments cannot have default values.

A public slots: section contains slots that anyone can connect signals too. This is very useful for component programming: You create objects that know nothing about each other, connect their signals and slots so information is passed correctly, and, like a model railway, turn it on and leave it running.

A protected slots: section contains slots that this class and its subclasses may connect signals too. This is intended for slots that are part of the class' implementation rather than its interface towards the rest of the world.

A private slots: section contains slots that only the class itself may connect signals too. This is intended for very tightly connected classes, where even subclasses aren't trusted to get the connections right.

Of course, you can also define slots to be virtual. We have found this to be very useful.

Signals and slots are fairly efficient. Of course there's some loss of speed compared to "real" callbacks due to the increased flexibility, but the loss is fairly small, we measured it to approximately 50 microseconds on a SPARC 2, so the simplicity and flexibility the mechanism affords is well worth it.

The Qt Meta Object Compiler

The meta object compiler (moc) parses a C++ header file and generates C++ code that initializes the meta object. The meta object contains names of all signal and slot members, as well as pointers to these functions.

Example

Here is a simple commented example (butchered from qlcddum.h). Unlike most of the Qt documentation, this isn't peppered with links, so if you want to read about QLCDNumber or any of its parent classes please do it now, before you go through the example.
    #include "qframe.h"
    #include "qbitarry.h"

    class QLCDNumber : public QFrame
QLCDNumber inherits QObject, which has most of the signal/slot knowledge, via QFrame and QWidget, and #include's the relevant declarations.
    {
        Q_OBJECT
Q_OBJECT is expanded by the preprocessor to declare several member functions that are implemented by the moc; if you get compiler errors along the lines of "virtual function QButton::className not defined" you have probably forgotten to mention Q_OBJECT and run the moc.
    public:
        QLCDNumber( QWidget *parent=0, const char *name=0 );
        QLCDNumber( uint numDigits, QWidget *parent=0, const char *name=0 );
It's not obviously relevant to the moc, but if you inherit QWidget you almost certainly want to have parent and name arguments to your constructors, and pass them to the parent constructor.

Some destructors and member functions are omitted here, the moc ignores member functions.

    signals:
        void    overflow();
QLCDNumber emits a signal when it is asked to show an impossible value.

"But I don't care about overflow," or "But I know the number won't overflow." Very well, then you don't connect the signal to any slot, and everything will be fine.

"But I want to call two different error functions when the number overflows." Then you connect the signal to two different slots. Qt will call both (in arbitrary order).

    public slots:
        void    display( int num );
        void    display( long num );
        void    display( float num );
        void    display( double num );
        void    display( const char *str );
        void    setMode( Mode );
        void    smallDecimalPoint( bool );
A slot is a receiving function, used to get information about state changes in other widgets. QLCDNumber uses it, as you can see, to set the displayed number. Since display() is part of the class' interface with the rest of the program, the slot is public.

Several of the example program connect the newValue signal of a QScrollBar to the display slot, so the LCD number continuously shows the value of the scroll bar.

(Note that display() is overloaded; Qt will select the appropriate version when you connect a signal to the slot. With callbacks, you'd have to find five different names and keep track of the types yourself.)

Some more irrelevant member functions have been omitted from this example.

    };

Moc output

This is really internal to Qt, but for the curious, here is the meat of the resulting mlcdnum.cpp:
    const char *QLCDNumber::className() const
    {
        return "QLCDNumber";
    }
    
    QMetaObject *QLCDNumber::metaObj = 0;
    
    void QLCDNumber::initMetaObject()
    {
        if ( metaObj )
        return;
        if ( !QFrame::metaObject() )
        QFrame::initMetaObject();
That last line is because QLCDNumber inherits QFrame. The next part, which sets up the table/signal structures, has been deleted for brevity.
    }
    
    // SIGNAL overflow
    void QLCDNumber::overflow()
    {
        activate_signal( "overflow()" );
    }
One function is generated for each signal, and at present it almost always is a single call to activate_signal(), which finds the appropriate slot or slots and passes on the call.

Please don't call activate_signal() directly, we may well move some code from activate_signal into the generated signal functions before 1.0. More generally, don't use knowledge of Qt's intestines, or risk unpredictable results now or later.


Generated at 16:17, 1995/06/30 by the webmaster at Troll Tech