Chapter 15. Focus Handling

Focus handling is one of the most difficult topics in GUI programming, and few programs get it completely right. Focus handling has the keyboard focus where the user expects it to be and allows the user to navigate through the GUI elements that can accept keyboard focus without using the mouse (and thus having to take the hands away from the keyboard). Normally, the Tab key invokes this operation of moving the keyboard focus.

The main concept to understand about focus handling in Qt is the focus policy. This attribute is set separately for each widget. It controls whether the widget can receive keyboard focus and how it can happen. A QWidget disables focus by default, but all widgets that want to get keyboard focus enable it in their constructors. Thus, the constructor of your widget is the correct place to set the focus policy. You rarely need to override the focus policy that built-in widgets in Qt have set for themselves.

The following focus policies are available:


The widget does not accept the keyboard focus at all.


The widget accepts the focus when the user explicitly clicks into the widget with the mouse.


The widget accepts the focus when the user moves the focus to it by means of the Tab key.


A combination of ClickFocus and TabFocus.


Like StrongFocus, but accepts focus by moving the wheel of a wheel mouse.

You can ask a widget whether it accepts focus by calling isFocusEnabled(). This ...

Get Programming with Qt, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.