QWidget¶
- PyQt5.QtWidgets.QWidget
Inherits from QObject, QPaintDevice.
Inherited by QAbstractButton, QAbstractSlider, QAbstractSpinBox, QAxWidget, QCalendarWidget, QComboBox, QDesignerActionEditorInterface, QDesignerFormWindowInterface, QDesignerObjectInspectorInterface, QDesignerPropertyEditorInterface, QDesignerWidgetBoxInterface, QDesktopWidget, QDialog, QDialogButtonBox, QDockWidget, QFocusFrame, QFrame, QGLWidget, QGroupBox, QHelpFilterSettingsWidget, QHelpSearchQueryWidget, QHelpSearchResultWidget, QKeySequenceEdit, QLineEdit, QMacCocoaViewContainer, QMainWindow, QMdiSubWindow, QMenu, QMenuBar, QOpenGLWidget, QPrintPreviewWidget, QProgressBar, QQuickWidget, QRubberBand, QSizeGrip, QSplashScreen, QSplitterHandle, QStatusBar, QSvgWidget, QTabBar, QTabWidget, QToolBar, QVideoWidget, QWebEngineView, QWizardPage.
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 is not 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:
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 Window as window flag).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, 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.

The diagram above 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 Management for more information.
Composite Widgets¶
When a widget 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 Tutorials.
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.
Note: The size of top-level widgets are constrained to 2/3 of the desktop’s height and width. You can resize() the widget manually if these bounds are inadequate.
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:
paintEvent() is called whenever the widget needs to be repainted. Every widget displaying custom content must implement it. Painting using a QPainter can only take place in a paintEvent() or a function called by a paintEvent().
resizeEvent() is called when the widget has been resized.
mousePressEvent() is called when a mouse button is pressed while the mouse cursor is inside the widget, or when the widget has grabbed the mouse using grabMouse(). Pressing the mouse without releasing it is effectively the same as calling grabMouse().
mouseReleaseEvent() is called when a mouse button is released. A widget receives mouse release events when it has received the corresponding mouse press event. This means that if the user presses the mouse inside your widget, then drags the mouse somewhere else before releasing the mouse button, your widget receives the release event. There is one exception: if a popup menu appears while the mouse button is held down, this popup immediately steals the mouse events.
mouseDoubleClickEvent() is called when the user double-clicks in the widget. If the user double-clicks, the widget receives a mouse press event, a mouse release event, (a mouse click event,) a second mouse press, this event and finally a second mouse release event. (Some mouse move events may also be received if the mouse is not held steady during this operation.) It is not possible to distinguish a click from a double-click until the second click arrives. (This is one reason why most GUI books recommend that double-clicks be an extension of single-clicks, rather than trigger a different action.)
Widgets that accept keyboard input need to reimplement a few more event handlers:
keyPressEvent() is called whenever a key is pressed, and again when a key has been held down long enough for it to auto-repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement event().
focusInEvent() is called when the widget gains keyboard focus (assuming you have called setFocusPolicy()). Well-behaved widgets indicate that they own the keyboard focus in a clear but discreet way.
focusOutEvent() is called when the widget loses keyboard focus.
You may be required to also reimplement some of the less common event handlers:
mouseMoveEvent() is called whenever the mouse moves while a mouse button is held down. This can be useful during drag and drop operations. If you call setMouseTracking()(true), you get mouse move events even when no buttons are held down. (See also the Drag and Drop guide.)
keyReleaseEvent() is called whenever a key is released and while it is held down (if the key is auto-repeating). In that case, the widget will receive a pair of key release and key press event for every repeat. The Tab and Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement event().
wheelEvent() is called whenever the user turns the mouse wheel while the widget has the focus.
enterEvent() is called when the mouse enters the widget’s screen space. (This excludes screen space owned by any of the widget’s children.)
leaveEvent() is called when the mouse leaves the widget’s screen space. If the mouse enters a child widget it will not cause a leaveEvent().
moveEvent() is called when the widget has been moved relative to its parent.
closeEvent() is called when the user closes the widget (or when close() is called).
There are also some rather obscure events described in the documentation for Type. To handle these events, you need to reimplement event() directly.
The default implementation of event() handles Tab and Shift+Tab (to move the keyboard focus), and passes on most of the other events to one of the more specialized handlers above.
Events and the mechanism used to deliver them are covered in The Event System.
Groups of Functions and Properties¶
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 widget style sheets is described in more detail in the Qt Style Sheets document.
Transparency and Double Buffering¶
Since Qt 4.0, QWidget automatically double-buffers its painting, so there is no need to write double-buffering code in paintEvent() to avoid flicker.
Since Qt 4.1, the WA_ContentsPropagated widget attribute has been deprecated. Instead, the contents of parent widgets are propagated by default to each of their children as long as WA_PaintOnScreen is not set. Custom widgets can be written to take advantage of this feature by updating irregular regions (to create non-rectangular child widgets), or painting with colors that have less than 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:
The left widget has no additional properties or widget attributes set. This default state suits most custom widgets using transparency, are irregularly-shaped, or do not paint over their entire area with an opaque brush.
The center widget has the autoFillBackground() property set. This property is used with custom widgets that rely on the widget to supply a default background, and do not paint over their entire area with an opaque brush.
The right widget has the WA_OpaquePaintEvent widget attribute set. This indicates that the widget will paint over its entire area with opaque colors. The widget’s area will initially be uninitialized, represented in the diagram with a red diagonal grid pattern that shines through the overpainted area. The Qt::WA_OpaquePaintArea attribute is useful for widgets that need to paint their own specialized contents quickly and do not need a default filled background.
To rapidly update 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 Window role), set the autoFillBackground() property, and only implement the necessary drawing functionality in the widget’s paintEvent().
To rapidly update custom widgets that constantly paint over their entire areas with opaque content, e.g., video streaming widgets, it is better to set the widget’s WA_OpaquePaintEvent, avoiding any unnecessary overhead associated with repainting the widget’s background.
If a widget has both the WA_OpaquePaintEvent widget attribute and the autoFillBackground() property set, the WA_OpaquePaintEvent attribute takes precedence. Depending on your requirements, you should choose either one of them.
Since 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.
Creating Translucent Windows¶
Since Qt 4.5, it has been possible to create windows with translucent regions on window systems that support compositing.
To enable this feature in a top-level widget, set its WA_TranslucentBackground attribute with setAttribute() and ensure that its background is painted with non-opaque colors in the regions you want to be partially transparent.
Platform notes:
X11: This feature relies on the use of an X server that supports ARGB visuals and a compositing window manager.
Windows: The widget needs to have the FramelessWindowHint window flag set for the translucency to work.
Native Widgets vs Alien Widgets¶
Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing system. They do not have a native window handle associated with them. This feature significantly speeds up widget painting, resizing, and removes flicker.
Should you require the old behavior with native windows, you can choose one of the following options:
Use the
QT_USE_NATIVE_WINDOWS=1
in your environment.Set the AA_NativeWindows attribute on your application. All widgets will be native widgets.
Set the WA_NativeWindow attribute on widgets: The widget itself and all of its ancestors will become native (unless WA_DontCreateNativeAncestors is set).
Call winId() to enforce a native window (this implies 3).
Set the WA_PaintOnScreen attribute to enforce a native window (this implies 3).
Classes¶
Enums¶
- RenderFlag
This enum describes how to render the widget when calling render().
Member
Value
Description
DrawChildren 0x2
If you enable this option, the widget’s children are rendered recursively into the target. By default, this option is enabled.
DrawWindowBackground 0x1
If 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.
IgnoreMask 0x4
If you enable this option, the widget’s mask() is ignored when rendering into the target. By default, this option is disabled.
Methods¶
- __init__(parent: QWidget = None, flags: Union[WindowFlags, WindowType] = Qt.WindowFlags())
TODO
- acceptDrops() bool
See also
- accessibleDescription() str
See also
- accessibleName() str
See also
- actionEvent(QActionEvent)
TODO
- actions() List[ QAction]
TODO
- activateWindow()
TODO
- addAction(QAction)
TODO
- addActions(Iterable[QAction])
TODO
- adjustSize()
TODO
- autoFillBackground() bool
See also
- backgroundRole() ColorRole
See also
- baseSize() QSize
See also
- changeEvent(QEvent)
TODO
- childAt(int, int) QWidget
TODO
- childrenRect() QRect
TODO
- childrenRegion() QRegion
TODO
- clearFocus()
TODO
- clearMask()
TODO
- close() bool
TODO
- closeEvent(QCloseEvent)
TODO
- contentsMargins() QMargins
See also
- contentsRect() QRect
TODO
- contextMenuEvent(QContextMenuEvent)
TODO
- contextMenuPolicy() ContextMenuPolicy
See also
- create(window: PyQt5.sip.voidptr = 0, initializeWindow: bool = True, destroyOldWindow: bool = True)
TODO
-
@staticmethod
createWindowContainer(QWindow, parent: QWidget = None, flags: Union[WindowFlags, WindowType] = 0) QWidget TODO
- cursor() QCursor
See also
- destroy(destroyWindow: bool = True, destroySubWindows: bool = True)
TODO
- devType() int
TODO
- dragEnterEvent(QDragEnterEvent)
TODO
- dragLeaveEvent(QDragLeaveEvent)
TODO
- dragMoveEvent(QDragMoveEvent)
TODO
- dropEvent(QDropEvent)
TODO
- effectiveWinId() PyQt5.sip.voidptr
TODO
- ensurePolished()
TODO
- enterEvent(QEvent)
TODO
- event(QEvent) bool
TODO
-
@staticmethod
find(PyQt5.sip.voidptr) QWidget TODO
- focusInEvent(QFocusEvent)
TODO
- focusNextChild() bool
TODO
- focusNextPrevChild(bool) bool
TODO
- focusOutEvent(QFocusEvent)
TODO
- focusPolicy() FocusPolicy
See also
- focusPreviousChild() bool
TODO
- focusProxy() QWidget
See also
- focusWidget() QWidget
TODO
- fontInfo() QFontInfo
TODO
- fontMetrics() QFontMetrics
TODO
- foregroundRole() ColorRole
See also
- frameGeometry() QRect
TODO
- frameSize() QSize
TODO
- geometry() QRect
See also
- getContentsMargins() (int, int, int, int)
TODO
- grabGesture(GestureType, flags: Union[GestureFlags, GestureFlag] = Qt.GestureFlags())
TODO
- grabKeyboard()
TODO
- grabMouse()
TODO
- grabMouse(Union[QCursor, CursorShape])
TODO
- grabShortcut(Union[QKeySequence, StandardKey, str, int], context: ShortcutContext = WindowShortcut) int
TODO
- graphicsEffect() QGraphicsEffect
TODO
- graphicsProxyWidget() QGraphicsProxyWidget
TODO
- hasFocus() bool
TODO
- hasHeightForWidth() bool
TODO
- hasMouseTracking() bool
TODO
- hasTabletTracking() bool
TODO
- height() int
TODO
- heightForWidth(int) int
TODO
- hide()
TODO
- hideEvent(QHideEvent)
TODO
- initPainter(QPainter)
TODO
- inputMethodEvent(QInputMethodEvent)
TODO
- inputMethodHints() InputMethodHints
See also
- inputMethodQuery(InputMethodQuery) Any
TODO
- isActiveWindow() bool
TODO
- isAncestorOf(QWidget) bool
TODO
- isEnabled() bool
TODO
- isEnabledTo(QWidget) bool
TODO
- isFullScreen() bool
TODO
- isHidden() bool
TODO
- isLeftToRight() bool
TODO
- isMaximized() bool
TODO
- isMinimized() bool
TODO
- isModal() bool
TODO
- isRightToLeft() bool
TODO
- isVisible() bool
TODO
- isVisibleTo(QWidget) bool
TODO
- isWindow() bool
TODO
- isWindowModified() bool
TODO
-
@staticmethod
keyboardGrabber() QWidget TODO
- keyPressEvent(QKeyEvent)
TODO
- keyReleaseEvent(QKeyEvent)
TODO
- layout() QLayout
See also
- layoutDirection() LayoutDirection
See also
- leaveEvent(QEvent)
TODO
- locale() QLocale
See also
- lower()
TODO
- maximumHeight() int
See also
- maximumSize() QSize
See also
- maximumWidth() int
See also
- metric(PaintDeviceMetric) int
TODO
- minimumHeight() int
See also
- minimumSize() QSize
See also
- minimumSizeHint() QSize
TODO
- minimumWidth() int
See also
- mouseDoubleClickEvent(QMouseEvent)
TODO
-
@staticmethod
mouseGrabber() QWidget TODO
- mouseMoveEvent(QMouseEvent)
TODO
- mousePressEvent(QMouseEvent)
TODO
- mouseReleaseEvent(QMouseEvent)
TODO
- move(QPoint)
TODO
- move(int, int)
TODO
- moveEvent(QMoveEvent)
TODO
- nativeEvent(Union[QByteArray, bytes, bytearray], sip.voidptr) (bool, int)
TODO
- nativeParentWidget() QWidget
TODO
- nextInFocusChain() QWidget
TODO
- normalGeometry() QRect
TODO
- overrideWindowFlags(Union[WindowFlags, WindowType])
TODO
- overrideWindowState(Union[WindowStates, WindowState])
TODO
- paintEngine() QPaintEngine
TODO
- paintEvent(QPaintEvent)
TODO
- palette() QPalette
See also
- parentWidget() QWidget
TODO
- pos() QPoint
TODO
- previousInFocusChain() QWidget
TODO
- raise_()
TODO
- rect() QRect
TODO
- releaseKeyboard()
TODO
- releaseMouse()
TODO
- releaseShortcut(int)
TODO
- removeAction(QAction)
TODO
- render(QPaintDevice, targetOffset: QPoint = QPoint(), sourceRegion: QRegion = QRegion(), flags: Union[RenderFlags, RenderFlag] = QWidget.RenderFlags(QWidget.RenderFlag.DrawWindowBackground|QWidget.RenderFlag.DrawChildren))
TODO
- render(QPainter, targetOffset: QPoint = QPoint(), sourceRegion: QRegion = QRegion(), flags: Union[RenderFlags, RenderFlag] = QWidget.RenderFlags(QWidget.RenderFlag.DrawWindowBackground|QWidget.RenderFlag.DrawChildren))
TODO
- repaint()
TODO
- repaint(QRect)
TODO
- repaint(QRegion)
TODO
- repaint(int, int, int, int)
TODO
- resize(QSize)
TODO
- resize(int, int)
TODO
- resizeEvent(QResizeEvent)
TODO
- restoreGeometry(Union[QByteArray, bytes, bytearray]) bool
TODO
- saveGeometry() QByteArray
TODO
- screen() QScreen
TODO
- scroll(int, int)
TODO
- scroll(int, int, QRect)
TODO
- setAcceptDrops(bool)
See also
- setAccessibleDescription(str)
See also
- setAccessibleName(str)
See also
- setAttribute(WidgetAttribute, on: bool = True)
TODO
- setAutoFillBackground(bool)
See also
- setBackgroundRole(ColorRole)
See also
- setBaseSize(QSize)
See also
- setBaseSize(int, int)
TODO
- setContentsMargins(QMargins)
TODO
- setContentsMargins(int, int, int, int)
See also
- setContextMenuPolicy(ContextMenuPolicy)
See also
- setCursor(Union[QCursor, CursorShape])
See also
- setDisabled(bool)
TODO
- setEnabled(bool)
See also
- setFixedHeight(int)
TODO
- setFixedSize(QSize)
TODO
- setFixedSize(int, int)
TODO
- setFixedWidth(int)
TODO
- setFocus()
See also
- setFocus(FocusReason)
TODO
- setFocusPolicy(FocusPolicy)
See also
- setFocusProxy(QWidget)
See also
- setForegroundRole(ColorRole)
See also
- setGeometry(QRect)
TODO
- setGeometry(int, int, int, int)
See also
- setGraphicsEffect(QGraphicsEffect)
TODO
- setHidden(bool)
See also
- setInputMethodHints(Union[InputMethodHints, InputMethodHint])
See also
- setLayoutDirection(LayoutDirection)
See also
- setMask(QRegion)
TODO
- setMaximumHeight(int)
See also
- setMaximumSize(QSize)
See also
- setMaximumSize(int, int)
TODO
- setMaximumWidth(int)
See also
- setMinimumHeight(int)
See also
- setMinimumSize(QSize)
See also
- setMinimumSize(int, int)
TODO
- setMinimumWidth(int)
See also
- setMouseTracking(bool)
See also
- setParent(QWidget)
TODO
- setParent(QWidget, Union[WindowFlags, WindowType])
TODO
- setShortcutAutoRepeat(int, enabled: bool = True)
TODO
- setShortcutEnabled(int, enabled: bool = True)
TODO
- setSizeIncrement(QSize)
See also
- setSizeIncrement(int, int)
TODO
- setSizePolicy(QSizePolicy)
TODO
- setStatusTip(str)
TODO
- setStyleSheet(str)
See also
- setTabletTracking(bool)
See also
- setToolTip(str)
See also
- setToolTipDuration(int)
See also
- setUpdatesEnabled(bool)
See also
- setVisible(bool)
See also
- setWhatsThis(str)
TODO
- setWindowFilePath(str)
See also
- setWindowFlag(WindowType, on: bool = True)
TODO
- setWindowFlags(Union[WindowFlags, WindowType])
See also
- setWindowIcon(QIcon)
See also
- setWindowIconText(str)
See also
- setWindowModality(WindowModality)
See also
- setWindowModified(bool)
See also
- setWindowOpacity(float)
See also
- setWindowRole(str)
See also
- setWindowState(Union[WindowStates, WindowState])
See also
- setWindowTitle(str)
See also
TODO
- show()
TODO
- showEvent(QShowEvent)
TODO
- showFullScreen()
TODO
- showMaximized()
TODO
- showMinimized()
TODO
- showNormal()
TODO
- size() QSize
TODO
- sizeHint() QSize
TODO
- sizeIncrement() QSize
See also
- sizePolicy() QSizePolicy
See also
- stackUnder(QWidget)
TODO
- statusTip() str
TODO
- style() QStyle
See also
- styleSheet() str
See also
- tabletEvent(QTabletEvent)
TODO
- testAttribute(WidgetAttribute) bool
TODO
- toolTip() str
See also
- toolTipDuration() int
See also
- underMouse() bool
TODO
- ungrabGesture(GestureType)
TODO
- unsetCursor()
TODO
- unsetLayoutDirection()
TODO
- unsetLocale()
TODO
- update()
TODO
- update(QRect)
TODO
- update(QRegion)
TODO
- update(int, int, int, int)
TODO
- updateGeometry()
TODO
- updateMicroFocus()
TODO
- updatesEnabled() bool
See also
- visibleRegion() QRegion
TODO
- whatsThis() str
TODO
- wheelEvent(QWheelEvent)
TODO
- width() int
TODO
- window() QWidget
TODO
- windowFilePath() str
See also
- windowFlags() WindowFlags
See also
- windowHandle() QWindow
TODO
- windowIcon() QIcon
See also
- windowIconText() str
See also
- windowModality() WindowModality
See also
- windowOpacity() float
See also
- windowRole() str
See also
- windowState() WindowStates
See also
- windowTitle() str
See also
- windowType() WindowType
TODO
- winId() PyQt5.sip.voidptr
TODO
- x() int
TODO
- y() int
TODO
Signals¶
- customContextMenuRequested(QPoint)
TODO
- windowIconChanged(QIcon)
TODO
- windowIconTextChanged(str)
TODO
- windowTitleChanged(str)
TODO