Qt Signal And Slots Callback
Classes- Annotated- Tree- Functions- Home- StructureQte |
One benefit of Qt's solution is that the sender is not dependent on the listener, it's just firing off the signal. In a callback mechanism the sender usually needs to know which listeners to notify. Another benefit, in contrast to many other callback implementations, is that the signals and slots functions are type safe. The callbacks can be signals and slots (via QtCallback) or arbitrary functions using tr1::function, std::function, boost::function or a similar wrapper. Qt 5 provides support for connecting signals to arbitrary functions out of the box and to lambdas when using C11.
In Qt, a signal is emitted when an event occurs. A slot is a function that is called when a signal is emitted. For example, a push button emits a clicked signal when clicked by a user. A slot that is attached to that signal is called when the clicked signal is emitted. The connection mechanism uses a vector indexed by signals. But all the slots waste space in the vector and there are usually more slots than signals in an object. So from Qt 4.6, a new internal signal index which only includes the signal index is used. While developing with Qt, you only need to know about the absolute method index.
Signals and slots are used for communication between objects. Thesignal/slot mechanism is a central feature of Qt and probably thepart that differs most from other toolkits.In most GUI toolkits widgets have a callback for each action they cantrigger. This callback is a pointer to a function. In Qt, signals andslots have taken over from these messy function pointers.
Signals and slots can take any number of arguments of any type. They arecompletely typesafe: no more callback core dumps!
All classes that inherit from QObject or one of its subclasses(e.g. QWidget) can contain signals and slots. Signals are emitted byobjects when they change their state in a way that may be interestingto the outside world. This is all the object does to communicate. Itdoes not know if anything is receiving the signal at the other end.This is true information encapsulation, and ensures that the objectcan be used as a software component.
Slots can be used for receiving signals, but they are normal memberfunctions. A slot does not know if it has any signal(s) connected toit. Again, the object does not know about the communication mechanism andcan be used as a true software component.
You can connect as many signals as you want to a single slot, and asignal can be connected to as many slots as you desire. It is evenpossible to connect a signal directly to another signal. (This willemit the second signal immediately whenever the first is emitted.)
Together, signals and slots make up a powerful component programmingmechanism.
A Small Example
A minimal C++ class declaration might read:
A small Qt class might read:
This class has the same internal state, and public methods to access thestate, but in addition it has support for component programming usingsignals and slots: This class can tell the outside world that its statehas changed by emitting a signal, valueChanged()
, and it hasa slot which other objects may send signals to.
All classes that contain signals and/or slots must mention Q_OBJECT intheir declaration.
Slots are implemented by the application programmer (that's you).Here is a possible implementation of Foo::setValue():
The line emit valueChanged(v)
emits the signalvalueChanged
from the object. As you can see, you emit asignal by using emit signal(arguments)
.
Here is one way to connect two of these objects together:
Calling a.setValue(79)
will make a
emit asignal, which b
will receive,i.e. b.setValue(79)
is invoked. b
will in turnemit the same signal, which nobody receives, since no slot has beenconnected to it, so it disappears into hyperspace.
Note that the setValue()
function sets the value and emitsthe signal only if v != val
. This prevents infinite loopingin the case of cyclic connections (e.g. if b.valueChanged()
were connected to a.setValue()
).
This example illustrates that objects can work together without knowingeach other, as long as there is someone around to set up a connectionbetween them initially.
The preprocessor changes or removes the signals
,slots
and emit
keywords so the compiler won'tsee anything it can't digest.
Run the moc on class definitions that containssignals or slots. This produces a C++ source file which should be compiledand linked with the other object files for the application.
Signals
Signals are emitted by an object when its internal state has changedin 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 thesignal.
A list box, for instance, emits both highlighted()
andactivated()
signals. Most object will probably only beinterested in activated()
but some may want to know aboutwhich item in the list box is currently highlighted. If the signal isinteresting to two different objects you just connect the signal toslots in both objects.
When a signal is emitted, the slots connected to it are executedimmediately, just like a normal function call. The signal/slotmechanism is totally independent of any GUI event loop. Theemit
will return when all slots have returned.
If several slots are connected to one signal, the slots will beexecuted one after the other, in an arbitrary order, when the signalis emitted.
Signals are automatically generated by the moc and must not be implementedin the .cpp file. They can never have return types (i.e. use void).
A word about arguments: Our experience shows that signals and slotsare more reusable if they do not use special types. If QScrollBar::valueChanged() were to use a special type such as thehypothetical QRangeControl::Range, it could only be connected to slotsdesigned specifically for QRangeControl. Something as simple as theprogram in Tutorial 5 would be impossible.
Slots
A slot is called when a signal connected to it is emitted. Slots arenormal C++ functions and can be called normally; their only specialfeature is that signals can be connected to them. A slot's argumentscannot have default values, and as for signals, it is generally a badidea to use custom types for slot arguments.
Since slots are normal member functions with just a little extraspice, they have access rights like everyone else. A slot's accessright determines who can connect to it:
A public slots:
section contains slots that anyone canconnect signals to. This is very useful for component programming:You create objects that know nothing about each other, connect theirsignals and slots so information is passed correctly, and, like amodel railway, turn it on and leave it running.
A protected slots:
section contains slots that this classand its subclasses may connect signals to. This is intended forslots that are part of the class' implementation rather than itsinterface towards the rest of the world.
A private slots:
section contains slots that only theclass itself may connect signals to. This is intended for verytightly connected classes, where even subclasses aren't trusted to getthe connections right.
Of course, you can also define slots to be virtual. We have foundthis to be very useful.
Signals and slots are fairly efficient. Of course there's some loss ofspeed compared to 'real' callbacks due to the increased flexibility, butthe loss is fairly small, we measured it to approximately 10 microsecondson a i586-133 running Linux (less than 1 microsecond when no slot has beenconnected) , so the simplicity and flexibility the mechanism affords iswell worth it.
Meta Object Information
The meta object compiler (moc) parses the class declaration in a C++file and generates C++ code that initializes the meta object. The metaobject contains names of all signal and slot members, as well aspointers to these functions.
The meta object contains additional information such as the object's class name. You can also check if an objectinherits a specific class, for example:
A Real Example
Here is a simple commented example (code fragments from qlcdnumber.h ).
QLCDNumber inherits QObject, which has most of the signal/slotknowledge, via QFrame and QWidget, and #include's the relevantdeclarations.
Q_OBJECT is expanded by the preprocessor to declare several memberfunctions that are implemented by the moc; if you get compiler errorsalong the lines of 'virtual function QButton::className not defined'you have probably forgotten to run the moc or toinclude the moc output in the link command.
It's not obviously relevant to the moc, but if you inherit QWidget youalmost certainly want to have parent and namearguments to your constructors, and pass them to the parentconstructor.
Some destructors and member functions are omitted here, the mocignores member functions.
QLCDNumber emits a signal when it is asked to show an impossiblevalue.
'But I don't care about overflow,' or 'But I know the number won'toverflow.' Very well, then you don't connect the signal to any slot,and everything will be fine.
Qt Signal Slot Callback
'But I want to call two different error functions when the numberoverflows.' Then you connect the signal to two different slots. Qtwill call both (in arbitrary order).
A slot is a receiving function, used to get information about statechanges in other widgets. QLCDNumber uses it, as you can see, to setthe displayed number. Since display()
is part of theclass' interface with the rest of the program, the slot is public.
Several of the example program connect the newValue signal of aQScrollBar to the display slot, so the LCD number continuously showsthe value of the scroll bar.
Note that display() is overloaded; Qt will select the appropriate versionwhen you connect a signal to the slot.With callbacks, you'd have to findfive different names and keep track of the types yourself.
Some more irrelevant member functions have been omitted from thisexample.
Moc output
This is really internal to Qt, but for the curious, here is the meatof the resulting mlcdnum.cpp:
That last line is because QLCDNumber inherits QFrame. The next part,which sets up the table/signal structures, has been deleted forbrevity.
One function is generated for each signal, and at present it almost alwaysis a single call to the internal Qt function activate_signal(), whichfinds the appropriate slot or slots and passes on the call. It is notrecommended to call activate_signal() directly.
Copyright © 2005 Trolltech | Trademarks |
In this chapter we will add some functionality to the window and we will learn how to obtain the values from the different widgets.
About Qt Signals and Slots
Qt (and therefore PySide/PyQt) has built-in signals and slots to control the most common functionalities of widgets. Signals are messages that are emitted by a widget when a certain event or action ocurs (a button was pressed, for example). Slots receive inputs from signals, and are able to perform common actions such as update a value or enable a widget. Signals and slots can be connected together as an easy way of achieving complex behaviors from common wiget interactions.
More info on signals and slot here at ZetCode.
Adding callbacks
The first action we want to be performed is to disable the cornerSpinBox when the cornerCheckBox is unchecked. To achieve this, we will define a callback function insde the class PCBOutlineCreator:
And we will connect the signal emitted when the state of the CheckBox changes to this callback:
Qt Signal Slots Vs Callbacks
Now, we can write the code to be executed inside the callback:
If we run the code, we can see that initially the cornersSpinBox is still enabled. As the initial state was unchecked, the state has not changed on reset and the signal was not sent. In order for the code to run as expected we have to either modify our UI file to make the checkbox enabled by default, modify the UI file to make the spinbox disabled by default, or perform either of these actions programatically using this sentence:
Using Qt Signals and Slots
Previously we added a callback function to disable the cornerSpinBox if it is unchecked. We can achieve the same result easily by connecting the corresponding signal and slot:
In this case, as stateChanged signal returns an int and setEnabled expects a bool, a lambda function was used to convert the value.
Extracting values from the widgets
In order to create the outline for our PCB, we need the dimensions specified by the user in the different widgets. For that pursose, we will add a callback to the save button that prints on the stdout the different values extracted from the widgets. first, we connect the signal to the callback:
And then we add the callback funtion. Inside this function, we request the values of the different widgets and we print them on the stdout:
When we run the code, and press the save button we get the following message on the stdout: