Search code examples
qtqgraphicsviewqgraphicssceneqgraphicsitem

QAction as keyboard shortcut on QGraphicsItem


I would like to implement keyboard shortcuts for my QGraphicsScene. My graphical objects are derived from QGraphicItem and QObject, so I can use signal/slot connections.

I'm already using QActions for context menus and now I would like to use some of QActions also as actions for keyboard shortcuts on the selected item.

My QGraphicsItems have enabled ItemIsFocusable and ItemIsSelectable via setFlag();

I can receive keyPressEvent(QKeyEvent* event) but in such case I would have to manually test event->key() == Qt::Key_xxx

Is there any way how to do this automatically?

  • I tried to compare QKeyEvent with QKeySequence, but this doesn't work (because sequence can contain multiple keys).

Thanks for any help


Solution

  • I'm not entirely sure what you mean by automatically. I'm assuming you're just trying to avoid having to manually check the key, which unfortunately I'm not sure of any simpler method.

    Catching the QKeyEvent* event like you're doing is generally the way to go, and yes unfortunately once you have the event you'll need to make sure it's expected. You may be able to make the code less ugly by using a bitmask or similar logic operations, but in general I've used a switch on event->key() and that tends to keep things readable.