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. « 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 8
Page suivante

Le Qt Labs au hasard

Logo

Utiliser OpenCL avec Qt

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. 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.2
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