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.
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.cppBoth C++ files are compiled and linked in the usual way.
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.
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.
#include "qframe.h" #include "qbitarry.h" class QLCDNumber : public QFrameQLCDNumber inherits QObject, which has most of the signal/slot knowledge, via QFrame and QWidget, and #include's the relevant declarations.
{ Q_OBJECTQ_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.
};
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.