Chapter 9. Widgets and Designer

Table of Contents

9.1. Widget Categories
9.2. Designer Introduction
9.3. Dialogs
9.4. Form Layout
9.5. Icons, Images and Resources
9.6. Layout of Widgets
9.6.1. Spacing, Stretching, and Struts
9.6.2. Size Policy and Size Hint
9.6.3. Exercises: Layout of Widgets
9.7. Designer Integration with Code
9.7.1. QtCreator Integration with Designer
9.8. Exercise: Input Forms
9.9. The Event Loop: Revisited
9.9.1. QTimer
9.9.1.1. Exercises: QTimer
9.10. Paint Events, Drawing Images
9.11. Review Questions

[ fromfile: widgets.xml id: widgets ]

Abstract

This chapter provides an overview of the GUI building blocks in the Qt library, called widgets, and includes some simple examples of how to use them. QtCreator and Designer are used to explore the widgets and their features, and to integrate forms with user code.

A widget is an object of a class derived from QWidget that has a visual representation on the screen. The structural origins of QWidget are shown in Figure 9.1.

Figure 9.1.  QWidget's Heritage

QWidget's Heritage

QWidget is a class that uses multiple inheritance (Section 22.3). A QWidget is a QObject, and thus can have a parent, signals, slots, and managed children. A QWidget is a QPaintDevice, the base class of all objects that can be "painted" on the screen.

QWidgets interact with their children in interesting ways. A widget that has no parent is called a window. If one widget is a parent of another widget, the boundaries of the child widget lie completely within the boundaries of the parent.[73] The contained child widget is displayed according to layout rules (Section 9.6 later in this chapter).

A QWidget can handle events by responding to messages from various entities in the window system (e.g., mouse, keyboard, timers, other processes, etc.). It can paint its own rectangular image on the screen. It can remove itself from the screen in a way that respects whatever else is on the screen at the moment.

A typical desktop GUI application can contain many (hundreds is not unusual) different QWidget-derived objects, deployed according to parent-child relationships and arranged according to the specifications of the applicable layouts.

QWidget is considered to be the simplest of all GUI classes because it is rendered as an empty box. The class itself, however, is quite complex, containing hundreds of functions. When you reuse QWidget and its subclasses you stand on the shoulders of giants because every QWidget is built on top of layers of Qt code, which in turn are built on top of different layers of native widget libraries, depending on your platform (X11 in Linux, Cocoa on MacOS, and Win32 in Windows).



[73] There are some exceptions to this rule. For example, a floating QDockWidget or QDialog can lie outside the boundaries of the parent widget, but is still "in front" of it. Section 10.2 discusses QDocWidgets.