Managing key events

advertisements

Currently I want to handle basic key handling; e.g. if key is pressed, do this. However, should this have its own class or be done within a single function? Qt has a means of recording key events, but I know not how to proceed. I could have:

void keyPrHandle(QKeyEvent *Ev)
{
   if (Ev->key() == Qt::Key_G)
       ui->label->setText(Ev->text());
}

Else I would have to build a class that handles key events. I don't know how Qt handles key events, nor how I should implement it.


You can do this in derived class. Suppose you have QBase and QDerive classes. Then you can reimplenent event handlers:

void QDerived::keyPressEvent(QKeyEvent *Ev)
{
   if (Ev->key() == Qt::Key_G)
       //do something
   QBase::keyPressEvent(Ev);
}

And also in QDerive class:

protected:
   void keyPressEvent(QKeyEvent *Ev);

You can also handle events without subclassing with event filter:

http://qt-project.org/doc/qt-4.8/eventsandfilters.html#event-filters