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  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

Events and Event Filters

In Qt, an event is an object that inherits QEvent. Events are delivered to objects that inherit QObject through calling QObject::event(). Event delivery means that an event has occurred, the QEvent indicates precisely what, and the QObject needs to respond. Most events are specific to QWidget and its subclasses, but there are important events that aren't related to graphics, for example, socket activation, which is the event used by QSocketNotifier for its work.

Some events come from the window system, e.g. QMouseEvent, some from other sources, e.g. QTimerEvent, and some come from the application program. Qt is symmetric, as usual, so you can send events in exactly the same ways as Qt's own event loop does.

Most events types have special classes, most commonly QResizeEvent, QPaintEvent, QMouseEvent, QKeyEvent and QCloseEvent. There are many others, perhaps forty or so, but most are rather odd.

Each class subclasses QEvent and adds event-specific functions; see, for example, QResizeEvent. In the case of QResizeEvent, QResizeEvent::size() and QResizeEvent::oldSize() are added.

Some classes support more than one event type. QMouseEvent supports mouse moves, presses, shift-presses, drags, clicks, right-presses, etc.

Since programs need to react in varied and complex ways, Qt's event delivery mechanisms are flexible. The documentation for QApplication::notify() concisely tells the whole story, here we will explain enough for 99% of applications.

The normal way for an event to be delivered is by calling a virtual function. For example, QPaintEvent is delivered by calling QWidget::paintEvent(). This virtual function is responsible for reacting appropriately, normally by repainting the widget. If you do not perform all the necessary work in your implementation of the virtual function, you may need to call the base class's implementation; for example:

    MyTable::contentsMouseMoveEvent( QMouseEvent *me )
    {
        // my implementation

        QTable::contentsMouseMoveEvent( me ); // hand it on
    }
If you want to replace the base class's function then you must implement everything yourself; but if you only want to extend the base class's functionality, then you implement what you want and then call the base class.

Occasionally there isn't such an event-specific function, or the event-specific function isn't sufficient. The most common example is tab key presses. Normally, those are interpreted by QWidget to move the keyboard focus, but a few widgets need the tab key for themselves.

These objects can reimplement QObject::event(), the general event handler, and either do their event handling before or after the usual handling, or replace it completely. A very unusual widget that both interprets tab and has an application-specific custom event might contain:

  bool MyClass:event( QEvent *evt ) {
      if ( evt->type() == QEvent::KeyPress ) {
          QKeyEvent *ke = (QKeyEvent *)evt;
          if ( ke->key() == Key_Tab ) {
              // special tab handling here
              ke->accept();
              return TRUE;
          }
      } else if ( evt->type() >= QEvent::User ) {
          QCustomEvent *ce = (QCustomEvent*) evt;
          // custom event handling here
          return TRUE;
      }
      return QWidget::event( evt );
  }

More commonly, an object needs to look at another's events. Qt supports this using QObject::installEventFilter() (and the corresponding remove). For example, dialogs commonly want to filter key presses for some widgets, e.g. to modify Return-key handling.

An event filter gets to process events before the target object does. The filter's QObject::eventFilter() implementation is called, and can accept or reject the filter, and allow or deny further processing of the event. If all the event filters allow further processing of an event, the event is sent to the target object itself. If one of them stops processing, the target and any later event filters don't get to see the event at all.

It's also possible to filter all events for the entire application, by installing an event filter on QApplication. This is what QToolTip does in order to see all the mouse and keyboard activity. This is very powerful, but it also slows down event delivery of every single event in the entire application, so it's best avoided.

The global event filters are called before the object-specific filters.

Finally, many applications want to create and send their own events.

Creating an event of a built-in type is very simple: create an object of the relevant type, and then call QApplication::sendEvent() or QApplication::postEvent().

sendEvent() processes the event immediately - when sendEvent() returns, (the event filters and) the object have already processed the event. For many event classes there is a function called isAccepted() that tells you whether the event was accepted or rejected by the last handler that was called.

postEvent() posts the event on a queue for later dispatch. The next time Qt's main event loop runs, it dispatches all posted events, with some optimization. For example, if there are several resize events, they are are compacted into one. The same applies to paint events: QWidget::update() calls postEvent(), which minimizes flickering and increases speed by avoiding multiple repaints.

postEvent() is also often used during object initialization, since the posted event will typically be dispatched very soon after the initialization of the object is complete.

To create events of a custom type, you need to define an event number, which must be greater than QEvent::User, and probably you also need to subclass QCustomEvent in order to pass characteristics about your custom event. See the documentation to QCustomEvent for details.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  2. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  3. Une nouvelle ère d'IHM 3D pour les automobiles, un concept proposé par Digia et implémenté avec Qt 3
  4. Qt Creator 2.5 est sorti en beta, l'EDI supporte maintenant plus de fonctionnalités de C++11 2
  5. Vingt sociétés montrent leurs décodeurs basés sur Qt au IPTV World Forum, en en exploitant diverses facettes (déclaratif, Web, widgets) 0
  6. PySide devient un add-on Qt et rejoint le Qt Project et le modèle d'open gouvernance 1
  7. Thread travailleur avec Qt en utilisant les signaux et les slots, un article de Christophe Dumez traduit par Thibaut Cuvelier 1
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 102
  2. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 53
  3. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 73
  4. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  5. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 11
Page suivante
  1. Linus Torvalds : le "C++ est un langage horrible", en justifiant le choix du C pour le système de gestion de version Git 100
  2. Comment prendre en compte l'utilisateur dans vos applications ? Pour un développeur, « 90 % des utilisateurs sont des idiots » 229
  3. Quel est LE livre que tout développeur doit lire absolument ? Celui qui vous a le plus marqué et inspiré 96
  4. Apple cède et s'engage à payer des droits à Nokia, le conflit des brevets entre les deux firmes s'achève 158
  5. Nokia porte à nouveau plainte contre Apple pour violation de sept nouveaux brevets 158
  6. Quel est le code dont vous êtes le plus fier ? Pourquoi l'avez-vous écrit ? Et pourquoi vous a-t-il donné autant de satisfaction ? 83
  7. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 101
Page suivante

Le Qt Quarterly au hasard

Logo

Algorithmes génériques

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 3.3
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