Trolltech| Documentation| Qt Quarterly |
Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type.
Dynamic Signals and Slots |
by Eskil Abrahamsen Blomfeldt |
A simple clickable button tutorial. In this tutorial, we'll show you how to start handling with Qt for Python's signals and slots.Basically, this Qt feature allows your graphical widgets to communicate with other graphical widgets or your own python code. Sending Python values with signals and slots. On the #pyqt channel on Freenode, Khertan asked about sending Python values via Qt's signals and slots mechanism. The following example uses the PyQtPyObject value declaration with an old-style signal-slot connection, and again when the signal is emitted, to communicate a Python dictionary. The argv coming from the signal is an array of pointers to the arguments. The problem is that these pointers point to the stack of the signal where the arguments are. Once the signal returns, they will not be valid anymore. So we'll have to copy the parameter values of the function on the heap.
Signals and slots are declared at compile-time, and normally youcannot add new signals and slots to a meta-object at run-time. Insome situations, it is useful to extend a meta-object while anapplication is running to obtain truly dynamic functioninvocation and introspection.
The need for the dynamic addition of signals and slots arises when bindinga script interpreter, such as Qt Script for Applications (QSA), to theC++ code in your application. In QSA, it is possible to use Qt'smeta-object system to communicate between objects created in theC++ code and objects created in a script. Qt 4's meta-object systemmakes this sort of extension possible, with a little bit of hackery.
This article will get you started writing a dynamic signals and slotsbinding layer for Qt 4. We will review an abstract base class,DynamicQObject, that offers the required functionality.The 'mini-framework' presented here can serve as afoundation for doing more advanced extensions of Qt's meta-objectsystem.
Expanding the Q_OBJECT Macro |
Any QObject subclass that declares signals andslots must contain the Q_OBJECT macroin its definition. This is a magic macro that expands to a set of privatedeclarations:
Q_OBJECT is 'magic' becauseqmake and mocwill recognize it and automagically generate code for the class's meta-objectduring compilation of the project.
We want to write a DynamicQObject class that mimics part of thebehavior of the moc but that does not limit us to staticallydeclared signals and slots. Since we need to prevent the moc fromcompiling our class, we can't use theQ_OBJECT macro; instead, wewill copy its definition and insert it into our code.
The Q_OBJECT macro is defined insrc/corelib/kernel/qobjectdefs.h (which is included by<QObject>). It declares a number of functions that must bereimplemented to fully support Qt's meta-object system. For thepurposes of this article, it will be sufficient to reimplement just oneof these functions:
When a signal is emitted, Qt uses qt_metacall() to invoke theslots connected to the signal. The first parameter, call, is thenset to QMetaObject::InvokeMetaMethod.(The qt_metacall() function is also used for other types of accessto the meta-object, such as setting or getting properties.)
The second parameter is an index that uniquely identifies a signal orslot in the hierarchy of classes inherited by the current object. Thelast parameter is an array that contains pointers to arguments,preceded by a pointer to the location where the return value shouldbe placed (if any).
The DynamicQObject Class Definition |
Here's the definition of the DynamicQObject class:
Qt Connect Signal Slot
The intended usage pattern of DynamicQObject involves subclassingit and adding some functionality. Whenever we add a slot to anobject, we would expect this slot to execute code when it is called.Since this part of the mechanism is dependent on the language towhich we want to bind, it must be implemented in a subclass.
These can range from your ordinary playing cards to cards used in games like Uno, bridge and rummy. Casino poker chip iset. Playing CardsWhile most poker chip sets include several decks of cards, you can also find new or additional seperately. The buttons for ‘big blind’ and ‘little blind’ help you keep track of who’s turn it is to put in a mandatory bet.
The pure virtual function createSlot() returns an instance ofan appropriate subclass of the abstract class DynamicSlot thathandles function invocation for your specific language binding.DynamicSlot is defined as follows:
DynamicSlot subclasses must reimplement the call() functionto handle a slot invocation. The arguments array's first entry isa pointer to a location where we can put the return value. Thispointer is null if the signal's return type is void.
The rest of the array contains pointers to arguments passed to theslot, in order of declaration. We must cast these pointers tothe correct data types before we can use them. For example, if theslot expects a parameter of type int as its first parameter, thefollowing code would be safe:
Implementation of connectDynamicSlot() |
The connectDynamicSlot() function connects a static signaldeclared in an arbitrary QObject instance toa dynamic slot in the current DynamicQObject instance. The functiontakes a pointer to the sender object (the receiver is always this)and the signatures of the signal and slot. The function returns falseon error.
The first step is to normalize the signatures passed to the function.This will remove meaningless whitespace in the signatures, making itpossible for us to recognize them. Then, we check whether thesignatures are compatible, to avoid crashes later.
If the argument lists are compatible for the two functions, wecan start resolving the signal and slot indexes. The signal isresolved using introspection into the providedQObject object. If the signal was not found,we return false.
Resolving the (dynamic) slot is a bit more work:
We check whether the slot signature has been registered before in thesame DynamicQObject instance. If it hasn't, we add it to our listof dynamic slots.
We use aQHash<QByteArray, int>called slotIndices and aQList<DynamicSlot *> calledslotList to store the information needed for the dynamic slots.
Finally, we register the connection with Qt's meta-object system.When we notify Qt about the connection, we must add the number ofmethods inherited from QObject to our slotId.
The connectDynamicSignal() function is very similar toconnectDynamicSlot(), so we won't review it here.
Implementation of qt_metacall() |
Qt's meta-object system uses the qt_metacall() function to accessthe meta-information for a particular QObjectobject (its signals, slots, properties, etc.).
Since the call may indicate access to the meta-object of theQObject base class, we must start by callingQObject's implementation of the function.This call will return a new identifier for the slot, indexing the methods inthe upper part of the current object's class hierarchy (the current classand its subclasses).
If the QObject::qt_metacall() callreturns -1, this means that the metacall has been handled byQObject and that there is nothing to do.In that case, we return immediately. Similarly, if the metacall isn't a slotinvocation, we follow QObject's conventionand return an identifier that can be handled by a subclass.
In the case of a slot invocation, the identifier must be a valididentifier for the DynamicQObject object. We don't allowsubclasses to declare their own signals and slots.
If all goes well, we invoke the specified slot (usingDynamicSlot::call()) and return -1 to indicate that themetacall has been processed.
Implementation of emitDynamicSignal() |
The last function we need to review is emitDynamicSignal(), whichtakes a dynamic signal signature and an array of arguments. The functionnormalizes the signature then emits the signal, invoking any slotsconnected to it.
The arguments array can be assumed to contain valid pointers. A simpleexample of how to do this can be found in the accompanying example'ssource code, but as a general rule,QMetaType::construct() isyour friend when you are doing more advanced bindings.
If the (dynamic) signal exists (i.e., it has been connected to aslot), the function simply usesQMetaObject::activate() to tellQt's meta-object system that a signal is being emitted. It returnstrue if the signal has previously been connected to a slot;otherwise it returns false.
Pitfalls and Pointers |
Having explained the architecture of this simple framework, I'd liketo conclude by explaining what the framework doesn't do and howyou can expand on it or improve it to suit your needs.
- Only a subset of the features in Qt's meta-object system is supported by DynamicQObject. Ideally, we would reimplement all the functions declared by the Q_OBJECT macro.
- Declaring new signals and slots in DynamicQObject subclasses will cause an application to crash. The reason for this is that the meta-object system expects the number of methods declared in a meta-object to be static. A safer workaround would be to use a different pattern than inheritance to employ dynamic signals and slots.
- The framework is sensitive to misspellings. For instance, if you try to connect two distinct signals to the same dynamic slot and misspell the signature of the slot in one of the connect calls, the framework will create two separate slots instead of indicating a failure. To handle this in a safer way, you could implement a register() function and require the user to register each signal and slot before connecting to them.
- The framework cannot handle connections where both the signals and the slot are dynamic. This can easily be written as an extension of the DynamicQObject class.
- Removing connections is not possible with the current framework. This can easily be implemented in a similar way to establishing connections. Make sure not to change the order of entries in slotList, because the list is indexed by slot ID.
- In real-world applications, you may need to do type conversions before passing parameters between functions declared in scripts and functions declared in C++. The DynamicQObject class can be expanded to handle this in a general way by declaring a set of virtual functions that can be reimplemented for different bindings.
This document is licensed under the Creative Commons Attribution-Share Alike 2.5 license.
Copyright © 2006 Trolltech | Trademarks |