O'Reilly logo

Programming with Qt, 2nd Edition by Matthias Kalle Dalheimer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

NoFocus

The widget does not accept the keyboard focus at all.

ClickFocus

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

TabFocus

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

StrongFocus

A combination of ClickFocus and TabFocus.

WheelFocus

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required