Home · Overviews · Examples 

QWidget Class Reference
[com.trolltech.qt.gui module]

The QWidget class is the base class of all user interface objects. More...

Inherits QObject and QObject.

Inherited by QAbstractButton, QAbstractSlider, QAbstractSpinBox, QCalendarWidget, QComboBox, QDesignerResourceBrowserInterface, QDesktopWidget, QDialog, QDialogButtonBox, QDockWidget, QFocusFrame, QFrame, QGLWidget, QGroupBox, QLineEdit, QMainWindow, QMdiSubWindow, QMenu, QMenuBar, QProgressBar, QRubberBand, QSizeGrip, QSplashScreen, QSplitterHandle, QStatusBar, QSvgWidget, QTabBar, QTabWidget, QToolBar, QWizardPage, and QWorkspace.


Detailed Description

The QWidget class is the base class of all user interface objects.

The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it.

A widget that isn't embedded in a parent widget is called a window. Usually, windows have a frame and a title bar, although it is also possible to create windows without such decoration using suitable window flags). In Qt, QMainWindow and the various subclasses of QDialog are the most common window types.

Every widget's constructor accepts one or two standard arguments:

  1. QWidget *parent = 0 is the parent of the new widget. If it is 0 (the default), the new widget will be a window. If not, it will be a child of parent, and be constrained by parent's geometry (unless you specify Qt::Window as window flag).
  2. Qt::WindowFlags f = 0 (where available) sets the window flags; the default is suitable for almost all widgets, but to get, for example, a window without a window system frame, you must use special flags.

QWidget has many member functions, but some of them have little direct functionality; for example, QWidget has a font property, but never uses this itself. There are many subclasses which provide real functionality, such as QLabel, QPushButton, QListWidget, and QTabWidget.

Top-Level and Child Widgets

A widget without a parent widget is always an independent window (top-level widget). For these widgets, setWindowTitle and setWindowIcon set the title bar and icon respectively.

Non-window widgets are child widgets, and are displayed within their parent widgets. Most widgets in Qt are mainly useful as child widgets. For example, it is possible to display a button as a top-level window, but most people prefer to put their buttons inside other widgets, such as QDialog.

A parent widget containing various child widgets.

The above diagram shows a QGroupBox widget being used to hold various child widgets in a layout provided by QGridLayout. The QLabel child widgets have been outlined to indicate their full sizes.

If you want to use a QWidget to hold child widgets you will usually want to add a layout to the parent QWidget. See Layout Classes for more information about these.

Composite Widgets

When a widgets is used as a container to group a number of child widgets, it is known as a composite widget. These can be created by constructing a widget with the required visual properties - a QFrame, for example - and adding child widgets to it, usually managed by a layout. The above diagram shows such a composite widget that was created using Qt Designer.

Composite widgets can also be created by subclassing a standard widget, such as QWidget or QFrame, and adding the necessary layout and child widgets in the constructor of the subclass. Many of the examples provided with Qt use this approach, and it is also covered in the Qt Tutorial.

Custom Widgets and Painting

Since QWidget is a subclass of QPaintDevice, subclasses can be used to display custom content that is composed using a series of painting operations with an instance of the QPainter class. This approach contrasts with the canvas-style approach used by the Graphics View Framework where items are added to a scene by the application and are rendered by the framework itself.

Each widget performs all painting operations from within its paintEvent function. This is called whenever the widget needs to be redrawn, either as a result of some external change or when requested by the application.

The Analog Clock example shows how a simple widget can handle paint events.

Size Hints and Size Policies

When implementing a new widget, it is almost always useful to reimplement sizeHint to provide a reasonable default size for the widget and to set the correct size policy with setSizePolicy.

By default, composite widgets which do not provide a size hint will be sized according to the space requirements of their child widgets.

The size policy lets you supply good default behavior for the layout management system, so that other widgets can contain and manage yours easily. The default size policy indicates that the size hint represents the preferred size of the widget, and this is often good enough for many widgets.

Events

Widgets respond to events that are typically caused by user actions. Qt delivers events to widgets by calling specific event handler functions with instances of QEvent subclasses containing information about each event.

If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child's underMouse function inside the widget's mousePressEvent.

The Scribble example implements a wider set of events to handle mouse movement, button presses, and window resizing.

You will need to supply the behavior and content for your own widgets, but here is a brief overview of the events that are relevant to QWidget, starting with the most common ones:

Widgets that accept keyboard input need to reimplement a few more event handlers:

Some widgets will also need to reimplement some of the less common event handlers:

There are also some rather obscure events described in the QEvent::Type documentation. You need to reimplement event directly to handle these. The default implementation of event handles Tab and Shift+Tab (to move the keyboard focus), and passes on most other events to one of the more specialized handlers above.

Events and the mechanism used to deliver them are covered in the Events and Event Filters document.

Groups of Functions and Properties

ContextFunctions and Properties
Window functionsshow, hide, raise, lower, close.
Top-level windowswindowModified, windowTitle, windowIcon, windowIconText, isActiveWindow, activateWindow, minimized, showMinimized, maximized, showMaximized, fullScreen, showFullScreen, showNormal.
Window contentsupdate, repaint, scroll.
Geometrypos, x, y, rect, size, width, height, move, resize, sizePolicy, sizeHint, minimumSizeHint, updateGeometry, layout, frameGeometry, geometry, childrenRect, childrenRegion, adjustSize, mapFromGlobal, mapToGlobal, mapFromParent, mapToParent, maximumSize, minimumSize, sizeIncrement, baseSize, setFixedSize
Modevisible, isVisibleTo, enabled, isEnabledTo, modal, isWindow, mouseTracking, updatesEnabled, visibleRegion.
Look and feelstyle, setStyle, styleSheet, cursor, font, palette, backgroundRole, setBackgroundRole, fontInfo, fontMetrics.
Keyboard focus functionsfocus, focusPolicy, setFocus, clearFocus, setTabOrder, setFocusProxy, focusNextChild, focusPreviousChild.
Mouse and keyboard grabbinggrabMouse, releaseMouse, grabKeyboard, releaseKeyboard, mouseGrabber, keyboardGrabber.
Event handlersevent, mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, mouseMoveEvent, keyPressEvent, keyReleaseEvent, focusInEvent, focusOutEvent, wheelEvent, enterEvent, leaveEvent, paintEvent, moveEvent, resizeEvent, closeEvent, dragEnterEvent, dragMoveEvent, dragLeaveEvent, dropEvent, childEvent, showEvent, hideEvent, customEvent. changeEvent,
System functionsparentWidget, window, setParent, winId, find(), metric.
Interactive helpsetToolTip, setWhatsThis

Widget Style Sheets

In addition to the standard widget styles for each platform, widgets can also be styled according to rules specified in a style sheet. This feature enables you to customize the appearance of specific widgets to provide visual cues to users about their purpose; for example, a button could be styled in a particular way to indicate that it performs a destructive action.

The use of widgets style sheets is described in more detail in Qt Style Sheets.

Transparency and Double Buffering

From Qt 4.0, QWidget automatically double-buffers its painting, so there's no need to write double-buffering code in paintEvent to avoid flicker. Additionally, it became possible for widgets to propagate their contents to children, in order to enable transparency effects, by setting the Qt::WA_ContentsPropagated widget attribute - this is now deprecated in Qt 4.1.

In Qt 4.1, the contents of parent widgets are propagated by default to each of their children. Custom widgets can be written to take advantage of this feature by only updating irregular regions (to create non-rectangular child widgets), or by using painting with colors that have less than the full alpha component. The following diagram shows how attributes and properties of a custom widget can be fine-tuned to achieve different effects.

In the above diagram, a semi-transparent rectangular child widget with an area removed is constructed and added to a parent widget (a QLabel showing a pixmap) then different properties and widget attributes are set to achieve different effects:

For rapidly updating custom widgets with simple background colors, such as real-time plotting or graphing widgets, it is better to define a suitable background color (using setBackgroundRole with the QPalette::Window role), set the autoFillBackground property, and only implement the necessary drawing functionality in the widget's paintEvent.

For rapidly updating custom widgets that constantly paint over their entire areas with opaque content, such as video streaming widgets, it is better to set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead associated with repainting the widget's background.

If a widget has both the Qt::WA_OpaquePaintEvent widget attribute and the autoFillBackground property set, the Qt::WA_OpaquePaintEvent attribute takes precedence. You should choose just one of these depending on your requirements.

In Qt 4.1, the contents of parent widgets are also propagated to standard Qt widgets. This can lead to some unexpected results if the parent widget is decorated in a non-standard way, as shown in the diagram below.

The scope for customizing the painting behavior of standard Qt widgets, without resorting to subclassing, is slightly less than that possible for custom widgets. Usually, the desired appearance of a standard widget can be achieved by setting its autoFillBackground property.

See also QEvent, QPainter, QGridLayout, and QBoxLayout.


Copyright © 2008 Trolltech Trademarks
Qt Jambi 4.3.4_01