Presentation is loading. Please wait.

Presentation is loading. Please wait.

Modèles et concepts de QT4 .

Similar presentations


Presentation on theme: "Modèles et concepts de QT4 ."— Presentation transcript:

1 Modèles et concepts de QT4 .
In this lecture we will try to cover the theoretical aspects of the QObject class, which makes Qt what Qt is. Understanding this is key to the rest of the lectures. The first half of the lecture will be devoted to the QObject class, meta-information and the possibilities given by these classes. The second half of the lecture will be devoted to signals and slots which is the single most important concept of Qt. Recommended reading before the lecture:

2 QObject De lui dépendent des mécanismes tels que
QObject est la classe mère de presque toutes les classes de QT De lui dépendent des mécanismes tels que Les évènements signaux et slots propriétés Gestion de la mémoire The QObject class is essential to Qt It is the base class of most “active” classes in Qt, including all widgets (the image shows only a subset of the classes derived from QObject, it also shows that those subclasses are themselves inherited by other classes) The QObject implements many of the features that makes Qt what it is, such as: signals slots properties simplified memory management

3 Meta data Chaque QObject à un meta objet Un meta objet connait:
class name (QObject::className) inheritance (QObject::inherits) properties signals and slots general information (QObject::classInfo) QObjects carry meta-data, that is data about the object itself. This makes it possible to add introspection to Qt, for instance to ask a class which methods it has Every QObject has a meta object which can be retreived using the metaObject method. The meta object knows about the class, its name, base class, properties, methods, slots and signals. Continues

4 Meta data les meta-données sont utilisées au moment de la compilation par le meta compilateur, moc. Ordinary C++ Build Process sources *.cpp compiles object files *.o links executables includes headers *.h While providing C++ developers with meta data, Qt is still based 100% on C++. There is no other language involved. Instead, moc, the meta object compiler, parses the C++ code and generates even more C++ code. The figure shows an ordinary C++ build process, headers are included, sources compiled, object files linked and the end result is executable code. (Even libraries are, more or less, executable code, so this holds true in all cases.) Continues

5 Meta data les meta-données sont utilisées au moment de la compilation par le meta compilateur, moc. le moc extrait les données depuis les en-têtes. Qt C++ Build Process sources *.cpp compiles object files *.o links executables includes compiles headers *.h mocs generated moc_*.cpp So, Qt adds a new step to the build process. Moc parses class declarations and generates C++ code that implements the specific meta object. Notice that it is possible to have the moc work on a source file directly, and then include the result into the same source file, but that is only useful in the special case of a QObject derived class only used from within one single file. All this is handled by QtCreator, so you do not need to worry about it. There are solutions taking care of this step for all other build environments as well (command line builds, Visual Studio, Eclipse, Xcode, etc) Continues

6 Meta data A quoi ressemble le moc?
Veiller à ce que la classe hérite de Qobject en premier A quoi ressemble le moc? class MyClass : public QObject { Q_OBJECT Q_CLASSINFO("author", "John Doe") public: MyClass(const Foo &foo, QObject *parent=0); Foo foo() const; public slots: void setFoo( const Foo &foo ); signals: void fooChanged( Foo ); private: Foo m_foo; }; La macro Q_OBJECT Informations à propos de la classe Mots-clefs Qt What does moc look for in your class declarations? First of all, you need to inherit QObject directly or indirectly. If you are inheriting multiple classes, your QObject (decendant) must appear first. You cannot inherit from QObject twice (directly or indirectly). You then need to put the Q_OBJECT macro in your class declaration, in the private section. By convention, and historical limitations, this is usually placed first. You can then add class info, and more, through special macros. For instance, in this case the key “author” is given the value “John Doe”. Qt also adds some special keywords (just macros, from the compiler's point of view) which will discuss later on.

7 Signaux et Slots Lier dynamiquement une action ou un évènement à une méthode de traitement. One of the key factors of Qt is the signals and slots mechanism. It is a mechanism to dynamically and loosely tie together events and changes with reactions Dynamically = at run-time Loosely = sender and receiver do not know each other events = timer event, clicks, etc. Not to be confused with actual events (QEvent). state changes = size changed, text changed, value changed, etc reactions = source code that actually does something This is what makes a Qt application tick Continues

8 Signaux et Slots en Action
emit clicked(); Looking at an example from the first lecture. The three buttons all emit the clicked signal when they are clicked by the user (or activated by other means). They do this regardless whether something is connected to them or not, and regardless of what is connected to them. Continues

9 Signaux et Slots en Action
connect(addButton,SIGNAL(clicked()),this,SLOT(...)); private slots: void on_addButton_clicked(); void on_deleteButton_clicked(); clear(); connect( clearButton, SIGNAL(clicked()), listWidget, SLOT(clear())); We choose to connect the buttons to the list widget's clear slot, and two custom slots in our custom code. As said earlier, the buttons do not care what they are connected to, and the slots are equally independent of what triggers them. You can even call them programatically as ordinary functions. Continues

10 Qu'est-ce qu'un slot ? Un slot est défini dans l'une des sections suivantes: Plusieurs signaux peuvent être connectés à un même slot Il est implémenté comme une méthode classique Il peut être appelé comme une méthode classique public slots: void aPublicSlot(); protected slots: void aProtectedSlot(); private slots: void aPrivateSlot(); A slot is an ordinary function, just that it can be connected to signals. They do not have to be connected, you can call a slot like any other function, and you implement it as usual. Slots are declared in one of the sections public, protected and private slots. These access restrictions work as intended when calling the function, but a private or protected slot can be connected to any other signal, so they can be triggered from outside the class. Slots can return values, but connections cannot carry return arguments. Any number of signals can be connected to a single slot. This means that a single slot can serve several sources of events – think keyboard shortcut, button, etc. Continues connect(src, SIGNAL(sig()), dest, SLOT(slt()));

11 Qu'est-ce qu'un signal ? Un signal est défini dans la section signals
Un signal retourne toujours void Un signal ne doit pas être implémenté Le moc fournit une implémentation Un signal peut être connecté à plusieurs slots Les slots sont alors activés dans un ordre arbitraire Un signal est émis en utilisant le mot clef emit signals: void aSignal(); Signals are defined in the signals section. This section can be considered protected, as a signal can only be emitted from within a class or its decendants. Signals always return void, and must not be implemented. Instead, moc provides function bodies that trigger the actual slot-activation-code. A signal can be connected to any number of slots, so a single event can trigger multiple reactions. It is fully possible to connect signals and slots across threads. Third party libraries such as Qxt ( Inside a signal emitting class, you use the emit keyword to emit a signal. The emit keyword is defined as nothing, what actually takes place is a call to the signal function which calls the slots. Continues emit aSignal();

12 Faire une connexion QObject* QObject::connect( src, SIGNAL( signature ), dest, SLOT( signature ) ); <nom du signal> ( <arguments>) <nom du slot> ( <arguments>) You can make signals to slots connections between any two QObjects. Qt verifies that the signatures of the signal and slot match. The signature consists of the name of the signal or slot followed by the argument types. There must be no values nor variable names in the signature. It is also recommended to stick to using standard types, e.g. the ItemClass custom type reduces the reusability and should thus be avoided. Continues

13 Faire une connexion Le slot doit avoir autant d'arguments que le signal et ils doivent être de même type. Signals rangeChanged(int,int) valueChanged(int) textChanged(QString) clicked() Slots setRange(int,int) setValue(int) updateDialog() When matching signatures, Qt is very forgiving. The basic rule is that Qt cannot create or convert values, but apart from that anything is allowed (i.e. skipping arguments). The examples on the slide demonstrate this. The errors are (from the top): missing the last int (cannot create) QString does not match int (cannot convert) missing the only int (cannot create) Continues

14 Connexions malheureuses
Connexion des deux côtés connect(dial1, SIGNAL(valueChanged(int)), dial2, SLOT(setValue(int))); connect(dial2, SIGNAL(valueChanged(int)), dial1, SLOT(setValue(int))); A common scenario for signals and slots is to synchronize a pair of widgets. This is implemented by interconnecting two objects. (Refer to the example). If the value of dial1 changes, it emits valueChanged, which changes the value of dial2, that emits valueChanged, which changes the value of dial1, that emits... To avoid an infinite loop (which results in endless recursion, which will make the stack grow until you run out of memory and then crash miserably) the setValue function ignores attempts to set the current value.


Download ppt "Modèles et concepts de QT4 ."

Similar presentations


Ads by Google