Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Qt Tutorial 7 - One Thing Leads to Another

Files:

Screenshot of Chapter 7

This example shows how to create custom widgets with signals and slots, and how to connect them together in more complex ways. For the first time, the source is split among several files which we've placed in the tutorials/tutorial/t7 directory.

Line by Line Walkthrough

t7/lcdrange.h

This file is mainly lifted from main.cpp in Chapter 6; only the non-trivial changes are noted here.

 #ifndef LCDRANGE_H
 #define LCDRANGE_H

This, together with the #endif at the end of the file, is the standard C++ construction to avoid errors if a header file happens to be included more than once. If you don't use it already, it is a very good habit to develop.

 #include <QWidget>

<QWidget> is included since our LCDRange class inherits QWidget. The header file of a parent class must always be included - we cheated a bit in the previous chapters, and we let <QWidget> be included indirectly via other header files.

 class QSlider;

This is another classic trick, but one that's much less used often. Because we don't need QSlider in the interface of the class, only in the implementation, we use a forward declaration of the class in the header file and include the header file for QSlider in the .cpp file.

This makes the compilation of big projects much faster, because the compiler usually spends most of its time parsing header files, not the actual source code. This trick alone can often speed up compilations by a factor of two or more.

 class LCDRange : public QWidget
 {
     Q_OBJECT

 public:
     LCDRange(QWidget *parent = 0);

Note the Q_OBJECT. This macro must be included in all classes that contain signals and/or slots. If you are curious, it defines the functions that are implemented in the meta-object file.

     int value() const;

 public slots:
     void setValue(int value);

 signals:
     void valueChanged(int newValue);

These three members make up an interface between this widget and other components in a program. Until now, LCDRange didn't really have an API at all.

value() is a public function for accessing the value of the LCDRange, setValue() is our first custom slot, and valueChanged() is our first custom signal.

Slots must be implemented in the normal way (a slot is also a C++ member function). Signals are automatically implemented in the meta-object file. Signals follow the access rules of protected C++ functions (i.e., they can be emitted only by the class they are defined in or by classes inheriting from it).

The valueChanged() signal is used when the LCDRange's value has changed.

t7/lcdrange.cpp

This file is mainly lifted from main.cpp in Chapter 6, and only the changes are noted here.

     connect(slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)));
     connect(slider, SIGNAL(valueChanged(int)),
             this, SIGNAL(valueChanged(int)));

This code is from the LCDRange constructor.

The first connect() call is the same that you have seen in the previous chapter. The second is new; it connects slider's valueChanged() signal to this object's valueChanged() signal. Yes, that's right. Signals can be connected to other signals. When the first is emitted, the second signal is also emitted.

Let's look at what happens when the user operates the slider. The slider sees that its value has changed and emits the valueChanged() signal. That signal is connected both to the display() slot of the QLCDNumber and to the valueChanged() signal of the LCDRange.

Thus, when the signal is emitted, LCDRange emits its own valueChanged() signal. In addition, QLCDNumber::display() is called and shows the new number.

Note that you're not guaranteed any particular order of execution; LCDRange::valueChanged() may be emitted before or after QLCDNumber::display() is called.

 int LCDRange::value() const
 {
     return slider->value();
 }

The implementation of value() is straightforward. It simply returns the slider's value.

 void LCDRange::setValue(int value)
 {
     slider->setValue(value);
 }

The implementation of setValue() is equally straightforward. Note that because the slider and LCD number are connected, setting the slider's value automatically updates the LCD number as well. In addition, the slider will automatically adjust the value if it is outside its legal range.

t7/main.cpp

     LCDRange *previousRange = 0;

     for (int row = 0; row < 3; ++row) {
         for (int column = 0; column < 3; ++column) {
             LCDRange *lcdRange = new LCDRange;
             grid->addWidget(lcdRange, row, column);
             if (previousRange)
                 connect(lcdRange, SIGNAL(valueChanged(int)),
                         previousRange, SLOT(setValue(int)));
             previousRange = lcdRange;
         }
     }

All of main.cpp is copied from the previous chapter except in the constructor for MyWidget. When we create the nine LCDRange objects, we connect them using the signals and slots mechanism. Each has its valueChanged() signal connected to the previous one's setValue() slot. Because LCDRange emits the valueChanged() signal when its value changes, we are here creating a chain of signals and slots.

Compiling the Application

Creating a makefile for a multi-file application is no different from creating one for a single-file application. If you've saved all the files in this example in their own directory, all you have to do is:

 qmake -project
 qmake

The first command tells qmake to create a .pro file. The second command tells it to create a (platform-specific) makefile based on the project file. You should now be able to type make (or nmake if you're using Visual Studio) to build your application.

Running the Application

On startup, the program's appearance is identical to the previous one. Try operating the slider to the bottom-right.

Exercises

Use the bottom-right slider to set all LCDs to 50. Then set the top six to 30 by clicking on the slider on the row above. Now, use the one to the left of the last one operated to set the first five LCDs back to 50.

Click to the left of the handle on the bottom-right slider. What happens? Why is this the correct behavior?

[Previous: Chapter 6] [Qt Tutorial] [Next: Chapter 8]

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 6
Page suivante

Le Qt Quarterly au hasard

Logo

Bibliothèques et plug-ins

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt qtextended4.4
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web