Keyboard focus in graphics scene

The scene implements the concept of focus that works similar to keyboard focus in widgets. Only one item can have focus at a time. When the scene receives a keyboard event, it is dispatched to the focus item.

To be focusable, an item must have the QGraphicsItem::ItemIsFocusable flag enabled:

item1->setFlag(QGraphicsItem::ItemIsFocusable, true);
item2->setFlag(QGraphicsItem::ItemIsFocusable, true);

Then, an item can be focused by a mouse click. You can also change the focused item from the code:

item1->setFocus();

Another way to set the focus is to use the scene's QGraphicsScene::setFocusItem() function, which expects a pointer to the item you like to focus as a parameter. Every time an item gains focus, the previously focused item (if any) will automatically lose focus.

To determine whether an item has focus, you again have two possibilities. One is that you can call QGraphicsItem::hasFocus() on an item, which returns true if the item has focus or false otherwise. Alternatively, you can get the actual focused item by calling the scene's QGraphicsScene::focusItem() method. On the other hand, if you call the item's QGraphicsItem::focusItem() function, the focused item is returned if the item itself or any descendant item has focus; otherwise, nullptr is returned. To remove focus, call clearFocus() on the focused item or click somewhere in the scene's background or on an item that cannot get focus.

If you want a click on the scene's background not to cause the focused item to lose its focus, set the scene's stickyFocus property to true.