QEvent
has a type()
member function which returns the event type as enum value. Should I check dynamic_cast
result for QEvent*
if I already checked event->type()
. E.g.
bool ClassName::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::KeyPress)
{
auto ke = dynamic_cast<QKeyEvent*>(event);
if (ke) // <----------- needed?
{
// ...
}
}
// ...
}
Is if (ke)
condition needed here?
As a commenter suggested, checking out the Qt docs regarding this has the following example:
bool FilterObject::eventFilter(QObject *object, QEvent *event)
{
if (object == target && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Tab) {
// Special tab handling
return true;
} else
return false;
}
return false;
}
Because specific events will always be guaranteed to return the same type, checking against QEvent::type()
is sufficient to allow for a safe static_cast
to the target type. This will avoids the RTTI cost that a dynamic_cast
would entail.