Can't set keyboard focus

As mentioned above, you can only grab focus if your component is showing on the screen. This means that not only this component needs to be visible, but also all ancestors (parent, parent of a parent etc) up to the top level have to be visible. Then, the top level component’s peer has to be “not minimised”, i.e. your window must be not minimised.

More robust solution is to use ComponentMovementWatcher which will call for you componentVisibilityChanged when isShowing() state may have potentially changed. Simply override its callback as follows:

void componentVisibilityChanged() override
{
    if (isShowing())
        grabKeyboardFocus();
}

Grabbing focus in paint() call is usually not ideal, because:

  • grabbing focus often means redrawing element losing/taking focus (thus another repaint)
  • paint() should paint, and not do any logic like grabbing focus :slight_smile: