[Qt-interest] Event Propagation Architecture of Graphics View Framework

Andre Somers andre at familiesomers.nl
Mon Aug 17 14:23:06 CEST 2009


varun singh wrote:
> hi,
>  So, I'm making this Tank's game using The Graphics View Framework.
> I've three classes of Tank(QGraphicsItem), Scene(QGraphicScene) and View(QGraphicsView).
> View contains a variable of Scene and Scene contains a variable of Tank.
>
> Now, I want the Tank to move using Keys (Up, Down etc.).
>
> So, I've programmed the Tank::keyPressEvent accordingly. The problem is that, I can't figure out how KeyEvents get propagated in the Framework.
>
> According to the documentation, QGraphicsView receives keyboard event n forwards it to QGraphicsScene which in turn forwards it to QGraphicsItem.
> But they, haven't specified it through an example (which is where I'm stuck). I can't simply call the keyPressEvent of one class from the other (they are protected). And moreover, like QEvent::QGraphicsSceneMousePressEvent, there is no such keyEvent specialized for it.
>
> Any help here would be like an oxygen mask to a drowning diver, or a parachute to a skydiver...
>   
I got bitten by this one too, if I understand your question correctly.

You have to understand that the event propagation is implemented in the 
default implementations of the event functions in the graphics view 
classes. That means that if you reimplement those classes, you will 
block this mechanism if you are not careful! Depending on what you want 
to achieve, you can avoid this issue by calling the baseclass 
implementaion of the event function in your reimplementation. For 
example (pseudo code; assuming Tank is a QGraphicsItem subclass):

void Tank::keyPressEvent(QKeyEvent* e) {
  QGraphicsItem::keyPressEvent(e);
  if (!e->isAccepted())  { // check if the event is handled by a child item
    // do our own handling, call e->accept() if we handle it or 
e->ignore() if we don't
  }
}

You can do this at any level (QGraphicsView, QGraphicsScene, 
QGraphicsItem). Note that sometimes you may want to catch the event 
before you give children the opportunity to handle the event, and 
sometimes you would allow children to try to handle it first. That 
depends on what you want to achieve.

If you let the base implementation handle the event propagation for you, 
you do not need access to the protected functions. Just let Qt handle 
that issue for you :-)

I hope this provides some oxygen for you?

André





More information about the Qt-interest-old mailing list