Home · All Classes · Modules

QWidget Class Reference
[QtGui module]

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

Inherits QObject and QPaintDevice.

Inherited by EffectWidget, SeekSlider, VideoPlayer, VideoWidget, VolumeSlider, QAbstractButton, QAbstractSlider, QAbstractSpinBox, QCalendarWidget, QComboBox, QDesignerActionEditorInterface, QDesignerFormWindowInterface, QDesignerObjectInspectorInterface, QDesignerPropertyEditorInterface, QDesignerWidgetBoxInterface, QDesktopWidget, QDialog, QDialogButtonBox, QDockWidget, QFocusFrame, QFrame, QGLWidget, QGroupBox, QHelpSearchQueryWidget, QHelpSearchResultWidget, QLineEdit, QMainWindow, QMdiSubWindow, QMenu, QMenuBar, QPrintPreviewWidget, QProgressBar, QRubberBand, QSizeGrip, QSplashScreen, QSplitterHandle, QStatusBar, QSvgWidget, QTabBar, QTabWidget, QToolBar, QWebView, QWizardPage, QWorkspace, QX11EmbedContainer and QX11EmbedWidget.

Types

Methods

Static Methods

Qt Signals


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.


Type Documentation

QWidget.RenderFlag

This enum describes how to render the widget when calling QWidget.render().

ConstantValueDescription
QWidget.DrawWindowBackground0x1If you enable this option, the widget's background is rendered into the target even if autoFillBackground is not set. By default, this option is enabled.
QWidget.DrawChildren0x2If you enable this option, the widget's children are rendered recursively into the target. By default, this option is enabled.
QWidget.IgnoreMask0x4If you enable this option, the widget's QWidget.mask() is ignored when rendering into the target. By default, this option is disabled.

This enum was introduced in Qt 4.3.

The RenderFlags type is a typedef for QFlags<RenderFlag>. It stores an OR combination of RenderFlag values.


Method Documentation

QWidget.__init__ (self, QWidget parent = None, Qt.WindowFlags f = 0)

The parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs a widget which is a child of parent, with widget flags set to f.

If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted.

The widget flags argument, f, is normally 0, but it can be set to customize the frame of a window (i.e. parent must be 0). To customize the frame, use a value composed from the bitwise OR of any of the window flags.

If you add a child widget to an already visible widget you must explicitly show the child to make it visible.

Note that the X11 version of Qt may not be able to deliver all combinations of style flags on all systems. This is because on X11, Qt can only ask the window manager, and the window manager can override the application's settings. On Windows, Qt can set whatever flags you want.

See also windowFlags.

bool QWidget.acceptDrops (self)

QString QWidget.accessibleDescription (self)

QString QWidget.accessibleName (self)

QWidget.actionEvent (self, QActionEvent)

This event handler is called with the given event whenever the widget's actions are changed.

See also addAction(), insertAction(), removeAction(), actions(), and QActionEvent.

QAction-list QWidget.actions (self)

Returns the (possibly empty) list of this widget's actions.

See also contextMenuPolicy, insertAction(), and removeAction().

QWidget.activateWindow (self)

Sets the top-level widget containing this widget to be the active window.

An active window is a visible top-level window that has the keyboard input focus.

This function performs the same operation as clicking the mouse on the title bar of a top-level window. On X11, the result depends on the Window Manager. If you want to ensure that the window is stacked on top as well you should also call raise_(). Note that the window must be visible, otherwise activateWindow() has no effect.

On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will change the color of the taskbar entry to indicate that the window has changed in some way. This is because Microsoft do not allow an application to interrupt what the user is currently doing in another application.

See also isActiveWindow(), window(), and show().

QWidget.addAction (self, QAction action)

Appends the action action to this widget's list of actions.

All QWidgets have a list of QActions, however they can be represented graphically in many different ways. The default use of the QAction list (as returned by actions()) is to create a context QMenu.

A QWidget should only have one of each action and adding an action it already has will not cause the same action to be in the widget twice.

See also removeAction(), insertAction(), actions(), and QMenu.

QWidget.addActions (self, QAction-list actions)

Appends the actions actions to this widget's list of actions.

See also removeAction(), QMenu, and addAction().

QWidget.adjustSize (self)

Adjusts the size of the widget to fit the contents.

Uses sizeHint() if valid (i.e if the size hint's width and height are >= 0); otherwise sets the size to the children rectangle that covers all child widgets (the union of all child widget rectangles).

For windows, the screen size is also taken into account, and if the sizeHint() is less than (200, 100) and the size policy is expanding, the window is made to be at least (200, 100).

See also sizeHint() and childrenRect().

bool QWidget.autoFillBackground (self)

QPalette.ColorRole QWidget.backgroundRole (self)

Returns the background role of the widget.

The background role defines the brush from the widget's palette that is used to render the background.

If no explicit background role is set, the widget inherts its parent widget's background role.

See also setBackgroundRole() and foregroundRole().

QSize QWidget.baseSize (self)

QWidget.changeEvent (self, QEvent)

This event handler can be reimplemented to handle state changes.

The state being changed in this event can be retrieved through event event.

Change events include: QEvent.ToolBarChange, QEvent.ActivationChange, QEvent.EnabledChange, QEvent.FontChange, QEvent.StyleChange, QEvent.PaletteChange, QEvent.WindowTitleChange, QEvent.IconTextChange, QEvent.ModifiedChange, QEvent.MouseTrackingChange, QEvent.ParentChange, QEvent.WindowStateChange, QEvent.LanguageChange, QEvent.LocaleChange, QEvent.LayoutDirectionChange.

QWidget QWidget.childAt (self, QPoint p)

Returns the visible child widget at the position (x, y) in the widget's coordinate system. If there is no visible child widget at the specified position, the function returns 0.

QWidget QWidget.childAt (self, int ax, int ay)

QRect QWidget.childrenRect (self)

QRegion QWidget.childrenRegion (self)

QWidget.clearFocus (self)

Takes keyboard input focus from the widget.

If the widget has active focus, a focus out event is sent to this widget to tell it that it is about to lose the focus.

This widget must enable focus setting in order to get the keyboard input focus, i.e. it must call setFocusPolicy().

See also hasFocus(), setFocus(), focusInEvent(), focusOutEvent(), setFocusPolicy(), and QApplication.focusWidget().

QWidget.clearMask (self)

Removes any mask set by setMask().

See also setMask().

bool QWidget.close (self)

This method is also a Qt slot with the C++ signature bool close().

Closes this widget. Returns true if the widget was closed; otherwise returns false.

First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget.closeEvent() accepts the close event.

If the widget has the Qt.WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not.

The QApplication.lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt.WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.

QWidget.closeEvent (self, QCloseEvent)

This event handler is called with the given event when Qt receives a window close request for a top-level widget from the window system.

By default, the event is accepted and the widget is closed. You can reimplement this function to change the way the widget responds to window close requests. For example, you can prevent the window from closing by calling ignore() on all events.

Main window applications typically use reimplementations of this function to check whether the user's work has been saved and ask for permission before closing. For example, the Application Example uses a helper function to determine whether or not to close the window:

 void MainWindow.closeEvent(QCloseEvent *event)
 {
     if (maybeSave()) {
         writeSettings();
         event->accept();
     } else {
         event->ignore();
     }
 }

See also event(), hide(), close(), QCloseEvent, and Application Example.

QRect QWidget.contentsRect (self)

Returns the area inside the widget's margins.

See also setContentsMargins() and getContentsMargins().

QWidget.contextMenuEvent (self, QContextMenuEvent)

This event handler, for event event, can be reimplemented in a subclass to receive widget context menu events.

The handler is called when the widget's contextMenuPolicy is Qt.DefaultContextMenu.

The default implementation ignores the context event. See the QContextMenuEvent documentation for more details.

See also event(), QContextMenuEvent, and customContextMenuRequested().

Qt.ContextMenuPolicy QWidget.contextMenuPolicy (self)

QWidget.create (self, unsigned long = 0, bool initializeWindow = True, bool destroyOldWindow = True)

Creates a new widget window if window is 0, otherwise sets the widget's window to window.

Initializes the window (sets the geometry etc.) if initializeWindow is true. If initializeWindow is false, no initialization is performed. This parameter only makes sense if window is a valid window.

Destroys the old window if destroyOldWindow is true. If destroyOldWindow is false, you are responsible for destroying the window yourself (using platform native code).

The QWidget constructor calls create(0,true,true) to create a window for this widget.

QCursor QWidget.cursor (self)

QWidget.destroy (self, bool destroyWindow = True, bool destroySubWindows = True)

Frees up window system resources. Destroys the widget window if destroyWindow is true.

destroy() calls itself recursively for all the child widgets, passing destroySubWindows for the destroyWindow parameter. To have more control over destruction of subwidgets, destroy subwidgets selectively first.

This function is usually called from the QWidget destructor.

int QWidget.devType (self)

QWidget.dragEnterEvent (self, QDragEnterEvent)

This event handler is called when a drag is in progress and the mouse enters this widget. The event is passed in the event parameter.

If the event is ignored, the widget won't receive any drag move events.

See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

See also QDrag and QDragEnterEvent.

QWidget.dragLeaveEvent (self, QDragLeaveEvent)

This event handler is called when a drag is in progress and the mouse leaves this widget. The event is passed in the event parameter.

See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

See also QDrag and QDragLeaveEvent.

QWidget.dragMoveEvent (self, QDragMoveEvent)

This event handler is called if a drag is in progress, and when any of the following conditions occur: the cursor enters this widget, the cursor moves within this widget, or a modifier key is pressed on the keyboard while this widget has the focus. The event is passed in the event parameter.

See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

See also QDrag and QDragMoveEvent.

QWidget.dropEvent (self, QDropEvent)

This event handler is called when the drag is dropped on this widget. The event is passed in the event parameter.

See the Drag-and-drop documentation for an overview of how to provide drag-and-drop in your application.

See also QDrag and QDropEvent.

unsigned long QWidget.effectiveWinId (self)

Returns the effective window system identifier of the widget, i.e. the native parent's window system identifier.

Note: We recommend that you do not store this value as it is likely to change during run-time.

This function was introduced in Qt 4.4.

See also nativeParentWidget().

QWidget.enabledChange (self, bool)

QWidget.ensurePolished (self)

Ensures that the widget has been polished by QStyle (i.e., has a proper font and palette).

QWidget calls this function after it has been fully constructed but before it is shown the very first time. You can call this function if you want to ensure that the widget is polished before doing an operation, e.g., the correct font size might be needed in the widget's sizeHint() reimplementation. Note that this function is called from the default implementation of sizeHint().

Polishing is useful for final initialization that must happen after all constructors (from base classes as well as from subclasses) have been called.

If you need to change some settings when a widget is polished, reimplement event() and handle the QEvent.Polish event type.

Note: The function is declared const so that it can be called from other const functions (e.g., sizeHint()).

See also event().

QWidget.enterEvent (self, QEvent)

This event handler can be reimplemented in a subclass to receive widget enter events which are passed in the event parameter.

An event is sent to the widget when the mouse cursor enters the widget.

See also leaveEvent(), mouseMoveEvent(), and event().

bool QWidget.event (self, QEvent)

This is the main event handler; it handles event event. You can reimplement this function in a subclass, but we recommend using one of the specialized event handlers instead.

Key press and release events are treated differently from other events. event() checks for Tab and Shift+Tab and tries to move the focus appropriately. If there is no widget to move the focus to (or the key press is not Tab or Shift+Tab), event() calls keyPressEvent().

Mouse and tablet event handling is also slightly special: only when the widget is enabled, event() will call the specialized handlers such as mousePressEvent(); otherwise it will discard the event.

This function returns true if the event was recognized, otherwise it returns false. If the recognized event was accepted (see QEvent.accepted), any further processing such as event propagation to the parent widget stops.

Reimplemented from QObject.

See also closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(), keyPressEvent(), keyReleaseEvent(), leaveEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(), mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(), QObject.event(), and QObject.timerEvent().

QWidget QWidget.find (unsigned long)

Returns a pointer to the widget with window identifer/handle id.

The window identifier type depends on the underlying window system, see qwindowdefs.h for the actual definition. If there is no widget with this identifier, 0 is returned.

QWidget.focusInEvent (self, QFocusEvent)

This event handler can be reimplemented in a subclass to receive keyboard focus events (focus received) for the widget. The event is passed in the event parameter

A widget normally must setFocusPolicy() to something other than Qt.NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)

The default implementation updates the widget (except for windows that do not specify a focusPolicy()).

See also focusOutEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.

bool QWidget.focusNextChild (self)

Finds a new widget to give the keyboard focus to, as appropriate for Tab, and returns true if it can find a new widget, or false if it can't.

See also focusPreviousChild().

bool QWidget.focusNextPrevChild (self, bool next)

Finds a new widget to give the keyboard focus to, as appropriate for Tab and Shift+Tab, and returns true if it can find a new widget, or false if it can't.

If next is true, this function searches forward, if next is false, it searches backward.

Sometimes, you will want to reimplement this function. For example, a web browser might reimplement it to move its "current active link" forward or backward, and call focusNextPrevChild() only when it reaches the last or first link on the "page".

Child widgets call focusNextPrevChild() on their parent widgets, but only the window that contains the child widgets decides where to redirect focus. By reimplementing this function for an object, you thus gain control of focus traversal for all child widgets.

See also focusNextChild() and focusPreviousChild().

QWidget.focusOutEvent (self, QFocusEvent)

This event handler can be reimplemented in a subclass to receive keyboard focus events (focus lost) for the widget. The events is passed in the event parameter.

A widget normally must setFocusPolicy() to something other than Qt.NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.)

The default implementation updates the widget (except for windows that do not specify a focusPolicy()).

See also focusInEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), and QFocusEvent.

Qt.FocusPolicy QWidget.focusPolicy (self)

bool QWidget.focusPreviousChild (self)

Finds a new widget to give the keyboard focus to, as appropriate for Shift+Tab, and returns true if it can find a new widget, or false if it can't.

See also focusNextChild().

QWidget QWidget.focusProxy (self)

Returns the focus proxy, or 0 if there is no focus proxy.

See also setFocusProxy().

QWidget QWidget.focusWidget (self)

Returns the last child of this widget that setFocus had been called on. For top level widgets this is the widget that will get focus in case this window gets activated

This is not the same as QApplication.focusWidget(), which returns the focus widget in the currently active window.

QFont QWidget.font (self)

QWidget.fontChange (self, QFont)

QFontInfo QWidget.fontInfo (self)

Returns the font info for the widget's current font. Equivalent to QFontInto(widget->font()).

See also font(), fontMetrics(), and setFont().

QFontMetrics QWidget.fontMetrics (self)

Returns the font metrics for the widget's current font. Equivalent to QFontMetrics(widget->font()).

See also font(), fontInfo(), and setFont().

QPalette.ColorRole QWidget.foregroundRole (self)

Returns the foreground role.

The foreground role defines the color from the widget's palette that is used to draw the foreground.

If no explicit foreground role is set, the function returns a role that contrasts with the background role.

See also setForegroundRole() and backgroundRole().

QRect QWidget.frameGeometry (self)

QSize QWidget.frameSize (self)

QRect QWidget.geometry (self)

(int left, int top, int right, int bottom) QWidget.getContentsMargins (self)

Returns the widget's contents margins for left, top, right, and bottom.

See also setContentsMargins() and contentsRect().

QWidget.grabKeyboard (self)

Grabs the keyboard input.

This widget receives all keyboard events until releaseKeyboard() is called; other widgets get no keyboard events at all. Mouse events are not affected. Use grabMouse() if you want to grab that.

The focus widget is not affected, except that it doesn't receive any keyboard events. setFocus() moves the focus as usual, but the new focus widget receives keyboard events only after releaseKeyboard() is called.

If a different widget is currently grabbing keyboard input, that widget's grab is released first.

See also releaseKeyboard(), grabMouse(), releaseMouse(), and focusWidget().

QWidget.grabMouse (self)

Grabs the mouse input.

This widget receives all mouse events until releaseMouse() is called; other widgets get no mouse events at all. Keyboard events are not affected. Use grabKeyboard() if you want to grab that.

Warning: Bugs in mouse-grabbing applications very often lock the terminal. Use this function with extreme caution, and consider using the -nograb command line option while debugging.

It is almost never necessary to grab the mouse when using Qt, as Qt grabs and releases it sensibly. In particular, Qt grabs the mouse when a mouse button is pressed and keeps it until the last button is released.

Note that only visible widgets can grab mouse input. If isVisible() returns false for a widget, that widget cannot call grabMouse().

focusWidget()

See also releaseMouse(), grabKeyboard(), releaseKeyboard(), and grabKeyboard().

QWidget.grabMouse (self, QCursor)

This is an overloaded member function, provided for convenience.

Grabs the mouse input and changes the cursor shape.

The cursor will assume shape cursor (for as long as the mouse focus is grabbed) and this widget will be the only one to receive mouse events until releaseMouse() is called().

Warning: Grabbing the mouse might lock the terminal.

See also releaseMouse(), grabKeyboard(), releaseKeyboard(), and setCursor().

int QWidget.grabShortcut (self, QKeySequence key, Qt.ShortcutContext context = Qt.WindowShortcut)

Adds a shortcut to Qt's shortcut system that watches for the given key sequence in the given context. If the context is Qt.ApplicationShortcut, the shortcut applies to the application as a whole. Otherwise, it is either local to this widget, Qt.WidgetShortcut, or to the window itself, Qt.WindowShortcut.

If the same key sequence has been grabbed by several widgets, when the key sequence occurs a QEvent.Shortcut event is sent to all the widgets to which it applies in a non-deterministic order, but with the ``ambiguous'' flag set to true.

Warning: You should not normally need to use this function; instead create QActions with the shortcut key sequences you require (if you also want equivalent menu options and toolbar buttons), or create QShortcuts if you just need key sequences. Both QAction and QShortcut handle all the event filtering for you, and provide signals which are triggered when the user triggers the key sequence, so are much easier to use than this low-level function.

See also releaseShortcut() and setShortcutEnabled().

unsigned long QWidget.handle (self)

bool QWidget.hasFocus (self)

bool QWidget.hasMouseTracking (self)

int QWidget.height (self)

int QWidget.heightForWidth (self, int)

Returns the preferred height for this widget, given the width w.

If this widget has a layout, the default implementation returns the layout's preferred height. if there is no layout, the default implementation returns -1 indicating that the preferred height does not depend on the width.

QWidget.hide (self)

This method is also a Qt slot with the C++ signature void hide().

Hides the widget. This function is equivalent to setVisible(false).

Note: If you are working with QDialog or its subclasses and you invoke the show() function after this function, the dialog will be displayed in its original position.

See also hideEvent(), isHidden(), show(), setVisible(), isVisible(), and close().

QWidget.hideEvent (self, QHideEvent)

This event handler can be reimplemented in a subclass to receive widget hide events. The event is passed in the event parameter.

Hide events are sent to widgets immediately after they have been hidden.

Note: A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. After receiving a spontaneous hide event, a widget is still considered visible in the sense of isVisible().

See also visible, event(), and QHideEvent.

QInputContext QWidget.inputContext (self)

This function returns the QInputContext for this widget. By default the input context is inherited from the widgets parent. For toplevels it is inherited from QApplication.

You can override this and set a special input context for this widget by using the setInputContext() method.

See also setInputContext().

QWidget.inputMethodEvent (self, QInputMethodEvent)

This event handler, for event event, can be reimplemented in a subclass to receive Input Method composition events. This handler is called when the state of the input method changes.

Note that when creating custom text editing widgets, the Qt.WA_InputMethodEnabled window attribute must be set explicitly (using the setAttribute() function) in order to receive input method events.

The default implementation calls event->ignore(), which rejects the Input Method event. See the QInputMethodEvent documentation for more details.

See also event() and QInputMethodEvent.

QVariant QWidget.inputMethodQuery (self, Qt.InputMethodQuery)

This method is only relevant for input widgets. It is used by the input method to query a set of properties of the widget to be able to support complex input method operations as support for surrounding text and reconversions.

query specifies which property is queried.

See also inputMethodEvent(), QInputMethodEvent, and QInputContext.

QWidget.insertAction (self, QAction before, QAction action)

Inserts the action action to this widget's list of actions, before the action before. It appends the action if before is 0 or before is not a valid action for this widget.

A QWidget should only have one of each action.

See also removeAction(), addAction(), QMenu, contextMenuPolicy, and actions().

QWidget.insertActions (self, QAction before, QAction-list actions)

Inserts the actions actions to this widget's list of actions, before the action before. It appends the action if before is 0 or before is not a valid action for this widget.

A QWidget can have at most one of each action.

See also removeAction(), QMenu, insertAction(), and contextMenuPolicy.

bool QWidget.isActiveWindow (self)

bool QWidget.isAncestorOf (self, QWidget child)

Returns true if this widget is a parent, (or grandparent and so on to any level), of the given child, and both widgets are within the same window; otherwise returns false.

bool QWidget.isEnabled (self)

bool QWidget.isEnabledTo (self, QWidget)

Returns true if this widget would become enabled if ancestor is enabled; otherwise returns false.

This is the case if neither the widget itself nor every parent up to but excluding ancestor has been explicitly disabled.

isEnabledTo(0) is equivalent to isEnabled().

See also setEnabled() and enabled.

bool QWidget.isEnabledToTLW (self)

bool QWidget.isFullScreen (self)

bool QWidget.isHidden (self)

Returns true if the widget is hidden, otherwise returns false.

A hidden widget will only become visible when show() is called on it. It will not be automatically shown when the parent is shown.

To check visiblity, use !isVisible() instead (notice the exclamation mark).

isHidden() implies !isVisible(), but a widget can be not visible and not hidden at the same time. This is the case for widgets that are children of widgets that are not visible.

Widgets are hidden if they were created as independent windows or as children of visible widgets, or if hide() or setVisible(false) was called.

bool QWidget.isLeftToRight (self)

bool QWidget.isMaximized (self)

bool QWidget.isMinimized (self)

bool QWidget.isModal (self)

bool QWidget.isRightToLeft (self)

bool QWidget.isTopLevel (self)

bool QWidget.isVisible (self)

bool QWidget.isVisibleTo (self, QWidget)

Returns true if this widget would become visible if ancestor is shown; otherwise returns false.

The true case occurs if neither the widget itself nor any parent up to but excluding ancestor has been explicitly hidden.

This function will still return true if the widget is obscured by other windows on the screen, but could be physically visible if it or they were to be moved.

isVisibleTo(0) is identical to isVisible().

See also show(), hide(), and isVisible().

bool QWidget.isWindow (self)

Returns true if the widget is an independent window, otherwise returns false.

A window is a widget that isn't visually the child of any other widget and that usually has a frame and a window title.

A window can have a parent widget. It will then be grouped with its parent and deleted when the parent is deleted, minimized when the parent is minimized etc. If supported by the window manager, it will also have a common taskbar entry with its parent.

QDialog and QMainWindow widgets are by default windows, even if a parent widget is specified in the constructor. This behavior is specified by the Qt.Window flag.

See also window(), isModal(), and parentWidget().

bool QWidget.isWindowModified (self)

QWidget QWidget.keyboardGrabber ()

Returns the widget that is currently grabbing the keyboard input.

If no widget in this application is currently grabbing the keyboard, 0 is returned.

See also grabMouse() and mouseGrabber().

QWidget.keyPressEvent (self, QKeyEvent)

This event handler, for event event, can be reimplemented in a subclass to receive key press events for the widget.

A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event.

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.

The default implementation closes popup widgets if the user presses Esc. Otherwise the event is ignored, so that the widget's parent can interpret it.

Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent.accept() - just do not call the base class implementation if you act upon the key.

See also keyReleaseEvent(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), QKeyEvent, and Tetrix Example.

QWidget.keyReleaseEvent (self, QKeyEvent)

This event handler, for event event, can be reimplemented in a subclass to receive key release events for the widget.

A widget must accept focus initially and have focus in order to receive a key release event.

If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key.

The default implementation ignores the event, so that the widget's parent can interpret it.

Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent.accept() - just do not call the base class implementation if you act upon the key.

See also keyPressEvent(), QKeyEvent.ignore(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), and QKeyEvent.

QWidget.languageChange (self)

QLayout QWidget.layout (self)

Returns the layout manager that is installed on this widget, or 0 if no layout manager is installed.

The layout manager sets the geometry of the widget's children that have been added to the layout.

See also setLayout(), sizePolicy(), and Layout Classes.

Qt.LayoutDirection QWidget.layoutDirection (self)

QWidget.leaveEvent (self, QEvent)

This event handler can be reimplemented in a subclass to receive widget leave events which are passed in the event parameter.

A leave event is sent to the widget when the mouse cursor leaves the widget.

See also enterEvent(), mouseMoveEvent(), and event().

QLocale QWidget.locale (self)

QWidget.lower (self)

This method is also a Qt slot with the C++ signature void lower().

Lowers the widget to the bottom of the parent widget's stack.

After this call the widget will be visually behind (and therefore obscured by) any overlapping sibling widgets.

See also raise_() and stackUnder().

QPoint QWidget.mapFrom (self, QWidget, QPoint)

Translates the widget coordinate pos from the coordinate system of parent to this widget's coordinate system. The parent must not be 0 and must be a parent of the calling widget.

See also mapTo(), mapFromParent(), mapFromGlobal(), and underMouse().

QPoint QWidget.mapFromGlobal (self, QPoint)

Translates the global screen coordinate pos to widget coordinates.

See also mapToGlobal(), mapFrom(), and mapFromParent().

QPoint QWidget.mapFromParent (self, QPoint)

Translates the parent widget coordinate pos to widget coordinates.

Same as mapFromGlobal() if the widget has no parent.

See also mapToParent(), mapFrom(), mapFromGlobal(), and underMouse().

QPoint QWidget.mapTo (self, QWidget, QPoint)

Translates the widget coordinate pos to the coordinate system of parent. The parent must not be 0 and must be a parent of the calling widget.

See also mapFrom(), mapToParent(), mapToGlobal(), and underMouse().

QPoint QWidget.mapToGlobal (self, QPoint)

Translates the widget coordinate pos to global screen coordinates. For example, mapToGlobal(QPoint(0,0)) would give the global coordinates of the top-left pixel of the widget.

See also mapFromGlobal(), mapTo(), and mapToParent().

QPoint QWidget.mapToParent (self, QPoint)

Translates the widget coordinate pos to a coordinate in the parent widget.

Same as mapToGlobal() if the widget has no parent.

See also mapFromParent(), mapTo(), mapToGlobal(), and underMouse().

QRegion QWidget.mask (self)

Returns the mask currently set on a widget. If no mask is set the return value will be an empty region.

See also setMask(), clearMask(), QRegion.isEmpty(), and Shaped Clock Example.

int QWidget.maximumHeight (self)

QSize QWidget.maximumSize (self)

int QWidget.maximumWidth (self)

int QWidget.metric (self, QPaintDevice.PaintDeviceMetric)

Internal implementation of the virtual QPaintDevice.metric() function.

m is the metric to get.

Reimplemented from QPaintDevice.

int QWidget.minimumHeight (self)

QSize QWidget.minimumSize (self)

QSize QWidget.minimumSizeHint (self)

int QWidget.minimumWidth (self)

QWidget.mouseDoubleClickEvent (self, QMouseEvent)

This event handler, for event event, can be reimplemented in a subclass to receive mouse double click events for the widget.

The default implementation generates a normal mouse press event.

Note that the widgets gets a mousePressEvent() and a mouseReleaseEvent() before the mouseDoubleClickEvent().

See also mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(), event(), and QMouseEvent.

QWidget QWidget.mouseGrabber ()

Returns the widget that is currently grabbing the mouse input.

If no widget in this application is currently grabbing the mouse, 0 is returned.

See also grabMouse() and keyboardGrabber().

QWidget.mouseMoveEvent (self, QMouseEvent)

This event handler, for event event, can be reimplemented in a subclass to receive mouse move events for the widget.

If mouse tracking is switched off, mouse move events only occur if a mouse button is pressed while the mouse is being moved. If mouse tracking is switched on, mouse move events occur even if no mouse button is pressed.

QMouseEvent.pos() reports the position of the mouse cursor, relative to this widget. For press and release events, the position is usually the same as the position of the last mouse move event, but it might be different if the user's hand shakes. This is a feature of the underlying window system, not Qt.

See also setMouseTracking(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), event(), QMouseEvent, and Scribble Example.

QWidget.mousePressEvent (self, QMouseEvent)

This event handler, for event event, can be reimplemented in a subclass to receive mouse press events for the widget.

If you create new widgets in the mousePressEvent() the mouseReleaseEvent() may not end up where you expect, depending on the underlying window system (or X11 window manager), the widgets' location and maybe more.

The default implementation implements the closing of popup widgets when you click outside the window. For other widget types it does nothing.

See also mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, and Scribble Example.

QWidget.mouseReleaseEvent (self, QMouseEvent)

This event handler, for event event, can be reimplemented in a subclass to receive mouse release events for the widget.

See also mousePressEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, and Scribble Example.

QWidget.move (self, QPoint)

QWidget.move (self, int ax, int ay)

QWidget.moveEvent (self, QMoveEvent)

This event handler can be reimplemented in a subclass to receive widget move events which are passed in the event parameter. When the widget receives this event, it is already at the new position.

The old position is accessible through QMoveEvent.oldPos().

See also resizeEvent(), event(), move(), and QMoveEvent.

QWidget QWidget.nativeParentWidget (self)

Returns the native parent for this widget, i.e. the next ancestor widget that has a system identifier, or 0 if it does not have any native parent.

This function was introduced in Qt 4.4.

See also effectiveWinId().

QWidget QWidget.nextInFocusChain (self)

Returns the next widget in this widget's focus chain.

QRect QWidget.normalGeometry (self)

QWidget.overrideWindowFlags (self, Qt.WindowFlags type)

Sets the window flags for the widget to flags, without telling the window system.

Warning: Do not call this function unless you really know what you're doing.

See also setWindowFlags().

QWidget.overrideWindowState (self, Qt.WindowStates state)

QPaintEngine QWidget.paintEngine (self)

Returns the widget's paint engine.

Reimplemented from QPaintDevice.

QWidget.paintEvent (self, QPaintEvent)

This event handler can be reimplemented in a subclass to receive paint events which are passed in the event parameter.

A paint event is a request to repaint all or part of the widget. It can happen as a result of repaint() or update(), or because the widget was obscured and has now been uncovered, or for many other reasons.

Many widgets can simply repaint their entire surface when asked to, but some slow widgets need to optimize by painting only the requested region: QPaintEvent.region(). This speed optimization does not change the result, as painting is clipped to that region during event processing. QListView and QTableView do this, for example.

Qt also tries to speed up painting by merging multiple paint events into one. When update() is called several times or the window system sends several paint events, Qt merges these events into one event with a larger region (see QRegion.united()). repaint() does not permit this optimization, so we suggest using update() whenever possible.

When the paint event occurs, the update region has normally been erased, so that you're painting on the widget's background.

The background can be set using setBackgroundRole() and setPalette().

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.

Note: Under X11 it is possible to toggle the global double buffering by calling qt_x11_set_global_double_buffer(). Example usage:

 ...
 extern void qt_x11_set_global_double_buffer(bool);
 qt_x11_set_global_double_buffer(false);
 ...

Note: In general, one should refrain from calling update() or repaint() inside of paintEvent(). For example, calling update() or repaint() on children inside a paintEvent() results in undefined behavior; the child may or may not get a paint event.

See also event(), repaint(), update(), QPainter, QPixmap, QPaintEvent, and Analog Clock Example.

QPalette QWidget.palette (self)

QWidget.paletteChange (self, QPalette)

QWidget QWidget.parentWidget (self)

Returns the parent of this widget, or 0 if it does not have any parent widget.

QPoint QWidget.pos (self)

QWidget.raise_ (self)

This method is also a Qt slot with the C++ signature void raise().

Raises this widget to the top of the parent widget's stack.

After this call the widget will be visually in front of any overlapping sibling widgets.

Note: When using activateWindow(), you can call this function to ensure that the window is stacked on top.

See also lower() and stackUnder().

QRect QWidget.rect (self)

QWidget.releaseKeyboard (self)

Releases the keyboard grab.

See also grabKeyboard(), grabMouse(), and releaseMouse().

QWidget.releaseMouse (self)

Releases the mouse grab.

See also grabMouse(), grabKeyboard(), and releaseKeyboard().

QWidget.releaseShortcut (self, int id)

Removes the shortcut with the given id from Qt's shortcut system. The widget will no longer receive QEvent.Shortcut events for the shortcut's key sequence (unless it has other shortcuts with the same key sequence).

Warning: You should not normally need to use this function since Qt's shortcut system removes shortcuts automatically when their parent widget is destroyed. It is best to use QAction or QShortcut to handle shortcuts, since they are easier to use than this low-level function. Note also that this is an expensive operation.

See also grabShortcut() and setShortcutEnabled().

QWidget.removeAction (self, QAction action)

Removes the action action from this widget's list of actions.

See also insertAction(), actions(), and insertAction().

QWidget.render (self, QPaintDevice target, QPoint targetOffset = QPoint(), QRegion sourceRegion = QRegion(), RenderFlags renderFlags = QWidget.DrawWindowBackground | QWidget.DrawChildren)

Renders the sourceRegion of this widget into the target using renderFlags to determine how to render. Rendering starts at targetOffset in the target. For example:

 QPixmap pixmap(widget->size());
 widget->render(&pixmap);

If sourceRegion is a null region, this function will use QWidget.rect() as the region, i.e. the entire widget.

Note: Make sure to call QPainter.end() for the given target's active painter (if any) before rendering. For example:

 QPainter painter(this);
 ...
 painter.end();
 myWidget->render(this);

This function was introduced in Qt 4.3.

QWidget.render (self, QPainter painter, QPoint targetOffset = QPoint(), QRegion sourceRegion = QRegion(), RenderFlags renderFlags = QWidget.DrawWindowBackground | QWidget.DrawChildren)

This is an overloaded member function, provided for convenience.

Renders the widget into the painter's QPainter.device().

Transformations and settings applied to the painter will be used when rendering.

Note: The painter must be active. On Mac OS X the widget will be rendered into a QPixmap and then drawn by the painter.

See also QPainter.device().

QWidget