Question

http://qt-project.org/doc/qt-5/qwidget.html#keyPressEvent

Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent::accept() - just do not call the base class implementation if you act upon the key.

http://qt-project.org/doc/qt-5/qkeyevent.html#details

A key event contains a special accept flag that indicates whether the receiver will handle the key event. You should call ignore() if the key press or release event is not handled by your widget. A key event is propagated up the parent widget chain until a widget accepts it with accept() or an event filter consumes it. Key events for multimedia keys are ignored by default. You should call accept() if your widget handles those events.

That's a bit confusing. Should I call accept or not? Should I call the base implementation or call ignore if I don't handle it?

The first page reads I don't need to call accept(), the second reads "is propagated up the parent widget chain until a widget accepts it with accept()"

If I call the base version it'll basically call ignore() if it's QWidget. Wouldn't that mean it would return to my keyPressedEvent, return with ignored state, then QWidget's version is called again cause "key event is propagated up to the parent widget"?

Was it helpful?

Solution

Like it says, it is accepted automatically. So if you're handling it, you don't have to do anything. Only if you're not handling the key event you should call ignore().

If your class is a subclass of QWidget, and if you are handling the key event, then do not call the base implementation. If you don't handle it, you can just call the base implementation as it will call ignore().

You can read this, if you want to know more about accepting and ignoring events.

  • The first page reads I don't need to call accept(), the second reads "is propagated up the parent widget chain until a widget accepts it with accept()"

This means if you choose to ignore it, it will be propagated to the parent widget. If you choose to accept it, it will not be propagated to the parent widget.

  • If I call the base version it'll basically call ignore() if it's QWidget. Wouldn't that mean it would return to my keyPressedEvent, return with ignored state, then QWidget's version is called again cause "key event is propagated up to the parent widget"?

The base class is not the same as the parent widget. Base class is the class your class is derived from. A parent widget is an object that contains this object as its child widget. This is usually the widget that is passed to your constructor as an argument. But if the parent widget is a QWidget type, then yes, that would be the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top