1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qapplication.h"
43 #include "qapplication_p.h"
46 #include "qdesktopwidget.h"
51 #include "qmetaobject.h"
56 #include "qstylefactory.h"
59 #include "qstyleoption.h"
60 #include "qstylehints.h"
61 #ifndef QT_NO_ACCESSIBILITY
62 # include "qaccessible.h"
65 # include "qt_mac_p.h"
66 # include "qt_cocoa_helpers_mac_p.h"
67 # include "qmainwindow.h"
68 # include "qtoolbar.h"
69 # include <private/qmainwindowlayout_p.h>
71 #include <qpa/qplatformwindow.h>
72 #include "private/qwidgetwindow_qpa_p.h"
75 #include "qwhatsthis.h"
77 #include "private/qstylesheetstyle_p.h"
78 #include "private/qstyle_p.h"
79 #include "qfileinfo.h"
80 #include <QtGui/qinputmethod.h>
82 #include <private/qgraphicseffect_p.h>
83 #include <qbackingstore.h>
84 #include <private/qwidgetbackingstore_p.h>
86 # include <private/qpaintengine_mac_p.h>
88 #include <private/qpaintengine_raster_p.h>
90 #include "qwidget_p.h"
91 #include <QtGui/private/qwindow_p.h>
92 #include "qaction_p.h"
93 #include "qlayout_p.h"
94 #include "QtWidgets/qgraphicsproxywidget.h"
95 #include "QtWidgets/qgraphicsscene.h"
96 #include "private/qgraphicsproxywidget_p.h"
97 #include "QtWidgets/qabstractscrollarea.h"
98 #include "private/qabstractscrollarea_p.h"
99 #include "private/qevent_p.h"
101 #include "private/qgesturemanager_p.h"
103 #ifdef QT_KEYPAD_NAVIGATION
104 #include "qtabwidget.h" // Needed in inTabWidget()
105 #endif // QT_KEYPAD_NAVIGATION
108 // widget/widget data creation count
109 //#define QWIDGET_EXTRA_DEBUG
110 //#define ALIEN_DEBUG
114 static bool qt_enable_backingstore = true;
116 // for compatibility with Qt 4.0
117 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
119 qt_enable_backingstore = enable;
124 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
127 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
129 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
130 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
133 static inline bool hasBackingStoreSupport()
139 # define QT_NO_PAINT_DEBUG
142 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
143 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
147 \class QWidgetBackingStoreTracker
148 \brief Class which allows tracking of which widgets are using a given backing store
150 QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
151 which maintains a list of the QWidgets which are currently using the backing
152 store. This list is modified via the registerWidget and unregisterWidget functions.
155 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
161 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
168 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
169 widgets using the backing store, then create a new QWidgetBackingStore, providing
172 void QWidgetBackingStoreTracker::create(QWidget *widget)
175 m_ptr = new QWidgetBackingStore(widget);
180 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181 widgets using the backing store.
183 void QWidgetBackingStoreTracker::destroy()
192 Add the widget to the list of widgets currently using the backing store.
193 If the widget was already in the list, this function is a no-op.
195 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
198 Q_ASSERT(w->internalWinId());
199 Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
205 Remove the widget from the list of widgets currently using the backing store.
206 If the widget was in the list, and removing it causes the list to be empty,
207 the backing store is deleted.
208 If the widget was not in the list, this function is a no-op.
210 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
212 if (m_widgets.remove(w) && m_widgets.isEmpty()) {
220 Recursively remove widget and all of its descendents.
222 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
224 unregisterWidget(widget);
225 foreach (QObject *child, widget->children())
226 if (QWidget *childWidget = qobject_cast<QWidget *>(child))
227 unregisterWidgetSubtree(childWidget);
230 QWidgetPrivate::QWidgetPrivate(int version)
231 : QObjectPrivate(version)
240 , extraPaintEngine(0)
243 #if !defined(QT_NO_IM)
244 , imHints(Qt::ImhNone)
246 , inheritedFontResolveMask(0)
247 , inheritedPaletteResolveMask(0)
252 , leftLayoutItemMargin(0)
253 , topLayoutItemMargin(0)
254 , rightLayoutItemMargin(0)
255 , bottomLayoutItemMargin(0)
257 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
258 , fg_role(QPalette::NoRole)
259 , bg_role(QPalette::NoRole)
260 , dirtyOpaqueChildren(1)
265 , usesDoubleBufferedGLContext(0)
267 , inheritsInputMethodHints(0)
269 #if defined(Q_OS_WIN)
272 #if defined(Q_WS_X11)
274 #elif defined(Q_WS_WIN)
275 #ifndef QT_NO_GESTURES
276 , nativeGesturePanEnabled(0)
278 #elif defined(Q_WS_MAC)
279 , needWindowChange(0)
285 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
289 if (version != QObjectPrivateVersion)
290 qFatal("Cannot mix incompatible Qt libraries");
293 memset(high_attributes, 0, sizeof(high_attributes));
295 drawRectOriginalAdded = false;
296 originalDrawMethod = true;
297 changeMethods = false;
298 isInUnifiedToolbar = false;
300 toolbar_ancestor = 0;
301 flushRequested = false;
302 touchEventsEnabled = false;
304 #ifdef QWIDGET_EXTRA_DEBUG
305 static int count = 0;
306 qDebug() << "widgets" << ++count;
311 QWidgetPrivate::~QWidgetPrivate()
319 #ifndef QT_NO_GRAPHICSEFFECT
320 delete graphicsEffect;
321 #endif //QT_NO_GRAPHICSEFFECT
327 void QWidgetPrivate::scrollChildren(int dx, int dy)
330 if (q->children().size() > 0) { // scroll children
332 QObjectList childObjects = q->children();
333 for (int i = 0; i < childObjects.size(); ++i) { // move all children
334 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
335 if (w && !w->isWindow()) {
336 QPoint oldp = w->pos();
337 QRect r(w->pos() + pd, w->size());
339 if (w->testAttribute(Qt::WA_WState_Created))
340 w->d_func()->setWSGeometry();
341 w->d_func()->setDirtyOpaqueRegion();
342 QMoveEvent e(r.topLeft(), oldp);
343 QApplication::sendEvent(w, &e);
349 void QWidgetPrivate::updateWidgetTransform()
352 if (q == qGuiApp->focusObject()) {
354 QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
355 t.translate(p.x(), p.y());
356 qApp->inputMethod()->setInputItemTransform(t);
360 #ifdef QT_KEYPAD_NAVIGATION
361 QPointer<QWidget> QWidgetPrivate::editingWidget;
364 Returns true if this widget currently has edit focus; otherwise false.
366 This feature is only available in Qt for Embedded Linux.
368 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
370 bool QWidget::hasEditFocus() const
372 const QWidget* w = this;
373 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
374 w = w->d_func()->extra->focus_proxy;
375 return QWidgetPrivate::editingWidget == w;
379 \fn void QWidget::setEditFocus(bool enable)
381 If \a enable is true, make this widget have edit focus, in which
382 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
383 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
386 This feature is only available in Qt for Embedded Linux.
388 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
390 void QWidget::setEditFocus(bool on)
393 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
394 f = f->d_func()->extra->focus_proxy;
396 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
397 QWidgetPrivate::editingWidget->setEditFocus(false);
399 if (on && !f->hasFocus())
402 if ((!on && !QWidgetPrivate::editingWidget)
403 || (on && QWidgetPrivate::editingWidget == f)) {
407 if (!on && QWidgetPrivate::editingWidget == f) {
408 QWidgetPrivate::editingWidget = 0;
409 QEvent event(QEvent::LeaveEditFocus);
410 QApplication::sendEvent(f, &event);
411 QApplication::sendEvent(f->style(), &event);
413 QWidgetPrivate::editingWidget = f;
414 QEvent event(QEvent::EnterEditFocus);
415 QApplication::sendEvent(f, &event);
416 QApplication::sendEvent(f->style(), &event);
422 \property QWidget::autoFillBackground
423 \brief whether the widget background is filled automatically
426 If enabled, this property will cause Qt to fill the background of the
427 widget before invoking the paint event. The color used is defined by the
428 QPalette::Window color role from the widget's \l{QPalette}{palette}.
430 In addition, Windows are always filled with QPalette::Window, unless the
431 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
433 This property cannot be turned off (i.e., set to false) if a widget's
434 parent has a static gradient for its background.
436 \warning Use this property with caution in conjunction with
437 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
438 background or a border-image, this property is automatically disabled.
440 By default, this property is false.
442 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
443 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
445 bool QWidget::autoFillBackground() const
448 return d->extra && d->extra->autoFillBackground;
451 void QWidget::setAutoFillBackground(bool enabled)
456 if (d->extra->autoFillBackground == enabled)
459 d->extra->autoFillBackground = enabled;
467 \brief The QWidget class is the base class of all user interface objects.
469 \ingroup basicwidgets
472 The widget is the atom of the user interface: it receives mouse, keyboard
473 and other events from the window system, and paints a representation of
474 itself on the screen. Every widget is rectangular, and they are sorted in a
475 Z-order. A widget is clipped by its parent and by the widgets in front of
478 A widget that is not embedded in a parent widget is called a window.
479 Usually, windows have a frame and a title bar, although it is also possible
480 to create windows without such decoration using suitable
481 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
482 subclasses of QDialog are the most common window types.
484 Every widget's constructor accepts one or two standard arguments:
487 \li \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
488 (the default), the new widget will be a window. If not, it will be
489 a child of \e parent, and be constrained by \e parent's geometry
490 (unless you specify Qt::Window as window flag).
491 \li \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
492 the default is suitable for almost all widgets, but to get, for
493 example, a window without a window system frame, you must use
497 QWidget has many member functions, but some of them have little direct
498 functionality; for example, QWidget has a font property, but never uses
499 this itself. There are many subclasses which provide real functionality,
500 such as QLabel, QPushButton, QListWidget, and QTabWidget.
503 \section1 Top-Level and Child Widgets
505 A widget without a parent widget is always an independent window (top-level
506 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
507 title bar and icon respectively.
509 Non-window widgets are child widgets, displayed within their parent
510 widgets. Most widgets in Qt are mainly useful as child widgets. For
511 example, it is possible to display a button as a top-level window, but most
512 people prefer to put their buttons inside other widgets, such as QDialog.
514 \image parent-child-widgets.png A parent widget containing various child widgets.
516 The diagram above shows a QGroupBox widget being used to hold various child
517 widgets in a layout provided by QGridLayout. The QLabel child widgets have
518 been outlined to indicate their full sizes.
520 If you want to use a QWidget to hold child widgets you will usually want to
521 add a layout to the parent QWidget. See \l{Layout Management} for more
525 \section1 Composite Widgets
527 When a widget is used as a container to group a number of child widgets, it
528 is known as a composite widget. These can be created by constructing a
529 widget with the required visual properties - a QFrame, for example - and
530 adding child widgets to it, usually managed by a layout. The above diagram
531 shows such a composite widget that was created using Qt Designer.
533 Composite widgets can also be created by subclassing a standard widget,
534 such as QWidget or QFrame, and adding the necessary layout and child
535 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
536 {examples provided with Qt} use this approach, and it is also covered in
537 the Qt \l{Tutorials}.
540 \section1 Custom Widgets and Painting
542 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
543 display custom content that is composed using a series of painting
544 operations with an instance of the QPainter class. This approach contrasts
545 with the canvas-style approach used by the \l{Graphics View}
546 {Graphics View Framework} where items are added to a scene by the
547 application and are rendered by the framework itself.
549 Each widget performs all painting operations from within its paintEvent()
550 function. This is called whenever the widget needs to be redrawn, either
551 as a result of some external change or when requested by the application.
553 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
554 can handle paint events.
557 \section1 Size Hints and Size Policies
559 When implementing a new widget, it is almost always useful to reimplement
560 sizeHint() to provide a reasonable default size for the widget and to set
561 the correct size policy with setSizePolicy().
563 By default, composite widgets which do not provide a size hint will be
564 sized according to the space requirements of their child widgets.
566 The size policy lets you supply good default behavior for the layout
567 management system, so that other widgets can contain and manage yours
568 easily. The default size policy indicates that the size hint represents
569 the preferred size of the widget, and this is often good enough for many
572 \note The size of top-level widgets are constrained to 2/3 of the desktop's
573 height and width. You can resize() the widget manually if these bounds are
579 Widgets respond to events that are typically caused by user actions. Qt
580 delivers events to widgets by calling specific event handler functions with
581 instances of QEvent subclasses containing information about each event.
583 If your widget only contains child widgets, you probably do not need to
584 implement any event handlers. If you want to detect a mouse click in a
585 child widget call the child's underMouse() function inside the widget's
588 The \l{widgets/scribble}{Scribble example} implements a wider set of
589 events to handle mouse movement, button presses, and window resizing.
591 You will need to supply the behavior and content for your own widgets, but
592 here is a brief overview of the events that are relevant to QWidget,
593 starting with the most common ones:
596 \li paintEvent() is called whenever the widget needs to be repainted.
597 Every widget displaying custom content must implement it. Painting
598 using a QPainter can only take place in a paintEvent() or a
599 function called by a paintEvent().
600 \li resizeEvent() is called when the widget has been resized.
601 \li mousePressEvent() is called when a mouse button is pressed while
602 the mouse cursor is inside the widget, or when the widget has
603 grabbed the mouse using grabMouse(). Pressing the mouse without
604 releasing it is effectively the same as calling grabMouse().
605 \li mouseReleaseEvent() is called when a mouse button is released. A
606 widget receives mouse release events when it has received the
607 corresponding mouse press event. This means that if the user
608 presses the mouse inside \e your widget, then drags the mouse
609 somewhere else before releasing the mouse button, \e your widget
610 receives the release event. There is one exception: if a popup menu
611 appears while the mouse button is held down, this popup immediately
612 steals the mouse events.
613 \li mouseDoubleClickEvent() is called when the user double-clicks in
614 the widget. If the user double-clicks, the widget receives a mouse
615 press event, a mouse release event, (a mouse click event,) a second
616 mouse press, this event and finally a second mouse release event.
617 (Some mouse move events may also be
618 received if the mouse is not held steady during this operation.) It
619 is \e{not possible} to distinguish a click from a double-click
620 until the second click arrives. (This is one reason why most GUI
621 books recommend that double-clicks be an extension of
622 single-clicks, rather than trigger a different action.)
625 Widgets that accept keyboard input need to reimplement a few more event
629 \li keyPressEvent() is called whenever a key is pressed, and again when
630 a key has been held down long enough for it to auto-repeat. The
631 \uicontrol Tab and \uicontrol Shift+Tab keys are only passed to the widget if
632 they are not used by the focus-change mechanisms. To force those
633 keys to be processed by your widget, you must reimplement
635 \li focusInEvent() is called when the widget gains keyboard focus
636 (assuming you have called setFocusPolicy()). Well-behaved widgets
637 indicate that they own the keyboard focus in a clear but discreet
639 \li focusOutEvent() is called when the widget loses keyboard focus.
642 You may be required to also reimplement some of the less common event
646 \li mouseMoveEvent() is called whenever the mouse moves while a mouse
647 button is held down. This can be useful during drag and drop
648 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
649 you get mouse move events even when no buttons are held down.
650 (See also the \l{Drag and Drop} guide.)
651 \li keyReleaseEvent() is called whenever a key is released and while it
652 is held down (if the key is auto-repeating). In that case, the
653 widget will receive a pair of key release and key press event for
654 every repeat. The \uicontrol Tab and \uicontrol Shift+Tab keys are only passed
655 to the widget if they are not used by the focus-change mechanisms.
656 To force those keys to be processed by your widget, you must
657 reimplement QWidget::event().
658 \li wheelEvent() is called whenever the user turns the mouse wheel
659 while the widget has the focus.
660 \li enterEvent() is called when the mouse enters the widget's screen
661 space. (This excludes screen space owned by any of the widget's
663 \li leaveEvent() is called when the mouse leaves the widget's screen
664 space. If the mouse enters a child widget it will not cause a
666 \li moveEvent() is called when the widget has been moved relative to
668 \li closeEvent() is called when the user closes the widget (or when
672 There are also some rather obscure events described in the documentation
673 for QEvent::Type. To handle these events, you need to reimplement event()
676 The default implementation of event() handles \uicontrol Tab and \uicontrol Shift+Tab
677 (to move the keyboard focus), and passes on most of the other events to
678 one of the more specialized handlers above.
680 Events and the mechanism used to deliver them are covered in
681 \l{The Event System}.
683 \section1 Groups of Functions and Properties
686 \header \li Context \li Functions and Properties
688 \row \li Window functions \li
695 \row \li Top-level windows \li
696 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
697 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
698 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
701 \row \li Window contents \li
706 \row \li Geometry \li
707 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
708 \l sizePolicy, sizeHint(), minimumSizeHint(),
709 updateGeometry(), layout(),
710 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
712 mapFromGlobal(), mapToGlobal(),
713 mapFromParent(), mapToParent(),
714 \l maximumSize, \l minimumSize, \l sizeIncrement,
715 \l baseSize, setFixedSize()
718 \l visible, isVisibleTo(),
719 \l enabled, isEnabledTo(),
726 \row \li Look and feel \li
733 backgroundRole(), setBackgroundRole(),
734 fontInfo(), fontMetrics().
736 \row \li Keyboard focus functions \li
737 \l focus, \l focusPolicy,
738 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
739 focusNextChild(), focusPreviousChild().
741 \row \li Mouse and keyboard grabbing \li
742 grabMouse(), releaseMouse(),
743 grabKeyboard(), releaseKeyboard(),
744 mouseGrabber(), keyboardGrabber().
746 \row \li Event handlers \li
750 mouseDoubleClickEvent(),
773 \row \li System functions \li
774 parentWidget(), window(), setParent(), winId(),
777 \row \li Interactive help \li
778 setToolTip(), setWhatsThis()
783 \section1 Widget Style Sheets
785 In addition to the standard widget styles for each platform, widgets can
786 also be styled according to rules specified in a \l{styleSheet}
787 {style sheet}. This feature enables you to customize the appearance of
788 specific widgets to provide visual cues to users about their purpose. For
789 example, a button could be styled in a particular way to indicate that it
790 performs a destructive action.
792 The use of widget style sheets is described in more detail in the
793 \l{Qt Style Sheets} document.
796 \section1 Transparency and Double Buffering
798 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
799 is no need to write double-buffering code in paintEvent() to avoid
802 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
803 deprecated. Instead, the contents of parent widgets are propagated by
804 default to each of their children as long as Qt::WA_PaintOnScreen is not
805 set. Custom widgets can be written to take advantage of this feature by
806 updating irregular regions (to create non-rectangular child widgets), or
807 painting with colors that have less than full alpha component. The
808 following diagram shows how attributes and properties of a custom widget
809 can be fine-tuned to achieve different effects.
811 \image propagation-custom.png
813 In the above diagram, a semi-transparent rectangular child widget with an
814 area removed is constructed and added to a parent widget (a QLabel showing
815 a pixmap). Then, different properties and widget attributes are set to
816 achieve different effects:
819 \li The left widget has no additional properties or widget attributes
820 set. This default state suits most custom widgets using
821 transparency, are irregularly-shaped, or do not paint over their
822 entire area with an opaque brush.
823 \li The center widget has the \l autoFillBackground property set. This
824 property is used with custom widgets that rely on the widget to
825 supply a default background, and do not paint over their entire
826 area with an opaque brush.
827 \li The right widget has the Qt::WA_OpaquePaintEvent widget attribute
828 set. This indicates that the widget will paint over its entire area
829 with opaque colors. The widget's area will initially be
830 \e{uninitialized}, represented in the diagram with a red diagonal
831 grid pattern that shines through the overpainted area. The
832 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
833 paint their own specialized contents quickly and do not need a
834 default filled background.
837 To rapidly update custom widgets with simple background colors, such as
838 real-time plotting or graphing widgets, it is better to define a suitable
839 background color (using setBackgroundRole() with the
840 QPalette::Window role), set the \l autoFillBackground property, and only
841 implement the necessary drawing functionality in the widget's paintEvent().
843 To rapidly update custom widgets that constantly paint over their entire
844 areas with opaque content, e.g., video streaming widgets, it is better to
845 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
846 associated with repainting the widget's background.
848 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
849 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
850 attribute takes precedence. Depending on your requirements, you should
851 choose either one of them.
853 Since Qt 4.1, the contents of parent widgets are also propagated to
854 standard Qt widgets. This can lead to some unexpected results if the
855 parent widget is decorated in a non-standard way, as shown in the diagram
858 \image propagation-standard.png
860 The scope for customizing the painting behavior of standard Qt widgets,
861 without resorting to subclassing, is slightly less than that possible for
862 custom widgets. Usually, the desired appearance of a standard widget can be
863 achieved by setting its \l autoFillBackground property.
866 \section1 Creating Translucent Windows
868 Since Qt 4.5, it has been possible to create windows with translucent regions
869 on window systems that support compositing.
871 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
872 attribute with setAttribute() and ensure that its background is painted with
873 non-opaque colors in the regions you want to be partially transparent.
878 \li X11: This feature relies on the use of an X server that supports ARGB visuals
879 and a compositing window manager.
880 \li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
881 for the translucency to work.
885 \section1 Native Widgets vs Alien Widgets
887 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
888 system. They do not have a native window handle associated with them. This
889 feature significantly speeds up widget painting, resizing, and removes flicker.
891 Should you require the old behavior with native windows, you can choose
892 one of the following options:
895 \li Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
896 \li Set the Qt::AA_NativeWindows attribute on your application. All
897 widgets will be native widgets.
898 \li Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
899 and all of its ancestors will become native (unless
900 Qt::WA_DontCreateNativeAncestors is set).
901 \li Call QWidget::winId to enforce a native window (this implies 3).
902 \li Set the Qt::WA_PaintOnScreen attribute to enforce a native window
906 \sa QEvent, QPainter, QGridLayout, QBoxLayout
910 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
911 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
914 /*****************************************************************************
915 QWidget utility functions
916 *****************************************************************************/
918 QRegion qt_dirtyRegion(QWidget *widget)
923 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
927 return bs->dirtyRegion(widget);
930 /*****************************************************************************
931 QWidget member functions
932 *****************************************************************************/
937 \li Qt::WA_WState_Created The widget has a valid winId().
938 \li Qt::WA_WState_Visible The widget is currently visible.
939 \li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
940 become visible unless you call show() on it. Qt::WA_WState_Hidden
941 implies !Qt::WA_WState_Visible.
942 \li Qt::WA_WState_CompressKeys Compress keyboard events.
943 \li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
944 \li Qt::WA_WState_InPaintEvent Currently processing a paint event.
945 \li Qt::WA_WState_Reparented The widget has been reparented.
946 \li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
947 \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
951 struct QWidgetExceptionCleaner
953 /* this cleans up when the constructor throws an exception */
954 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
956 #ifdef QT_NO_EXCEPTIONS
960 QWidgetPrivate::allWidgets->remove(that);
961 if (d->focus_next != that) {
963 d->focus_next->d_func()->focus_prev = d->focus_prev;
965 d->focus_prev->d_func()->focus_next = d->focus_next;
972 Constructs a widget which is a child of \a parent, with widget
975 If \a parent is 0, the new widget becomes a window. If
976 \a parent is another widget, this widget becomes a child window
977 inside \a parent. The new widget is deleted when its \a parent is
980 The widget flags argument, \a f, is normally 0, but it can be set
981 to customize the frame of a window (i.e. \a
982 parent must be 0). To customize the frame, use a value composed
983 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
985 If you add a child widget to an already visible widget you must
986 explicitly show the child to make it visible.
988 Note that the X11 version of Qt may not be able to deliver all
989 combinations of style flags on all systems. This is because on
990 X11, Qt can only ask the window manager, and the window manager
991 can override the application's settings. On Windows, Qt can set
992 whatever flags you want.
996 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
997 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1000 d_func()->init(parent, f);
1002 QWidgetExceptionCleaner::cleanup(this, d_func());
1010 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1011 : QObject(dd, 0), QPaintDevice()
1017 QWidgetExceptionCleaner::cleanup(this, d_func());
1025 int QWidget::devType() const
1027 return QInternal::Widget;
1031 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1032 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1034 bool customize = (flags & (Qt::CustomizeWindowHint
1035 | Qt::FramelessWindowHint
1036 | Qt::WindowTitleHint
1037 | Qt::WindowSystemMenuHint
1038 | Qt::WindowMinimizeButtonHint
1039 | Qt::WindowMaximizeButtonHint
1040 | Qt::WindowCloseButtonHint
1041 | Qt::WindowContextHelpButtonHint));
1043 uint type = (flags & Qt::WindowType_Mask);
1045 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1047 flags |= Qt::Window;
1050 if (flags & Qt::CustomizeWindowHint) {
1051 // modify window flags to make them consistent.
1052 // Only enable this on non-Mac platforms. Since the old way of doing this would
1053 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1054 // we can't just add this in.
1056 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1057 flags |= Qt::WindowSystemMenuHint;
1059 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1060 | Qt::WindowSystemMenuHint)) {
1062 flags |= Qt::WindowTitleHint;
1063 flags &= ~Qt::FramelessWindowHint;
1065 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1066 // if any of the window hints that affect the titlebar are set
1067 // and the window is supposed to have frame, we add a titlebar
1068 // and system menu by default.
1069 flags |= Qt::WindowSystemMenuHint;
1070 flags |= Qt::WindowTitleHint;
1073 ; // don't modify window flags if the user explicitly set them.
1074 else if (type == Qt::Dialog || type == Qt::Sheet)
1076 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1078 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1080 else if (type == Qt::Tool)
1081 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1083 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint |
1084 Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint;
1088 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1091 if (!qobject_cast<QApplication *>(QCoreApplication::instance()))
1092 qFatal("QWidget: Cannot create a QWidget without QApplication");
1094 Q_ASSERT(allWidgets);
1096 allWidgets->insert(q);
1098 QWidget *desktopWidget = 0;
1099 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1100 desktopWidget = parentWidget;
1106 #ifndef QT_NO_THREAD
1108 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1109 "Widgets must be created in the GUI thread.");
1113 #if defined(Q_WS_X11)
1114 if (desktopWidget) {
1115 // make sure the widget is created on the same screen as the
1116 // programmer specified desktop widget
1117 xinfo = desktopWidget->d_func()->xinfo;
1120 if (desktopWidget) {
1121 const int screen = desktopWidget->d_func()->topData()->screenIndex;
1122 if (QWindow *window = q->windowHandle())
1123 window->setScreen(QGuiApplication::screens().value(screen, 0));
1126 data.fstrut_dirty = true;
1129 data.widget_attributes = 0;
1130 data.window_flags = f;
1131 data.window_state = 0;
1132 data.focus_policy = 0;
1133 data.context_menu_policy = Qt::DefaultContextMenu;
1134 data.window_modality = Qt::NonModal;
1136 data.sizehint_forced = 0;
1137 data.is_closing = 0;
1139 data.in_set_window_state = 0;
1140 data.in_destructor = false;
1142 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1143 if (f & Qt::MSWindowsOwnDC)
1144 q->setAttribute(Qt::WA_NativeWindow);
1147 // q->setAttribute(Qt::WA_NativeWindow);
1150 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1151 adjustQuitOnCloseAttribute();
1153 q->setAttribute(Qt::WA_WState_Hidden);
1155 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1156 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1157 focus_next = focus_prev = q;
1159 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1161 else if (parentWidget)
1162 q->setParent(parentWidget, data.window_flags);
1164 adjustFlags(data.window_flags, q);
1165 resolveLayoutDirection();
1166 // opaque system background?
1167 const QBrush &background = q->palette().brush(QPalette::Window);
1168 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1170 data.fnt = QFont(data.fnt, q);
1171 #if defined(Q_WS_X11)
1172 data.fnt.x11SetScreen(xinfo.screen());
1175 q->setAttribute(Qt::WA_PendingMoveEvent);
1176 q->setAttribute(Qt::WA_PendingResizeEvent);
1178 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1179 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1181 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1184 QEvent e(QEvent::Create);
1185 QApplication::sendEvent(q, &e);
1186 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1188 extraPaintEngine = 0;
1191 // If we add a child to the unified toolbar, we have to redirect the painting.
1192 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1193 if (parentWidget->d_func()->unifiedSurface) {
1194 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1195 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1203 void QWidgetPrivate::createRecursively()
1206 q->create(0, true, true);
1207 for (int i = 0; i < children.size(); ++i) {
1208 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1209 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1210 child->d_func()->createRecursively();
1218 Creates a new widget window if \a window is 0, otherwise sets the
1219 widget's window to \a window.
1221 Initializes the window (sets the geometry etc.) if \a
1222 initializeWindow is true. If \a initializeWindow is false, no
1223 initialization is performed. This parameter only makes sense if \a
1224 window is a valid window.
1226 Destroys the old window if \a destroyOldWindow is true. If \a
1227 destroyOldWindow is false, you are responsible for destroying the
1228 window yourself (using platform native code).
1230 The QWidget constructor calls create(0,true,true) to create a
1231 window for this widget.
1234 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1237 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1240 if (d->data.in_destructor)
1243 Qt::WindowType type = windowType();
1244 Qt::WindowFlags &flags = data->window_flags;
1246 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1248 flags |= Qt::Window;
1251 if (QWidget *parent = parentWidget()) {
1252 if (type & Qt::Window) {
1253 if (!parent->testAttribute(Qt::WA_WState_Created))
1254 parent->createWinId();
1255 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1256 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1257 // We're about to create a native child widget that doesn't have a native parent;
1258 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1259 // attribute is set.
1260 d->createWinId(window);
1261 // Nothing more to do.
1262 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1263 Q_ASSERT(internalWinId());
1269 static int paintOnScreenEnv = -1;
1270 if (paintOnScreenEnv == -1)
1271 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1272 if (paintOnScreenEnv == 1)
1273 setAttribute(Qt::WA_PaintOnScreen);
1275 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1276 setAttribute(Qt::WA_NativeWindow);
1279 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1280 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1283 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1284 // Unregister the dropsite (if already registered) before we
1285 // re-create the widget with a native window.
1286 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1287 && d->extra && d->extra->dropTarget) {
1288 d->registerDropSite(false);
1290 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1292 d->updateIsOpaque();
1294 setAttribute(Qt::WA_WState_Created); // set created flag
1295 d->create_sys(window, initializeWindow, destroyOldWindow);
1297 // a real toplevel window needs a backing store
1298 if (isWindow() && windowType() != Qt::Desktop) {
1299 d->topData()->backingStoreTracker.destroy();
1300 if (hasBackingStoreSupport())
1301 d->topData()->backingStoreTracker.create(this);
1306 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1307 setAttribute(Qt::WA_DropSiteRegistered, true);
1310 extern void qt_eval_init_widget(QWidget *w);
1311 qt_eval_init_widget(this);
1314 // need to force the resting of the icon after changing parents
1315 if (testAttribute(Qt::WA_SetWindowIcon))
1316 d->setWindowIcon_sys();
1318 if (isWindow() && !d->topData()->iconText.isEmpty())
1319 d->setWindowIconText_helper(d->topData()->iconText);
1320 if (isWindow() && !d->topData()->caption.isEmpty())
1321 d->setWindowTitle_helper(d->topData()->caption);
1322 if (windowType() != Qt::Desktop) {
1323 d->updateSystemBackground();
1325 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1326 d->setWindowIcon_sys();
1329 // Frame strut update needed in cases where there are native widgets such as QGLWidget,
1330 // as those force native window creation on their ancestors before they are shown.
1331 // If the strut is not updated, any subsequent move of the top level window before show
1332 // will cause window frame to be ignored when positioning the window.
1333 // Note that this only helps on platforms that handle window creation synchronously.
1334 d->updateFrameStrut();
1338 Destroys the widget.
1340 All this widget's children are deleted first. The application
1341 exits if this widget is the main widget.
1347 d->data.in_destructor = true;
1349 #if defined (QT_CHECK_STATE)
1350 if (paintingActive())
1351 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1354 #ifndef QT_NO_GESTURES
1355 foreach (Qt::GestureType type, d->gestureContext.keys())
1356 ungrabGesture(type);
1359 // force acceptDrops false before winId is destroyed.
1360 d->registerDropSite(false);
1362 #ifndef QT_NO_ACTION
1363 // remove all actions from this widget
1364 for (int i = 0; i < d->actions.size(); ++i) {
1365 QActionPrivate *apriv = d->actions.at(i)->d_func();
1366 apriv->widgets.removeAll(this);
1371 #ifndef QT_NO_SHORTCUT
1372 // Remove all shortcuts grabbed by this
1373 // widget, unless application is closing
1374 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1375 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1378 // delete layout while we still are a valid widget
1381 // Remove myself from focus list
1383 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1384 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1386 if (d->focus_next != this) {
1387 d->focus_next->d_func()->focus_prev = d->focus_prev;
1388 d->focus_prev->d_func()->focus_next = d->focus_next;
1389 d->focus_next = d->focus_prev = 0;
1396 // swallow this problem because we are in a destructor
1399 d->setDirtyOpaqueRegion();
1401 if (isWindow() && isVisible() && internalWinId()) {
1403 d->close_helper(QWidgetPrivate::CloseNoEvent);
1405 // if we're out of memory, at least hide the window.
1409 // and if that also doesn't work, then give up
1414 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1415 else if (!internalWinId() && isVisible()) {
1416 qApp->d_func()->sendSyntheticEnterLeave(this);
1419 else if (isVisible()) {
1420 qApp->d_func()->sendSyntheticEnterLeave(this);
1423 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1424 bs->removeDirtyWidget(this);
1425 if (testAttribute(Qt::WA_StaticContents))
1426 bs->removeStaticWidget(this);
1429 delete d->needsFlush;
1432 // The next 20 lines are duplicated from QObject, but required here
1433 // since QWidget deletes is children itself
1434 bool blocked = d->blockSig;
1435 d->blockSig = 0; // unblock signals so we always emit destroyed()
1437 if (d->isSignalConnected(0)) {
1439 emit destroyed(this);
1441 // all the signal/slots connections are still in place - if we don't
1442 // quit now, we will crash pretty soon.
1443 qWarning("Detected an unexpected exception in ~QWidget while emitting destroyed().");
1448 if (d->declarativeData) {
1449 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1450 d->declarativeData = 0; // don't activate again in ~QObject
1453 d->blockSig = blocked;
1456 // QCocoaView holds a pointer back to this widget. Clear it now
1457 // to make sure it's not followed later on. The lifetime of the
1458 // QCocoaView might exceed the lifetime of this widget in cases
1459 // where Cocoa itself holds references to it.
1460 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1461 qt_mac_clearCocoaViewQWidgetPointers(this);
1464 if (!d->children.isEmpty())
1465 d->deleteChildren();
1467 QApplication::removePostedEvents(this);
1470 destroy(); // platform-dependent cleanup
1472 // if this fails we can't do anything about it but at least we are not allowed to throw.
1474 --QWidgetPrivate::instanceCounter;
1476 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1477 QWidgetPrivate::allWidgets->remove(this);
1480 QEvent e(QEvent::Destroy);
1481 QCoreApplication::sendEvent(this, &e);
1482 } QT_CATCH(const std::exception&) {
1483 // if this fails we can't do anything about it but at least we are not allowed to throw.
1487 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1488 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1490 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1493 // the user might create a widget with Qt::Desktop window
1494 // attribute (or create another QDesktopWidget instance), which
1495 // will have the same windowid (the root window id) as the
1496 // qt_desktopWidget. We should not add the second desktop widget
1498 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1499 if (mapper && data.winid && !userDesktopWidget) {
1500 mapper->remove(data.winid);
1503 const WId oldWinId = data.winid;
1506 #if defined(Q_WS_X11)
1507 hd = id; // X11: hd == ident
1509 if (mapper && id && !userDesktopWidget) {
1510 mapper->insert(data.winid, q);
1513 if(oldWinId != id) {
1514 QEvent e(QEvent::WinIdChange);
1515 QCoreApplication::sendEvent(q, &e);
1519 void QWidgetPrivate::createTLExtra()
1523 if (!extra->topextra) {
1524 QTLWExtra* x = extra->topextra = new QTLWExtra;
1526 x->backingStore = 0;
1527 x->sharedPainter = 0;
1528 x->incw = x->inch = 0;
1529 x->basew = x->baseh = 0;
1530 x->frameStrut.setCoords(0, 0, 0, 0);
1531 x->normalGeometry = QRect(0,0,-1,-1);
1534 x->posIncludesFrame = 0;
1535 x->sizeAdjusted = false;
1536 x->inTopLevelResize = false;
1537 x->inRepaint = false;
1540 x->wasMaximized = false;
1543 #ifdef QWIDGET_EXTRA_DEBUG
1544 static int count = 0;
1545 qDebug() << "tlextra" << ++count;
1552 Creates the widget extra data.
1555 void QWidgetPrivate::createExtra()
1557 if (!extra) { // if not exists
1558 extra = new QWExtra;
1559 extra->glContext = 0;
1560 extra->topextra = 0;
1561 #ifndef QT_NO_GRAPHICSVIEW
1562 extra->proxyWidget = 0;
1564 #ifndef QT_NO_CURSOR
1569 extra->maxw = QWIDGETSIZE_MAX;
1570 extra->maxh = QWIDGETSIZE_MAX;
1571 extra->customDpiX = 0;
1572 extra->customDpiY = 0;
1573 extra->explicitMinSize = 0;
1574 extra->explicitMaxSize = 0;
1575 extra->autoFillBackground = 0;
1576 extra->nativeChildrenForced = 0;
1577 extra->inRenderWithPainter = 0;
1580 #ifdef QWIDGET_EXTRA_DEBUG
1581 static int count = 0;
1582 qDebug() << "extra" << ++count;
1590 Deletes the widget extra data.
1593 void QWidgetPrivate::deleteExtra()
1595 if (extra) { // if exists
1596 #ifndef QT_NO_CURSOR
1600 #ifndef QT_NO_STYLE_STYLESHEET
1601 // dereference the stylesheet style
1602 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1605 if (extra->topextra) {
1607 // extra->topextra->backingStore destroyed in QWidgetPrivate::deleteTLSysExtra()
1608 delete extra->topextra->icon;
1609 delete extra->topextra;
1612 // extra->xic destroyed in QWidget::destroy()
1618 Returns true if there are widgets above this which overlap with
1619 \a rect, which is in parent's coordinate system (same as crect).
1622 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1626 const QWidget *w = q;
1631 QWidgetPrivate *pd = w->parentWidget()->d_func();
1633 for (int i = 0; i < pd->children.size(); ++i) {
1634 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1635 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1638 above = (sibling == w);
1642 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1643 const QWExtra *siblingExtra = sibling->d_func()->extra;
1644 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1645 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1651 w = w->parentWidget();
1652 r.translate(pd->data.crect.topLeft());
1657 void QWidgetPrivate::syncBackingStore()
1659 if (paintOnScreen()) {
1662 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1667 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1669 if (paintOnScreen())
1670 repaint_sys(region);
1671 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1672 bs->sync(q_func(), region);
1676 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1680 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1681 return; // nothing we can do
1683 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1684 return; // nothing to do
1686 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1690 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1691 for (int i = 0; i < children.size(); ++i) {
1692 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1693 if (w && !w->isWindow() && !w->testAttribute(attribute))
1694 w->d_func()->setUpdatesEnabled_helper(enable);
1701 Propagate this widget's palette to all children, except style sheet
1702 widgets, and windows that don't enable window propagation (palettes don't
1703 normally propagate to windows).
1705 void QWidgetPrivate::propagatePaletteChange()
1708 // Propagate a new inherited mask to all children.
1709 #ifndef QT_NO_GRAPHICSVIEW
1710 if (!q->parentWidget() && extra && extra->proxyWidget) {
1711 QGraphicsProxyWidget *p = extra->proxyWidget;
1712 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1714 #endif //QT_NO_GRAPHICSVIEW
1715 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1716 inheritedPaletteResolveMask = 0;
1718 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1720 QEvent pc(QEvent::PaletteChange);
1721 QApplication::sendEvent(q, &pc);
1722 for (int i = 0; i < children.size(); ++i) {
1723 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1724 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1725 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1726 QWidgetPrivate *wd = w->d_func();
1727 wd->inheritedPaletteResolveMask = mask;
1728 wd->resolvePalette();
1734 Returns the widget's clipping rectangle.
1736 QRect QWidgetPrivate::clipRect() const
1739 const QWidget * w = q;
1740 if (!w->isVisible())
1742 QRect r = effectiveRectFor(q->rect());
1748 && w->parentWidget()) {
1751 w = w->parentWidget();
1752 r &= QRect(ox, oy, w->width(), w->height());
1758 Returns the widget's clipping region (without siblings).
1760 QRegion QWidgetPrivate::clipRegion() const
1763 if (!q->isVisible())
1765 QRegion r(q->rect());
1766 const QWidget * w = q;
1767 const QWidget *ignoreUpTo;
1773 && w->parentWidget()) {
1777 w = w->parentWidget();
1778 r &= QRegion(ox, oy, w->width(), w->height());
1781 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1783 for ( ; i < w->d_func()->children.size(); ++i) {
1784 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1785 if(sibling->isVisible() && !sibling->isWindow()) {
1786 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1787 sibling->width(), sibling->height());
1788 if (qRectIntersects(siblingRect, q->rect()))
1789 r -= QRegion(siblingRect);
1797 void QWidgetPrivate::setSystemClip(QPaintDevice *paintDevice, const QRegion ®ion)
1799 // Transform the system clip region from device-independent pixels to device pixels
1800 // Qt 5.0.0: This is a Mac-only code path for now, can be made cross-platform once
1801 // it has been tested.
1802 QPaintEngine *paintEngine = paintDevice->paintEngine();
1804 const qreal devicePixelRatio = (paintDevice->physicalDpiX() == 0 || paintDevice->logicalDpiX() == 0) ?
1805 1.0 : (paintDevice->physicalDpiX() / paintDevice->logicalDpiX());
1806 QTransform scaleTransform;
1807 scaleTransform.scale(devicePixelRatio, devicePixelRatio);
1808 paintEngine->d_func()->systemClip = scaleTransform.map(region);
1810 paintEngine->d_func()->systemClip = region;
1814 #ifndef QT_NO_GRAPHICSEFFECT
1815 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1820 if (w->graphicsEffect()) {
1821 QWidgetEffectSourcePrivate *sourced =
1822 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1823 if (!sourced->updateDueToGraphicsEffect)
1824 w->graphicsEffect()->source()->d_func()->invalidateCache();
1826 w = w->parentWidget();
1829 #endif //QT_NO_GRAPHICSEFFECT
1831 void QWidgetPrivate::setDirtyOpaqueRegion()
1835 dirtyOpaqueChildren = true;
1837 #ifndef QT_NO_GRAPHICSEFFECT
1838 invalidateGraphicsEffectsRecursively();
1839 #endif //QT_NO_GRAPHICSEFFECT
1844 QWidget *parent = q->parentWidget();
1848 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1849 QWidgetPrivate *pd = parent->d_func();
1850 if (!pd->dirtyOpaqueChildren)
1851 pd->setDirtyOpaqueRegion();
1854 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1856 if (!dirtyOpaqueChildren)
1857 return opaqueChildren;
1859 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1860 that->opaqueChildren = QRegion();
1862 for (int i = 0; i < children.size(); ++i) {
1863 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1864 if (!child || !child->isVisible() || child->isWindow())
1867 const QPoint offset = child->geometry().topLeft();
1868 QWidgetPrivate *childd = child->d_func();
1869 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1870 if (childd->extra && childd->extra->hasMask)
1871 r &= childd->extra->mask;
1874 r.translate(offset);
1875 that->opaqueChildren += r;
1878 that->opaqueChildren &= q_func()->rect();
1879 that->dirtyOpaqueChildren = false;
1881 return that->opaqueChildren;
1884 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1886 if (children.isEmpty() || clipRect.isEmpty())
1889 const QRegion &r = getOpaqueChildren();
1891 source -= (r & clipRect);
1894 //subtract any relatives that are higher up than me --- this is too expensive !!!
1895 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1896 bool alsoNonOpaque) const
1899 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1900 if (disableSubtractOpaqueSiblings || q->isWindow())
1904 if (q->d_func()->isInUnifiedToolbar)
1908 QRect clipBoundingRect;
1909 bool dirtyClipBoundingRect = true;
1912 bool dirtyParentClip = true;
1914 QPoint parentOffset = data.crect.topLeft();
1916 const QWidget *w = q;
1921 QWidgetPrivate *pd = w->parentWidget()->d_func();
1922 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1923 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1924 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1925 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1926 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1929 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1930 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1933 if (dirtyClipBoundingRect) {
1934 clipBoundingRect = sourceRegion.boundingRect();
1935 dirtyClipBoundingRect = false;
1938 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1941 if (dirtyParentClip) {
1942 parentClip = sourceRegion.translated(parentOffset);
1943 dirtyParentClip = false;
1946 const QPoint siblingPos(sibling->data->crect.topLeft());
1947 const QRect siblingClipRect(sibling->d_func()->clipRect());
1948 QRegion siblingDirty(parentClip);
1949 siblingDirty &= (siblingClipRect.translated(siblingPos));
1950 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1951 && !sibling->d_func()->graphicsEffect;
1953 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1954 if (siblingDirty.isEmpty())
1957 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1959 siblingDirty.translate(-parentOffset);
1960 sourceRegion -= siblingDirty;
1962 sourceRegion -= siblingGeometry.translated(-parentOffset);
1965 if (hasDirtySiblingsAbove)
1966 *hasDirtySiblingsAbove = true;
1967 if (sibling->d_func()->children.isEmpty())
1969 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1970 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1971 sourceRegion -= opaqueSiblingChildren;
1973 if (sourceRegion.isEmpty())
1976 dirtyClipBoundingRect = true;
1977 dirtyParentClip = true;
1980 w = w->parentWidget();
1981 parentOffset += pd->data.crect.topLeft();
1982 dirtyParentClip = true;
1986 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
1990 const QWidget *w = q;
1993 #ifndef QT_NO_GRAPHICSEFFECT
1994 if (graphicsEffect) {
1995 w = q->parentWidget();
1996 offset -= data.crect.topLeft();
1998 #endif //QT_NO_GRAPHICSEFFECT
2001 const QWidgetPrivate *wd = w->d_func();
2002 if (wd->extra && wd->extra->hasMask)
2003 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2006 offset -= wd->data.crect.topLeft();
2007 w = w->parentWidget();
2011 bool QWidgetPrivate::paintOnScreen() const
2013 #if defined(QT_NO_BACKINGSTORE)
2017 if (q->testAttribute(Qt::WA_PaintOnScreen)
2018 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2022 return !qt_enable_backingstore;
2026 void QWidgetPrivate::updateIsOpaque()
2028 // hw: todo: only needed if opacity actually changed
2029 setDirtyOpaqueRegion();
2031 #ifndef QT_NO_GRAPHICSEFFECT
2032 if (graphicsEffect) {
2033 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2037 #endif //QT_NO_GRAPHICSEFFECT
2041 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2047 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2052 const QPalette &pal = q->palette();
2054 if (q->autoFillBackground()) {
2055 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2056 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2062 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2063 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2064 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2072 void QWidgetPrivate::setOpaque(bool opaque)
2074 if (isOpaque != opaque) {
2076 updateIsTranslucent();
2080 void QWidgetPrivate::updateIsTranslucent()
2083 if (QWindow *window = q->windowHandle())
2084 window->setOpacity(isOpaque ? qreal(1.0) : qreal(0.0));
2087 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2091 if (brush.style() == Qt::TexturePattern) {
2093 // Optimize pattern filling on mac by using HITheme directly
2094 // when filling with the standard widget background.
2095 // Defined in qmacstyle_mac.cpp
2096 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2097 qt_mac_fill_background(painter, rgn, brush);
2100 const QRect rect(rgn.boundingRect());
2101 painter->setClipRegion(rgn);
2102 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2106 } else if (brush.gradient()
2107 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2109 painter->setClipRegion(rgn);
2110 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2113 const QVector<QRect> &rects = rgn.rects();
2114 for (int i = 0; i < rects.size(); ++i)
2115 painter->fillRect(rects.at(i), brush);
2119 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2123 #ifndef QT_NO_SCROLLAREA
2124 bool resetBrushOrigin = false;
2125 QPointF oldBrushOrigin;
2126 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2127 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2128 if (scrollArea && scrollArea->viewport() == q) {
2129 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2130 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2131 oldBrushOrigin = painter->brushOrigin();
2132 resetBrushOrigin = true;
2133 painter->setBrushOrigin(-priv->contentsOffset());
2136 #endif // QT_NO_SCROLLAREA
2138 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2140 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2141 const QBrush bg = q->palette().brush(QPalette::Window);
2142 if (!(flags & DontSetCompositionMode)) {
2143 //copy alpha straight in
2144 QPainter::CompositionMode oldMode = painter->compositionMode();
2145 painter->setCompositionMode(QPainter::CompositionMode_Source);
2146 fillRegion(painter, rgn, bg);
2147 painter->setCompositionMode(oldMode);
2149 fillRegion(painter, rgn, bg);
2153 if (q->autoFillBackground())
2154 fillRegion(painter, rgn, autoFillBrush);
2156 if (q->testAttribute(Qt::WA_StyledBackground)) {
2157 painter->setClipRegion(rgn);
2160 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2163 #ifndef QT_NO_SCROLLAREA
2164 if (resetBrushOrigin)
2165 painter->setBrushOrigin(oldBrushOrigin);
2166 #endif // QT_NO_SCROLLAREA
2171 This function is called when a widget is hidden or destroyed.
2172 It resets some application global pointers that should only refer active,
2177 extern QPointer<QWidget> qt_button_down;
2179 extern QWidget *qt_button_down;
2182 void QWidgetPrivate::deactivateWidgetCleanup()
2185 // If this was the active application window, reset it
2186 if (QApplication::activeWindow() == q)
2187 QApplication::setActiveWindow(0);
2188 // If the is the active mouse press widget, reset it
2189 if (q == qt_button_down)
2195 Returns a pointer to the widget with window identifer/handle \a
2198 The window identifier type depends on the underlying window
2199 system, see \c qwindowdefs.h for the actual definition. If there
2200 is no widget with this identifier, 0 is returned.
2203 QWidget *QWidget::find(WId id)
2205 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2211 \fn WId QWidget::internalWinId() const
2213 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2218 \fn WId QWidget::winId() const
2220 Returns the window system identifier of the widget.
2222 Portable in principle, but if you use it you are probably about to
2223 do something non-portable. Be careful.
2225 If a widget is non-native (alien) and winId() is invoked on it, that widget
2226 will be provided a native handle.
2228 On Mac OS X, the type returned depends on which framework Qt was linked
2229 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2230 is using Cocoa, {WId} is a pointer to an NSView.
2232 This value may change at run-time. An event with type QEvent::WinIdChange
2233 will be sent to the widget following a change in window system identifier.
2237 WId QWidget::winId() const
2239 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2241 qDebug() << "QWidget::winId: creating native window for" << this;
2243 QWidget *that = const_cast<QWidget*>(this);
2244 that->setAttribute(Qt::WA_NativeWindow);
2245 that->d_func()->createWinId();
2246 return that->data->winid;
2252 void QWidgetPrivate::createWinId(WId winid)
2257 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2259 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2260 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2261 if (!q->isWindow()) {
2262 QWidget *parent = q->parentWidget();
2263 QWidgetPrivate *pd = parent->d_func();
2264 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2265 parent->setAttribute(Qt::WA_NativeWindow);
2266 if (!parent->internalWinId()) {
2270 for (int i = 0; i < pd->children.size(); ++i) {
2271 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2272 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2273 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2278 // if the window has already been created, we
2279 // need to raise it to its proper stacking position
2294 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2298 void QWidget::createWinId()
2302 qDebug() << "QWidget::createWinId" << this;
2304 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2311 Returns the effective window system identifier of the widget, i.e. the
2312 native parent's window system identifier.
2314 If the widget is native, this function returns the native widget ID.
2315 Otherwise, the window ID of the first native parent widget, i.e., the
2316 top-level widget that contains this widget, is returned.
2318 \note We recommend that you do not store this value as it is likely to
2321 \sa nativeParentWidget()
2323 WId QWidget::effectiveWinId() const
2325 const WId id = internalWinId();
2326 if (id || !testAttribute(Qt::WA_WState_Created))
2328 if (const QWidget *realParent = nativeParentWidget())
2329 return realParent->internalWinId();
2333 #ifndef QT_NO_STYLE_STYLESHEET
2336 \property QWidget::styleSheet
2337 \brief the widget's style sheet
2340 The style sheet contains a textual description of customizations to the
2341 widget's style, as described in the \l{Qt Style Sheets} document.
2343 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2345 \warning Qt style sheets are currently not supported for custom QStyle
2346 subclasses. We plan to address this in some future release.
2348 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2350 QString QWidget::styleSheet() const
2355 return d->extra->styleSheet;
2358 void QWidget::setStyleSheet(const QString& styleSheet)
2363 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2364 d->extra->styleSheet = styleSheet;
2365 if (styleSheet.isEmpty()) { // stylesheet removed
2373 if (proxy) { // style sheet update
2374 proxy->repolish(this);
2378 if (testAttribute(Qt::WA_SetStyle)) {
2379 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2381 d->setStyle_helper(new QStyleSheetStyle(0), true);
2385 #endif // QT_NO_STYLE_STYLESHEET
2388 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2391 QStyle *QWidget::style() const
2395 if (d->extra && d->extra->style)
2396 return d->extra->style;
2397 return QApplication::style();
2401 Sets the widget's GUI style to \a style. The ownership of the style
2402 object is not transferred.
2404 If no style is set, the widget uses the application's style,
2405 QApplication::style() instead.
2407 Setting a widget's style has no effect on existing or future child
2410 \warning This function is particularly useful for demonstration
2411 purposes, where you want to show Qt's styling capabilities. Real
2412 applications should avoid it and use one consistent GUI style
2415 \warning Qt style sheets are currently not supported for custom QStyle
2416 subclasses. We plan to address this in some future release.
2418 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2421 void QWidget::setStyle(QStyle *style)
2424 setAttribute(Qt::WA_SetStyle, style != 0);
2426 #ifndef QT_NO_STYLE_STYLESHEET
2427 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2428 //if for some reason someone try to set a QStyleSheetStyle, ref it
2429 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2431 d->setStyle_helper(style, false);
2432 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2433 // if we have an application stylesheet or have a proxy already, propagate
2434 d->setStyle_helper(new QStyleSheetStyle(style), true);
2437 d->setStyle_helper(style, false);
2440 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2447 QStyle *oldStyle = q->style();
2448 #ifndef QT_NO_STYLE_STYLESHEET
2449 QPointer<QStyle> origStyle;
2453 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2454 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2455 // set when changing that attribute and passes the widget's CURRENT style.
2456 // therefore no need to do a reassignment.
2462 #ifndef QT_NO_STYLE_STYLESHEET
2463 origStyle = extra->style.data();
2465 extra->style = newStyle;
2469 if (q->windowType() != Qt::Desktop) {
2471 oldStyle->unpolish(q);
2474 macUpdateMetalAttribute();
2476 q->style()->polish(q);
2478 } else if (metalHack) {
2479 macUpdateMetalAttribute();
2485 // We copy the list because the order may be modified
2486 const QObjectList childrenList = children;
2487 for (int i = 0; i < childrenList.size(); ++i) {
2488 QWidget *c = qobject_cast<QWidget*>(childrenList.at(i));
2490 c->d_func()->inheritStyle();
2494 #ifndef QT_NO_STYLE_STYLESHEET
2495 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2496 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2497 cssStyle->clearWidgetFont(q);
2502 QEvent e(QEvent::StyleChange);
2503 QApplication::sendEvent(q, &e);
2505 #ifndef QT_NO_STYLE_STYLESHEET
2506 // dereference the old stylesheet style
2507 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2512 // Inherits style from the current parent and propagates it as necessary
2513 void QWidgetPrivate::inheritStyle()
2515 #ifndef QT_NO_STYLE_STYLESHEET
2518 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2520 if (!q->styleSheet().isEmpty()) {
2526 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2527 QWidget *parent = q->parentWidget();
2528 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2529 // If we have stylesheet on app or parent has stylesheet style, we need
2530 // to be running a proxy
2531 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2532 QStyle *newStyle = parentStyle;
2533 if (q->testAttribute(Qt::WA_SetStyle))
2534 newStyle = new QStyleSheetStyle(origStyle);
2535 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2538 setStyle_helper(newStyle, true);
2542 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2543 // we just need our original style back
2544 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2547 // We could have inherited the proxy from our parent (which has a custom style)
2548 // In such a case we need to start following the application style (i.e revert
2549 // the propagation behavior of QStyleSheetStyle)
2550 if (!q->testAttribute(Qt::WA_SetStyle))
2553 setStyle_helper(origStyle, true);
2554 #endif // QT_NO_STYLE_STYLESHEET
2559 \fn bool QWidget::isWindow() const
2561 Returns true if the widget is an independent window, otherwise
2564 A window is a widget that isn't visually the child of any other
2565 widget and that usually has a frame and a
2566 \l{QWidget::setWindowTitle()}{window title}.
2568 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2569 It will then be grouped with its parent and deleted when the
2570 parent is deleted, minimized when the parent is minimized etc. If
2571 supported by the window manager, it will also have a common
2572 taskbar entry with its parent.
2574 QDialog and QMainWindow widgets are by default windows, even if a
2575 parent widget is specified in the constructor. This behavior is
2576 specified by the Qt::Window flag.
2578 \sa window(), isModal(), parentWidget()
2582 \property QWidget::modal
2583 \brief whether the widget is a modal widget
2585 This property only makes sense for windows. A modal widget
2586 prevents widgets in all other windows from getting any input.
2588 By default, this property is false.
2590 \sa isWindow(), windowModality, QDialog
2594 \property QWidget::windowModality
2595 \brief which windows are blocked by the modal widget
2598 This property only makes sense for windows. A modal widget
2599 prevents widgets in other windows from getting input. The value of
2600 this property controls which windows are blocked when the widget
2601 is visible. Changing this property while the window is visible has
2602 no effect; you must hide() the widget first, then show() it again.
2604 By default, this property is Qt::NonModal.
2606 \sa isWindow(), QWidget::modal, QDialog
2609 Qt::WindowModality QWidget::windowModality() const
2611 return static_cast<Qt::WindowModality>(data->window_modality);
2614 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2616 data->window_modality = windowModality;
2617 // setModal_sys() will be called by setAttribute()
2618 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2619 setAttribute(Qt::WA_SetWindowModality, true);
2623 \fn bool QWidget::underMouse() const
2625 Returns true if the widget is under the mouse cursor; otherwise
2628 This value is not updated properly during drag and drop
2631 \sa enterEvent(), leaveEvent()
2635 \property QWidget::minimized
2636 \brief whether this widget is minimized (iconified)
2638 This property is only relevant for windows.
2640 By default, this property is false.
2642 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2644 bool QWidget::isMinimized() const
2645 { return data->window_state & Qt::WindowMinimized; }
2648 Shows the widget minimized, as an icon.
2650 Calling this function only affects \l{isWindow()}{windows}.
2652 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2655 void QWidget::showMinimized()
2657 bool isMin = isMinimized();
2658 if (isMin && isVisible())
2664 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2669 \property QWidget::maximized
2670 \brief whether this widget is maximized
2672 This property is only relevant for windows.
2674 \note Due to limitations on some window systems, this does not always
2675 report the expected results (e.g., if the user on X11 maximizes the
2676 window via the window manager, Qt has no way of distinguishing this
2677 from any other resize). This is expected to improve as window manager
2680 By default, this property is false.
2682 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2684 bool QWidget::isMaximized() const
2685 { return data->window_state & Qt::WindowMaximized; }
2690 Returns the current window state. The window state is a OR'ed
2691 combination of Qt::WindowState: Qt::WindowMinimized,
2692 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2694 \sa Qt::WindowState, setWindowState()
2696 Qt::WindowStates QWidget::windowState() const
2698 return Qt::WindowStates(data->window_state);
2703 The function sets the window state on child widgets similar to
2704 setWindowState(). The difference is that the window state changed
2705 event has the isOverride() flag set. It exists mainly to keep
2708 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2710 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2711 data->window_state = newstate;
2712 QApplication::sendEvent(this, &e);
2716 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2718 Sets the window state to \a windowState. The window state is a OR'ed
2719 combination of Qt::WindowState: Qt::WindowMinimized,
2720 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2722 If the window is not visible (i.e. isVisible() returns false), the
2723 window state will take effect when show() is called. For visible
2724 windows, the change is immediate. For example, to toggle between
2725 full-screen and normal mode, use the following code:
2727 \snippet code/src_gui_kernel_qwidget.cpp 0
2729 In order to restore and activate a minimized window (while
2730 preserving its maximized and/or full-screen state), use the following:
2732 \snippet code/src_gui_kernel_qwidget.cpp 1
2734 Calling this function will hide the widget. You must call show() to make
2735 the widget visible again.
2737 \note On some window systems Qt::WindowActive is not immediate, and may be
2738 ignored in certain cases.
2740 When the window state changes, the widget receives a changeEvent()
2741 of type QEvent::WindowStateChange.
2743 \sa Qt::WindowState, windowState()
2747 \property QWidget::fullScreen
2748 \brief whether the widget is shown in full screen mode
2750 A widget in full screen mode occupies the whole screen area and does not
2751 display window decorations, such as a title bar.
2753 By default, this property is false.
2755 \sa windowState(), minimized, maximized
2757 bool QWidget::isFullScreen() const
2758 { return data->window_state & Qt::WindowFullScreen; }
2761 Shows the widget in full-screen mode.
2763 Calling this function only affects \l{isWindow()}{windows}.
2765 To return from full-screen mode, call showNormal().
2767 Full-screen mode works fine under Windows, but has certain
2768 problems under X. These problems are due to limitations of the
2769 ICCCM protocol that specifies the communication between X11
2770 clients and the window manager. ICCCM simply does not understand
2771 the concept of non-decorated full-screen windows. Therefore, the
2772 best we can do is to request a borderless window and place and
2773 resize it to fill the entire screen. Depending on the window
2774 manager, this may or may not work. The borderless window is
2775 requested using MOTIF hints, which are at least partially
2776 supported by virtually all modern window managers.
2778 An alternative would be to bypass the window manager entirely and
2779 create a window with the Qt::X11BypassWindowManagerHint flag. This
2780 has other severe problems though, like totally broken keyboard focus
2781 and very strange effects on desktop changes or when the user raises
2784 X11 window managers that follow modern post-ICCCM specifications
2785 support full-screen mode properly.
2787 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2789 void QWidget::showFullScreen()
2792 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2793 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2794 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2795 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2796 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2797 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2802 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2803 | Qt::WindowFullScreen);
2809 Shows the widget maximized.
2811 Calling this function only affects \l{isWindow()}{windows}.
2813 On X11, this function may not work properly with certain window
2814 managers. See the \l{Window Geometry} documentation for an explanation.
2816 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2818 void QWidget::showMaximized()
2822 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2823 | Qt::WindowMaximized);
2825 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2826 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2829 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2830 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2831 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2832 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2840 Restores the widget after it has been maximized or minimized.
2842 Calling this function only affects \l{isWindow()}{windows}.
2844 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2846 void QWidget::showNormal()
2850 setWindowState(windowState() & ~(Qt::WindowMinimized
2851 | Qt::WindowMaximized
2852 | Qt::WindowFullScreen));
2854 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2855 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2858 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2859 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2860 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2861 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2869 Returns true if this widget would become enabled if \a ancestor is
2870 enabled; otherwise returns false.
2874 This is the case if neither the widget itself nor every parent up
2875 to but excluding \a ancestor has been explicitly disabled.
2877 isEnabledTo(0) is equivalent to isEnabled().
2879 \sa setEnabled(), enabled
2882 bool QWidget::isEnabledTo(const QWidget *ancestor) const
2884 const QWidget * w = this;
2885 while (!w->testAttribute(Qt::WA_ForceDisabled)
2887 && w->parentWidget()
2888 && w->parentWidget() != ancestor)
2889 w = w->parentWidget();
2890 return !w->testAttribute(Qt::WA_ForceDisabled);
2893 #ifndef QT_NO_ACTION
2895 Appends the action \a action to this widget's list of actions.
2897 All QWidgets have a list of \l{QAction}s, however they can be
2898 represented graphically in many different ways. The default use of
2899 the QAction list (as returned by actions()) is to create a context
2902 A QWidget should only have one of each action and adding an action
2903 it already has will not cause the same action to be in the widget twice.
2905 The ownership of \a action is not transferred to this QWidget.
2907 \sa removeAction(), insertAction(), actions(), QMenu
2909 void QWidget::addAction(QAction *action)
2911 insertAction(0, action);
2915 Appends the actions \a actions to this widget's list of actions.
2917 \sa removeAction(), QMenu, addAction()
2919 void QWidget::addActions(QList<QAction*> actions)
2921 for(int i = 0; i < actions.count(); i++)
2922 insertAction(0, actions.at(i));
2926 Inserts the action \a action to this widget's list of actions,
2927 before the action \a before. It appends the action if \a before is 0 or
2928 \a before is not a valid action for this widget.
2930 A QWidget should only have one of each action.
2932 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2934 void QWidget::insertAction(QAction *before, QAction *action)
2937 qWarning("QWidget::insertAction: Attempt to insert null action");
2942 if(d->actions.contains(action))
2943 removeAction(action);
2945 int pos = d->actions.indexOf(before);
2948 pos = d->actions.size();
2950 d->actions.insert(pos, action);
2952 QActionPrivate *apriv = action->d_func();
2953 apriv->widgets.append(this);
2955 QActionEvent e(QEvent::ActionAdded, action, before);
2956 QApplication::sendEvent(this, &e);
2960 Inserts the actions \a actions to this widget's list of actions,
2961 before the action \a before. It appends the action if \a before is 0 or
2962 \a before is not a valid action for this widget.
2964 A QWidget can have at most one of each action.
2966 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2968 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2970 for(int i = 0; i < actions.count(); ++i)
2971 insertAction(before, actions.at(i));
2975 Removes the action \a action from this widget's list of actions.
2976 \sa insertAction(), actions(), insertAction()
2978 void QWidget::removeAction(QAction *action)
2985 QActionPrivate *apriv = action->d_func();
2986 apriv->widgets.removeAll(this);
2988 if (d->actions.removeAll(action)) {
2989 QActionEvent e(QEvent::ActionRemoved, action);
2990 QApplication::sendEvent(this, &e);
2995 Returns the (possibly empty) list of this widget's actions.
2997 \sa contextMenuPolicy, insertAction(), removeAction()
2999 QList<QAction*> QWidget::actions() const
3004 #endif // QT_NO_ACTION
3007 \fn bool QWidget::isEnabledToTLW() const
3010 This function is deprecated. It is equivalent to isEnabled()
3014 \property QWidget::enabled
3015 \brief whether the widget is enabled
3017 In general an enabled widget handles keyboard and mouse events; a disabled
3018 widget does not. An exception is made with \l{QAbstractButton}.
3020 Some widgets display themselves differently when they are
3021 disabled. For example a button might draw its label grayed out. If
3022 your widget needs to know when it becomes enabled or disabled, you
3023 can use the changeEvent() with type QEvent::EnabledChange.
3025 Disabling a widget implicitly disables all its children. Enabling
3026 respectively enables all child widgets unless they have been
3027 explicitly disabled.
3029 By default, this property is true.
3031 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3033 void QWidget::setEnabled(bool enable)
3036 setAttribute(Qt::WA_ForceDisabled, !enable);
3037 d->setEnabled_helper(enable);
3040 void QWidgetPrivate::setEnabled_helper(bool enable)
3044 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3045 return; // nothing we can do
3047 if (enable != q->testAttribute(Qt::WA_Disabled))
3048 return; // nothing to do
3050 q->setAttribute(Qt::WA_Disabled, !enable);
3051 updateSystemBackground();
3053 if (!enable && q->window()->focusWidget() == q) {
3054 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3055 if (!parentIsEnabled || !q->focusNextChild())
3059 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3060 for (int i = 0; i < children.size(); ++i) {
3061 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3062 if (w && !w->testAttribute(attribute))
3063 w->d_func()->setEnabled_helper(enable);
3065 #if defined(Q_WS_X11)
3066 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3067 // enforce the windows behavior of clearing the cursor on
3069 qt_x11_enforce_cursor(q);
3072 #ifndef QT_NO_CURSOR
3073 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3074 // enforce the windows behavior of clearing the cursor on
3076 qt_qpa_set_cursor(q, false);
3079 #if defined(Q_WS_MAC)
3080 setEnabled_helper_sys(enable);
3083 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3084 QWidget *focusWidget = effectiveFocusWidget();
3087 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3088 qApp->inputMethod()->update(Qt::ImEnabled);
3090 qApp->inputMethod()->commit();
3091 qApp->inputMethod()->update(Qt::ImEnabled);
3095 QEvent e(QEvent::EnabledChange);
3096 QApplication::sendEvent(q, &e);
3100 \property QWidget::acceptDrops
3101 \brief whether drop events are enabled for this widget
3103 Setting this property to true announces to the system that this
3104 widget \e may be able to accept drop events.
3106 If the widget is the desktop (windowType() == Qt::Desktop), this may
3107 fail if another application is using the desktop; you can call
3108 acceptDrops() to test if this occurs.
3110 \warning Do not modify this property in a drag and drop event handler.
3112 By default, this property is false.
3116 bool QWidget::acceptDrops() const
3118 return testAttribute(Qt::WA_AcceptDrops);
3121 void QWidget::setAcceptDrops(bool on)
3123 setAttribute(Qt::WA_AcceptDrops, on);
3129 Disables widget input events if \a disable is true; otherwise
3130 enables input events.
3132 See the \l enabled documentation for more information.
3134 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3136 void QWidget::setDisabled(bool disable)
3138 setEnabled(!disable);
3142 \property QWidget::frameGeometry
3143 \brief geometry of the widget relative to its parent including any
3146 See the \l{Window Geometry} documentation for an overview of geometry
3147 issues with windows.
3149 By default, this property contains a value that depends on the user's
3150 platform and screen geometry.
3152 \sa geometry(), x(), y(), pos()
3154 QRect QWidget::frameGeometry() const
3157 if (isWindow() && ! (windowType() == Qt::Popup)) {
3158 QRect fs = d->frameStrut();
3159 return QRect(data->crect.x() - fs.left(),
3160 data->crect.y() - fs.top(),
3161 data->crect.width() + fs.left() + fs.right(),
3162 data->crect.height() + fs.top() + fs.bottom());
3168 \property QWidget::x
3170 \brief the x coordinate of the widget relative to its parent including
3173 See the \l{Window Geometry} documentation for an overview of geometry
3174 issues with windows.
3176 By default, this property has a value of 0.
3178 \sa frameGeometry, y, pos
3180 int QWidget::x() const
3183 if (isWindow() && ! (windowType() == Qt::Popup))
3184 return data->crect.x() - d->frameStrut().left();
3185 return data->crect.x();
3189 \property QWidget::y
3190 \brief the y coordinate of the widget relative to its parent and
3191 including any window frame
3193 See the \l{Window Geometry} documentation for an overview of geometry
3194 issues with windows.
3196 By default, this property has a value of 0.
3198 \sa frameGeometry, x, pos
3200 int QWidget::y() const
3203 if (isWindow() && ! (windowType() == Qt::Popup))
3204 return data->crect.y() - d->frameStrut().top();
3205 return data->crect.y();
3209 \property QWidget::pos
3210 \brief the position of the widget within its parent widget
3212 If the widget is a window, the position is that of the widget on
3213 the desktop, including its frame.
3215 When changing the position, the widget, if visible, receives a
3216 move event (moveEvent()) immediately. If the widget is not
3217 currently visible, it is guaranteed to receive an event before it
3220 By default, this property contains a position that refers to the
3223 \warning Calling move() or setGeometry() inside moveEvent() can
3224 lead to infinite recursion.
3226 See the \l{Window Geometry} documentation for an overview of geometry
3227 issues with windows.
3229 \sa frameGeometry, size, x(), y()
3231 QPoint QWidget::pos() const
3234 QPoint result = data->crect.topLeft();
3235 if (isWindow() && ! (windowType() == Qt::Popup))
3236 if (!d->maybeTopData() || !d->maybeTopData()->posIncludesFrame)
3237 result -= d->frameStrut().topLeft();
3242 \property QWidget::geometry
3243 \brief the geometry of the widget relative to its parent and
3244 excluding the window frame
3246 When changing the geometry, the widget, if visible, receives a
3247 move event (moveEvent()) and/or a resize event (resizeEvent())
3248 immediately. If the widget is not currently visible, it is
3249 guaranteed to receive appropriate events before it is shown.
3251 The size component is adjusted if it lies outside the range
3252 defined by minimumSize() and maximumSize().
3254 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3255 can lead to infinite recursion.
3257 See the \l{Window Geometry} documentation for an overview of geometry
3258 issues with windows.
3260 By default, this property contains a value that depends on the user's
3261 platform and screen geometry.
3263 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3264 resizeEvent(), minimumSize(), maximumSize()
3268 \property QWidget::normalGeometry
3270 \brief the geometry of the widget as it will appear when shown as
3271 a normal (not maximized or full screen) top-level widget
3273 For child widgets this property always holds an empty rectangle.
3275 By default, this property contains an empty rectangle.
3277 \sa QWidget::windowState(), QWidget::geometry
3281 \property QWidget::size
3282 \brief the size of the widget excluding any window frame
3284 If the widget is visible when it is being resized, it receives a resize event
3285 (resizeEvent()) immediately. If the widget is not currently
3286 visible, it is guaranteed to receive an event before it is shown.
3288 The size is adjusted if it lies outside the range defined by
3289 minimumSize() and maximumSize().
3291 By default, this property contains a value that depends on the user's
3292 platform and screen geometry.
3294 \warning Calling resize() or setGeometry() inside resizeEvent() can
3295 lead to infinite recursion.
3297 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3298 appear on screen. This also applies to windows.
3300 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3304 \property QWidget::width
3305 \brief the width of the widget excluding any window frame
3307 See the \l{Window Geometry} documentation for an overview of geometry
3308 issues with windows.
3310 \note Do not use this function to find the width of a screen on
3311 a \l{QDesktopWidget}{multiple screen desktop}. Read
3312 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3314 By default, this property contains a value that depends on the user's
3315 platform and screen geometry.
3317 \sa geometry, height, size
3321 \property QWidget::height
3322 \brief the height of the widget excluding any window frame
3324 See the \l{Window Geometry} documentation for an overview of geometry
3325 issues with windows.
3327 \note Do not use this function to find the height of a screen
3328 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3329 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3331 By default, this property contains a value that depends on the user's
3332 platform and screen geometry.
3334 \sa geometry, width, size
3338 \property QWidget::rect
3339 \brief the internal geometry of the widget excluding any window
3342 The rect property equals QRect(0, 0, width(), height()).
3344 See the \l{Window Geometry} documentation for an overview of geometry
3345 issues with windows.
3347 By default, this property contains a value that depends on the user's
3348 platform and screen geometry.
3354 QRect QWidget::normalGeometry() const
3357 if (!d->extra || !d->extra->topextra)
3360 if (!isMaximized() && !isFullScreen())
3363 return d->topData()->normalGeometry;
3368 \property QWidget::childrenRect
3369 \brief the bounding rectangle of the widget's children
3371 Hidden children are excluded.
3373 By default, for a widget with no children, this property contains a
3374 rectangle with zero width and height located at the origin.
3376 \sa childrenRegion(), geometry()
3379 QRect QWidget::childrenRect() const
3382 QRect r(0, 0, 0, 0);
3383 for (int i = 0; i < d->children.size(); ++i) {
3384 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3385 if (w && !w->isWindow() && !w->isHidden())
3392 \property QWidget::childrenRegion
3393 \brief the combined region occupied by the widget's children
3395 Hidden children are excluded.
3397 By default, for a widget with no children, this property contains an
3400 \sa childrenRect(), geometry(), mask()
3403 QRegion QWidget::childrenRegion() const
3407 for (int i = 0; i < d->children.size(); ++i) {
3408 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3409 if (w && !w->isWindow() && !w->isHidden()) {
3410 QRegion mask = w->mask();
3414 r |= mask.translated(w->pos());
3422 \property QWidget::minimumSize
3423 \brief the widget's minimum size
3425 The widget cannot be resized to a smaller size than the minimum
3426 widget size. The widget's size is forced to the minimum size if
3427 the current size is smaller.
3429 The minimum size set by this function will override the minimum size
3430 defined by QLayout. In order to unset the minimum size, use a
3431 value of \c{QSize(0, 0)}.
3433 By default, this property contains a size with zero width and height.
3435 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3438 QSize QWidget::minimumSize() const
3441 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3445 \property QWidget::maximumSize
3446 \brief the widget's maximum size in pixels
3448 The widget cannot be resized to a larger size than the maximum
3451 By default, this property contains a size in which both width and height
3452 have values of 16777215.
3454 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3457 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3460 QSize QWidget::maximumSize() const
3463 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3464 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3469 \property QWidget::minimumWidth
3470 \brief the widget's minimum width in pixels
3472 This property corresponds to the width held by the \l minimumSize property.
3474 By default, this property has a value of 0.
3476 \sa minimumSize, minimumHeight
3480 \property QWidget::minimumHeight
3481 \brief the widget's minimum height in pixels
3483 This property corresponds to the height held by the \l minimumSize property.
3485 By default, this property has a value of 0.
3487 \sa minimumSize, minimumWidth
3491 \property QWidget::maximumWidth
3492 \brief the widget's maximum width in pixels
3494 This property corresponds to the width held by the \l maximumSize property.
3496 By default, this property contains a value of 16777215.
3498 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3501 \sa maximumSize, maximumHeight
3505 \property QWidget::maximumHeight
3506 \brief the widget's maximum height in pixels
3508 This property corresponds to the height held by the \l maximumSize property.
3510 By default, this property contains a value of 16777215.
3512 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3515 \sa maximumSize, maximumWidth
3519 \property QWidget::sizeIncrement
3520 \brief the size increment of the widget
3522 When the user resizes the window, the size will move in steps of
3523 sizeIncrement().width() pixels horizontally and
3524 sizeIncrement.height() pixels vertically, with baseSize() as the
3525 basis. Preferred widget sizes are for non-negative integers \e i
3527 \snippet code/src_gui_kernel_qwidget.cpp 2
3529 Note that while you can set the size increment for all widgets, it
3530 only affects windows.
3532 By default, this property contains a size with zero width and height.
3534 \warning The size increment has no effect under Windows, and may
3535 be disregarded by the window manager on X11.
3537 \sa size, minimumSize, maximumSize
3539 QSize QWidget::sizeIncrement() const
3542 return (d->extra && d->extra->topextra)
3543 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3548 \property QWidget::baseSize
3549 \brief the base size of the widget
3551 The base size is used to calculate a proper widget size if the
3552 widget defines sizeIncrement().
3554 By default, for a newly-created widget, this property contains a size with
3555 zero width and height.
3557 \sa setSizeIncrement()
3560 QSize QWidget::baseSize() const
3563 return (d->extra != 0 && d->extra->topextra != 0)
3564 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3568 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3572 int mw = minw, mh = minh;
3573 if (mw == QWIDGETSIZE_MAX)
3575 if (mh == QWIDGETSIZE_MAX)
3577 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3578 qWarning("QWidget::setMinimumSize: (%s/%s) "
3579 "The largest allowed size is (%d,%d)",
3580 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3582 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3583 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3585 if (minw < 0 || minh < 0) {
3586 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3588 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3589 minw = mw = qMax(minw, 0);
3590 minh = mh = qMax(minh, 0);
3593 if (extra->minw == mw && extra->minh == mh)
3597 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3604 This function corresponds to setMinimumSize(QSize(minw, minh)).
3605 Sets the minimum width to \a minw and the minimum height to \a
3609 void QWidget::setMinimumSize(int minw, int minh)
3612 if (!d->setMinimumSize_helper(minw, minh))
3616 d->setConstraints_sys();
3617 if (minw > width() || minh > height()) {
3618 bool resized = testAttribute(Qt::WA_Resized);
3619 bool maximized = isMaximized();
3620 resize(qMax(minw,width()), qMax(minh,height()));
3621 setAttribute(Qt::WA_Resized, resized); //not a user resize
3623 data->window_state = data->window_state | Qt::WindowMaximized;
3625 #ifndef QT_NO_GRAPHICSVIEW
3627 if (d->extra->proxyWidget)
3628 d->extra->proxyWidget->setMinimumSize(minw, minh);
3631 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3634 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3637 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3638 qWarning("QWidget::setMaximumSize: (%s/%s) "
3639 "The largest allowed size is (%d,%d)",
3640 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3642 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3643 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3645 if (maxw < 0 || maxh < 0) {
3646 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3648 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3649 maxw = qMax(maxw, 0);
3650 maxh = qMax(maxh, 0);
3653 if (extra->maxw == maxw && extra->maxh == maxh)
3657 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3658 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3665 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3666 maxh)). Sets the maximum width to \a maxw and the maximum height
3669 void QWidget::setMaximumSize(int maxw, int maxh)
3672 if (!d->setMaximumSize_helper(maxw, maxh))
3676 d->setConstraints_sys();
3677 if (maxw < width() || maxh < height()) {
3678 bool resized = testAttribute(Qt::WA_Resized);
3679 resize(qMin(maxw,width()), qMin(maxh,height()));
3680 setAttribute(Qt::WA_Resized, resized); //not a user resize
3683 #ifndef QT_NO_GRAPHICSVIEW
3685 if (d->extra->proxyWidget)
3686 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3690 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3696 Sets the x (width) size increment to \a w and the y (height) size
3699 void QWidget::setSizeIncrement(int w, int h)
3703 QTLWExtra* x = d->topData();
3704 if (x->incw == w && x->inch == h)
3709 d->setConstraints_sys();
3715 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3716 the widgets base size to width \a basew and height \a baseh.
3718 void QWidget::setBaseSize(int basew, int baseh)
3722 QTLWExtra* x = d->topData();
3723 if (x->basew == basew && x->baseh == baseh)
3728 d->setConstraints_sys();
3732 Sets both the minimum and maximum sizes of the widget to \a s,
3733 thereby preventing it from ever growing or shrinking.
3735 This will override the default size constraints set by QLayout.
3737 To remove constraints, set the size to QWIDGETSIZE_MAX.
3739 Alternatively, if you want the widget to have a
3740 fixed size based on its contents, you can call
3741 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3743 \sa maximumSize, minimumSize
3746 void QWidget::setFixedSize(const QSize & s)
3748 setFixedSize(s.width(), s.height());
3753 \fn void QWidget::setFixedSize(int w, int h)
3756 Sets the width of the widget to \a w and the height to \a h.
3759 void QWidget::setFixedSize(int w, int h)
3762 bool minSizeSet = d->setMinimumSize_helper(w, h);
3763 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3764 if (!minSizeSet && !maxSizeSet)
3768 d->setConstraints_sys();
3770 d->updateGeometry_helper(true);
3772 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3776 void QWidget::setMinimumWidth(int w)
3780 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3781 setMinimumSize(w, minimumSize().height());
3782 d->extra->explicitMinSize = expl;
3785 void QWidget::setMinimumHeight(int h)
3789 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3790 setMinimumSize(minimumSize().width(), h);
3791 d->extra->explicitMinSize = expl;
3794 void QWidget::setMaximumWidth(int w)
3798 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3799 setMaximumSize(w, maximumSize().height());
3800 d->extra->explicitMaxSize = expl;
3803 void QWidget::setMaximumHeight(int h)
3807 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3808 setMaximumSize(maximumSize().width(), h);
3809 d->extra->explicitMaxSize = expl;
3813 Sets both the minimum and maximum width of the widget to \a w
3814 without changing the heights. Provided for convenience.
3816 \sa sizeHint(), minimumSize(), maximumSize(), setFixedSize()
3819 void QWidget::setFixedWidth(int w)
3823 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3824 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3825 setMinimumSize(w, minimumSize().height());
3826 setMaximumSize(w, maximumSize().height());
3827 d->extra->explicitMinSize = explMin;
3828 d->extra->explicitMaxSize = explMax;
3833 Sets both the minimum and maximum heights of the widget to \a h
3834 without changing the widths. Provided for convenience.
3836 \sa sizeHint(), minimumSize(), maximumSize(), setFixedSize()
3839 void QWidget::setFixedHeight(int h)
3843 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3844 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3845 setMinimumSize(minimumSize().width(), h);
3846 setMaximumSize(maximumSize().width(), h);
3847 d->extra->explicitMinSize = explMin;
3848 d->extra->explicitMaxSize = explMax;
3853 Translates the widget coordinate \a pos to the coordinate system
3854 of \a parent. The \a parent must not be 0 and must be a parent
3855 of the calling widget.
3857 \sa mapFrom(), mapToParent(), mapToGlobal(), underMouse()
3860 QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const
3864 const QWidget * w = this;
3865 while (w != parent) {
3866 Q_ASSERT_X(w, "QWidget::mapTo(const QWidget *parent, const QPoint &pos)",
3867 "parent must be in parent hierarchy");
3868 p = w->mapToParent(p);
3869 w = w->parentWidget();
3877 Translates the widget coordinate \a pos from the coordinate system
3878 of \a parent to this widget's coordinate system. The \a parent
3879 must not be 0 and must be a parent of the calling widget.
3881 \sa mapTo(), mapFromParent(), mapFromGlobal(), underMouse()
3884 QPoint QWidget::mapFrom(const QWidget * parent, const QPoint & pos) const
3888 const QWidget * w = this;
3889 while (w != parent) {
3890 Q_ASSERT_X(w, "QWidget::mapFrom(const QWidget *parent, const QPoint &pos)",
3891 "parent must be in parent hierarchy");
3893 p = w->mapFromParent(p);
3894 w = w->parentWidget();
3902 Translates the widget coordinate \a pos to a coordinate in the
3905 Same as mapToGlobal() if the widget has no parent.
3907 \sa mapFromParent(), mapTo(), mapToGlobal(), underMouse()
3910 QPoint QWidget::mapToParent(const QPoint &pos) const
3912 return pos + data->crect.topLeft();
3916 Translates the parent widget coordinate \a pos to widget
3919 Same as mapFromGlobal() if the widget has no parent.
3921 \sa mapToParent(), mapFrom(), mapFromGlobal(), underMouse()
3924 QPoint QWidget::mapFromParent(const QPoint &pos) const
3926 return pos - data->crect.topLeft();
3931 Returns the window for this widget, i.e. the next ancestor widget
3932 that has (or could have) a window-system frame.
3934 If the widget is a window, the widget itself is returned.
3936 Typical usage is changing the window title:
3938 \snippet code/src_gui_kernel_qwidget.cpp 3
3943 QWidget *QWidget::window() const
3945 QWidget *w = (QWidget *)this;
3946 QWidget *p = w->parentWidget();
3947 while (!w->isWindow() && p) {
3949 p = p->parentWidget();
3957 Returns the native parent for this widget, i.e. the next ancestor widget
3958 that has a system identifier, or 0 if it does not have any native parent.
3960 \sa effectiveWinId()
3962 QWidget *QWidget::nativeParentWidget() const
3964 QWidget *parent = parentWidget();
3965 while (parent && !parent->internalWinId())
3966 parent = parent->parentWidget();
3970 /*! \fn QWidget *QWidget::topLevelWidget() const
3973 Use window() instead.
3979 Returns the background role of the widget.
3981 The background role defines the brush from the widget's \l palette that
3982 is used to render the background.
3984 If no explicit background role is set, the widget inherts its parent
3985 widget's background role.
3987 \sa setBackgroundRole(), foregroundRole()
3989 QPalette::ColorRole QWidget::backgroundRole() const
3992 const QWidget *w = this;
3994 QPalette::ColorRole role = w->d_func()->bg_role;
3995 if (role != QPalette::NoRole)
3997 if (w->isWindow() || w->windowType() == Qt::SubWindow)
3999 w = w->parentWidget();
4001 return QPalette::Window;
4005 Sets the background role of the widget to \a role.
4007 The background role defines the brush from the widget's \l palette that
4008 is used to render the background.
4010 If \a role is QPalette::NoRole, then the widget inherits its
4011 parent's background role.
4013 Note that styles are free to choose any color from the palette.
4014 You can modify the palette or set a style sheet if you don't
4015 achieve the result you want with setBackgroundRole().
4017 \sa backgroundRole(), foregroundRole()
4020 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4024 d->updateSystemBackground();
4025 d->propagatePaletteChange();
4026 d->updateIsOpaque();
4030 Returns the foreground role.
4032 The foreground role defines the color from the widget's \l palette that
4033 is used to draw the foreground.
4035 If no explicit foreground role is set, the function returns a role
4036 that contrasts with the background role.
4038 \sa setForegroundRole(), backgroundRole()
4040 QPalette::ColorRole QWidget::foregroundRole() const
4043 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4044 if (rl != QPalette::NoRole)
4046 QPalette::ColorRole role = QPalette::WindowText;
4047 switch (backgroundRole()) {
4048 case QPalette::Button:
4049 role = QPalette::ButtonText;
4051 case QPalette::Base:
4052 role = QPalette::Text;
4054 case QPalette::Dark:
4055 case QPalette::Shadow:
4056 role = QPalette::Light;
4058 case QPalette::Highlight:
4059 role = QPalette::HighlightedText;
4061 case QPalette::ToolTipBase:
4062 role = QPalette::ToolTipText;
4071 Sets the foreground role of the widget to \a role.
4073 The foreground role defines the color from the widget's \l palette that
4074 is used to draw the foreground.
4076 If \a role is QPalette::NoRole, the widget uses a foreground role
4077 that contrasts with the background role.
4079 Note that styles are free to choose any color from the palette.
4080 You can modify the palette or set a style sheet if you don't
4081 achieve the result you want with setForegroundRole().
4083 \sa foregroundRole(), backgroundRole()
4085 void QWidget::setForegroundRole(QPalette::ColorRole role)
4089 d->updateSystemBackground();
4090 d->propagatePaletteChange();
4094 \property QWidget::palette
4095 \brief the widget's palette
4097 This property describes the widget's palette. The palette is used by the
4098 widget's style when rendering standard components, and is available as a
4099 means to ensure that custom widgets can maintain consistency with the
4100 native platform's look and feel. It's common that different platforms, or
4101 different styles, have different palettes.
4103 When you assign a new palette to a widget, the color roles from this
4104 palette are combined with the widget's default palette to form the
4105 widget's final palette. The palette entry for the widget's background role
4106 is used to fill the widget's background (see QWidget::autoFillBackground),
4107 and the foreground role initializes QPainter's pen.
4109 The default depends on the system environment. QApplication maintains a
4110 system/theme palette which serves as a default for all widgets. There may
4111 also be special palette defaults for certain types of widgets (e.g., on
4112 Windows XP and Vista, all classes that derive from QMenuBar have a special
4113 default palette). You can also define default palettes for widgets
4114 yourself by passing a custom palette and the name of a widget to
4115 QApplication::setPalette(). Finally, the style always has the option of
4116 polishing the palette as it's assigned (see QStyle::polish()).
4118 QWidget propagates explicit palette roles from parent to child. If you
4119 assign a brush or color to a specific role on a palette and assign that
4120 palette to a widget, that role will propagate to all the widget's
4121 children, overriding any system defaults for that role. Note that palettes
4122 by default don't propagate to windows (see isWindow()) unless the
4123 Qt::WA_WindowPropagation attribute is enabled.
4125 QWidget's palette propagation is similar to its font propagation.
4127 The current style, which is used to render the content of all standard Qt
4128 widgets, is free to choose colors and brushes from the widget palette, or
4129 in some cases, to ignore the palette (partially, or completely). In
4130 particular, certain styles like GTK style, Mac style, Windows XP, and
4131 Vista style, depend on third party APIs to render the content of widgets,
4132 and these styles typically do not follow the palette. Because of this,
4133 assigning roles to a widget's palette is not guaranteed to change the
4134 appearance of the widget. Instead, you may choose to apply a \l
4135 styleSheet. You can refer to our Knowledge Base article
4136 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4139 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4140 When using style sheets, the palette of a widget can be customized using
4141 the "color", "background-color", "selection-color",
4142 "selection-background-color" and "alternate-background-color".
4144 \sa QApplication::palette(), QWidget::font()
4146 const QPalette &QWidget::palette() const
4149 data->pal.setCurrentColorGroup(QPalette::Disabled);
4150 } else if ((!isVisible() || isActiveWindow())
4151 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4152 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4155 data->pal.setCurrentColorGroup(QPalette::Active);
4158 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4159 if (qt_mac_can_clickThrough(this))
4160 data->pal.setCurrentColorGroup(QPalette::Active);
4163 data->pal.setCurrentColorGroup(QPalette::Inactive);
4168 void QWidget::setPalette(const QPalette &palette)
4171 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4173 // Determine which palette is inherited from this widget's ancestors and
4174 // QApplication::palette, resolve this against \a palette (attributes from
4175 // the inherited palette are copied over this widget's palette). Then
4176 // propagate this palette to this widget's children.
4177 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4178 QPalette resolvedPalette = palette.resolve(naturalPalette);
4179 d->setPalette_helper(resolvedPalette);
4185 Returns the palette that the widget \a w inherits from its ancestors and
4186 QApplication::palette. \a inheritedMask is the combination of the widget's
4187 ancestors palette request masks (i.e., which attributes from the parent
4188 widget's palette are implicitly imposed on this widget by the user). Note
4189 that this font does not take into account the palette set on \a w itself.
4191 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4194 QPalette naturalPalette = QApplication::palette(q);
4195 if (!q->testAttribute(Qt::WA_StyleSheet)
4196 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4197 #ifndef QT_NO_GRAPHICSVIEW
4198 || (extra && extra->proxyWidget)
4199 #endif //QT_NO_GRAPHICSVIEW
4201 if (QWidget *p = q->parentWidget()) {
4202 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4203 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4204 QPalette inheritedPalette = p->palette();
4205 inheritedPalette.resolve(inheritedMask);
4206 naturalPalette = inheritedPalette.resolve(naturalPalette);
4208 naturalPalette = p->palette();
4212 #ifndef QT_NO_GRAPHICSVIEW
4213 else if (extra && extra->proxyWidget) {
4214 QPalette inheritedPalette = extra->proxyWidget->palette();
4215 inheritedPalette.resolve(inheritedMask);
4216 naturalPalette = inheritedPalette.resolve(naturalPalette);
4218 #endif //QT_NO_GRAPHICSVIEW
4220 naturalPalette.resolve(0);
4221 return naturalPalette;
4226 Determine which palette is inherited from this widget's ancestors and
4227 QApplication::palette, resolve this against this widget's palette
4228 (attributes from the inherited palette are copied over this widget's
4229 palette). Then propagate this palette to this widget's children.
4231 void QWidgetPrivate::resolvePalette()
4233 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4234 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4235 setPalette_helper(resolvedPalette);
4238 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4241 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4244 updateSystemBackground();
4245 propagatePaletteChange();
4252 \property QWidget::font
4253 \brief the font currently set for the widget
4255 This property describes the widget's requested font. The font is used by
4256 the widget's style when rendering standard components, and is available as
4257 a means to ensure that custom widgets can maintain consistency with the
4258 native platform's look and feel. It's common that different platforms, or
4259 different styles, define different fonts for an application.
4261 When you assign a new font to a widget, the properties from this font are
4262 combined with the widget's default font to form the widget's final
4263 font. You can call fontInfo() to get a copy of the widget's final
4264 font. The final font is also used to initialize QPainter's font.
4266 The default depends on the system environment. QApplication maintains a
4267 system/theme font which serves as a default for all widgets. There may
4268 also be special font defaults for certain types of widgets. You can also
4269 define default fonts for widgets yourself by passing a custom font and the
4270 name of a widget to QApplication::setFont(). Finally, the font is matched
4271 against Qt's font database to find the best match.
4273 QWidget propagates explicit font properties from parent to child. If you
4274 change a specific property on a font and assign that font to a widget,
4275 that property will propagate to all the widget's children, overriding any
4276 system defaults for that property. Note that fonts by default don't
4277 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4278 attribute is enabled.
4280 QWidget's font propagation is similar to its palette propagation.
4282 The current style, which is used to render the content of all standard Qt
4283 widgets, is free to choose to use the widget font, or in some cases, to
4284 ignore it (partially, or completely). In particular, certain styles like
4285 GTK style, Mac style, Windows XP, and Vista style, apply special
4286 modifications to the widget font to match the platform's native look and
4287 feel. Because of this, assigning properties to a widget's font is not
4288 guaranteed to change the appearance of the widget. Instead, you may choose
4289 to apply a \l styleSheet.
4291 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4292 style sheets will take precedence if the settings conflict.
4294 \sa fontInfo(), fontMetrics()
4297 void QWidget::setFont(const QFont &font)
4301 #ifndef QT_NO_STYLE_STYLESHEET
4302 const QStyleSheetStyle* style;
4303 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4304 style->saveWidgetFont(this, font);
4308 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4310 // Determine which font is inherited from this widget's ancestors and
4311 // QApplication::font, resolve this against \a font (attributes from the
4312 // inherited font are copied over). Then propagate this font to this
4313 // widget's children.
4314 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4315 QFont resolvedFont = font.resolve(naturalFont);
4316 d->setFont_helper(resolvedFont);
4322 Returns the font that the widget \a w inherits from its ancestors and
4323 QApplication::font. \a inheritedMask is the combination of the widget's
4324 ancestors font request masks (i.e., which attributes from the parent
4325 widget's font are implicitly imposed on this widget by the user). Note
4326 that this font does not take into account the font set on \a w itself.
4328 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4329 is applied, fonts are not propagated anymore
4331 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4334 QFont naturalFont = QApplication::font(q);
4335 if (!q->testAttribute(Qt::WA_StyleSheet)
4336 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4337 #ifndef QT_NO_GRAPHICSVIEW
4338 || (extra && extra->proxyWidget)
4339 #endif //QT_NO_GRAPHICSVIEW
4341 if (QWidget *p = q->parentWidget()) {
4342 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4343 if (!naturalFont.isCopyOf(QApplication::font())) {
4344 QFont inheritedFont = p->font();
4345 inheritedFont.resolve(inheritedMask);
4346 naturalFont = inheritedFont.resolve(naturalFont);
4348 naturalFont = p->font();
4352 #ifndef QT_NO_GRAPHICSVIEW
4353 else if (extra && extra->proxyWidget) {
4354 QFont inheritedFont = extra->proxyWidget->font();
4355 inheritedFont.resolve(inheritedMask);
4356 naturalFont = inheritedFont.resolve(naturalFont);
4358 #endif //QT_NO_GRAPHICSVIEW
4360 naturalFont.resolve(0);
4367 Determine which font is implicitly imposed on this widget by its ancestors
4368 and QApplication::font, resolve this against its own font (attributes from
4369 the implicit font are copied over). Then propagate this font to this
4372 void QWidgetPrivate::resolveFont()
4374 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4375 QFont resolvedFont = data.fnt.resolve(naturalFont);
4376 setFont_helper(resolvedFont);
4382 Assign \a font to this widget, and propagate it to all children, except
4383 style sheet widgets (handled differently) and windows that don't enable
4384 window propagation. \a implicitMask is the union of all ancestor widgets'
4385 font request masks, and determines which attributes from this widget's
4386 font should propagate.
4388 void QWidgetPrivate::updateFont(const QFont &font)
4391 #ifndef QT_NO_STYLE_STYLESHEET
4392 const QStyleSheetStyle* cssStyle;
4393 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4396 data.fnt = QFont(font, q);
4397 #if defined(Q_WS_X11)
4398 // make sure the font set on this widget is associated with the correct screen
4399 data.fnt.x11SetScreen(xinfo.screen());
4401 // Combine new mask with natural mask and propagate to children.
4402 #ifndef QT_NO_GRAPHICSVIEW
4403 if (!q->parentWidget() && extra && extra->proxyWidget) {
4404 QGraphicsProxyWidget *p = extra->proxyWidget;
4405 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4407 #endif //QT_NO_GRAPHICSVIEW
4408 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4409 inheritedFontResolveMask = 0;
4411 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4413 for (int i = 0; i < children.size(); ++i) {
4414 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4417 #ifndef QT_NO_STYLE_STYLESHEET
4418 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4419 // Style sheets follow a different font propagation scheme.
4421 cssStyle->updateStyleSheetFont(w);
4423 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4424 // Propagate font changes.
4425 QWidgetPrivate *wd = w->d_func();
4426 wd->inheritedFontResolveMask = newMask;
4432 #ifndef QT_NO_STYLE_STYLESHEET
4434 cssStyle->updateStyleSheetFont(q);
4438 QEvent e(QEvent::FontChange);
4439 QApplication::sendEvent(q, &e);
4442 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4446 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4448 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4449 if (!children.isEmpty()) {
4450 for (int i = 0; i < children.size(); ++i) {
4451 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4452 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4453 w->d_func()->setLayoutDirection_helper(direction);
4456 QEvent e(QEvent::LayoutDirectionChange);
4457 QApplication::sendEvent(q, &e);
4460 void QWidgetPrivate::resolveLayoutDirection()
4463 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4464 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4468 \property QWidget::layoutDirection
4470 \brief the layout direction for this widget
4472 By default, this property is set to Qt::LeftToRight.
4474 When the layout direction is set on a widget, it will propagate to
4475 the widget's children, but not to a child that is a window and not
4476 to a child for which setLayoutDirection() has been explicitly
4477 called. Also, child widgets added \e after setLayoutDirection()
4478 has been called for the parent do not inherit the parent's layout
4481 This method no longer affects text layout direction since Qt 4.7.
4483 \sa QApplication::layoutDirection
4485 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4489 if (direction == Qt::LayoutDirectionAuto) {
4490 unsetLayoutDirection();
4494 setAttribute(Qt::WA_SetLayoutDirection);
4495 d->setLayoutDirection_helper(direction);
4498 Qt::LayoutDirection QWidget::layoutDirection() const
4500 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4503 void QWidget::unsetLayoutDirection()
4506 setAttribute(Qt::WA_SetLayoutDirection, false);
4507 d->resolveLayoutDirection();
4511 \fn QFontMetrics QWidget::fontMetrics() const
4513 Returns the font metrics for the widget's current font.
4514 Equivalent to QFontMetrics(widget->font()).
4516 \sa font(), fontInfo(), setFont()
4520 \fn QFontInfo QWidget::fontInfo() const
4522 Returns the font info for the widget's current font.
4523 Equivalent to QFontInto(widget->font()).
4525 \sa font(), fontMetrics(), setFont()
4530 \property QWidget::cursor
4531 \brief the cursor shape for this widget
4533 The mouse cursor will assume this shape when it's over this
4534 widget. See the \l{Qt::CursorShape}{list of predefined cursor objects} for a range of useful shapes.
4536 An editor widget might use an I-beam cursor:
4537 \snippet code/src_gui_kernel_qwidget.cpp 6
4539 If no cursor has been set, or after a call to unsetCursor(), the
4540 parent's cursor is used.
4542 By default, this property contains a cursor with the Qt::ArrowCursor
4545 Some underlying window implementations will reset the cursor if it
4546 leaves a widget even if the mouse is grabbed. If you want to have
4547 a cursor set for all widgets, even when outside the window, consider
4548 QApplication::setOverrideCursor().
4550 \sa QApplication::setOverrideCursor()
4553 #ifndef QT_NO_CURSOR
4554 QCursor QWidget::cursor() const
4557 if (testAttribute(Qt::WA_SetCursor))
4558 return (d->extra && d->extra->curs)
4560 : QCursor(Qt::ArrowCursor);
4561 if (isWindow() || !parentWidget())
4562 return QCursor(Qt::ArrowCursor);
4563 return parentWidget()->cursor();
4566 void QWidget::setCursor(const QCursor &cursor)
4569 // On Mac we must set the cursor even if it is the ArrowCursor.
4570 #if !defined(Q_WS_MAC)
4571 if (cursor.shape() != Qt::ArrowCursor
4572 || (d->extra && d->extra->curs))
4576 QCursor *newCursor = new QCursor(cursor);
4577 delete d->extra->curs;
4578 d->extra->curs = newCursor;
4580 setAttribute(Qt::WA_SetCursor);
4581 d->setCursor_sys(cursor);
4583 QEvent event(QEvent::CursorChange);
4584 QApplication::sendEvent(this, &event);
4587 void QWidget::unsetCursor()
4591 delete d->extra->curs;
4595 setAttribute(Qt::WA_SetCursor, false);
4596 d->unsetCursor_sys();
4598 QEvent event(QEvent::CursorChange);
4599 QApplication::sendEvent(this, &event);
4605 \enum QWidget::RenderFlag
4607 This enum describes how to render the widget when calling QWidget::render().
4609 \value DrawWindowBackground If you enable this option, the widget's background
4610 is rendered into the target even if autoFillBackground is not set. By default,
4611 this option is enabled.
4613 \value DrawChildren If you enable this option, the widget's children
4614 are rendered recursively into the target. By default, this option is enabled.
4616 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4617 is ignored when rendering into the target. By default, this option is disabled.
4625 Renders the \a sourceRegion of this widget into the \a target
4626 using \a renderFlags to determine how to render. Rendering
4627 starts at \a targetOffset in the \a target. For example:
4629 \snippet code/src_gui_kernel_qwidget.cpp 7
4631 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4632 the region, i.e. the entire widget.
4634 Ensure that you call QPainter::end() for the \a target device's
4635 active painter (if any) before rendering. For example:
4637 \snippet code/src_gui_kernel_qwidget.cpp 8
4639 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4640 or QGLWidget::renderPixmap() instead.
4642 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4643 const QRegion &sourceRegion, RenderFlags renderFlags)
4645 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4651 Renders the widget into the \a painter's QPainter::device().
4653 Transformations and settings applied to the \a painter will be used
4656 \note The \a painter must be active. On Mac OS X the widget will be
4657 rendered into a QPixmap and then drawn by the \a painter.
4659 \sa QPainter::device()
4661 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4662 const QRegion &sourceRegion, RenderFlags renderFlags)
4665 qWarning("QWidget::render: Null pointer to painter");
4669 if (!painter->isActive()) {
4670 qWarning("QWidget::render: Cannot render with an inactive painter");
4674 const qreal opacity = painter->opacity();
4675 if (qFuzzyIsNull(opacity))
4676 return; // Fully transparent.
4679 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4680 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4682 if (toBePainted.isEmpty())
4687 d->extra->inRenderWithPainter = true;
4690 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4692 QPaintEngine *engine = painter->paintEngine();
4694 QPaintEnginePrivate *enginePriv = engine->d_func();
4695 Q_ASSERT(enginePriv);
4696 QPaintDevice *target = engine->paintDevice();
4699 // Render via a pixmap when dealing with non-opaque painters or printers.
4700 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4701 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4702 d->extra->inRenderWithPainter = false;
4706 // Set new shared painter.
4707 QPainter *oldPainter = d->sharedPainter();
4708 d->setSharedPainter(painter);
4710 // Save current system clip, viewport and transform,
4711 const QTransform oldTransform = enginePriv->systemTransform;
4712 const QRegion oldSystemClip = enginePriv->systemClip;
4713 const QRegion oldSystemViewport = enginePriv->systemViewport;
4715 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4716 if (painter->hasClipping()) {
4717 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4718 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4720 enginePriv->setSystemViewport(oldSystemClip);
4723 render(target, targetOffset, toBePainted, renderFlags);
4725 // Restore system clip, viewport and transform.
4726 enginePriv->systemClip = oldSystemClip;
4727 enginePriv->setSystemViewport(oldSystemViewport);
4728 enginePriv->setSystemTransform(oldTransform);
4730 // Restore shared painter.
4731 d->setSharedPainter(oldPainter);
4734 d->extra->inRenderWithPainter = false;
4737 static void sendResizeEvents(QWidget *target)
4739 QResizeEvent e(target->size(), QSize());
4740 QApplication::sendEvent(target, &e);
4742 const QObjectList children = target->children();
4743 for (int i = 0; i < children.size(); ++i) {
4744 QWidget *child = static_cast<QWidget*>(children.at(i));
4745 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4746 sendResizeEvents(child);
4753 Renders the widget into a pixmap restricted by the
4754 given \a rectangle. If the widget has any children, then
4755 they are also painted in the appropriate positions.
4757 If a rectangle with an invalid size is specified (the default),
4758 the entire widget is painted.
4760 \sa render(), QPixmap
4763 /* INVOKABLE since used by QPixmap::grabWidget(). */
4764 QPixmap QWidget::grab(const QRect &rectangle)
4767 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4768 sendResizeEvents(this);
4770 const QWidget::RenderFlags renderFlags = QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask;
4772 const bool oldDirtyOpaqueChildren = d->dirtyOpaqueChildren;
4774 if (r.width() < 0 || r.height() < 0) {
4775 // For grabbing widgets that haven't been shown yet,
4776 // we trigger the layouting mechanism to determine the widget's size.
4777 r = d->prepareToRender(QRegion(), renderFlags).boundingRect();
4778 r.setTopLeft(rectangle.topLeft());
4781 if (!r.intersects(rect()))
4784 QPixmap res(r.size());
4786 res.fill(Qt::transparent);
4787 render(&res, QPoint(), QRegion(r), renderFlags);
4789 d->dirtyOpaqueChildren = oldDirtyOpaqueChildren;
4794 \brief The graphicsEffect function returns a pointer to the
4795 widget's graphics effect.
4797 If the widget has no graphics effect, 0 is returned.
4801 \sa setGraphicsEffect()
4803 #ifndef QT_NO_GRAPHICSEFFECT
4804 QGraphicsEffect *QWidget::graphicsEffect() const
4807 return d->graphicsEffect;
4809 #endif //QT_NO_GRAPHICSEFFECT
4813 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4815 Sets \a effect as the widget's effect. If there already is an effect installed
4816 on this widget, QWidget will delete the existing effect before installing
4819 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4820 the effect from the widget and install it on this widget.
4822 QWidget takes ownership of \a effect.
4824 \note This function will apply the effect on itself and all its children.
4828 \sa graphicsEffect()
4830 #ifndef QT_NO_GRAPHICSEFFECT
4831 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4834 if (d->graphicsEffect == effect)
4837 if (d->graphicsEffect) {
4838 d->invalidateBuffer(rect());
4839 delete d->graphicsEffect;
4840 d->graphicsEffect = 0;
4845 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4846 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4847 d->graphicsEffect = effect;
4848 effect->d_func()->setGraphicsEffectSource(source);
4852 d->updateIsOpaque();
4854 #endif //QT_NO_GRAPHICSEFFECT
4856 bool QWidgetPrivate::isAboutToShow() const
4865 // The widget will be shown if any of its ancestors are about to show.
4866 QWidget *parent = q->parentWidget();
4867 return parent ? parent->d_func()->isAboutToShow() : false;
4870 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4873 const bool isVisible = q->isVisible();
4875 // Make sure the widget is laid out correctly.
4876 if (!isVisible && !isAboutToShow()) {
4877 QWidget *topLevel = q->window();
4878 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4879 topLevel->ensurePolished();
4881 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4882 // they're not explicitly hidden.
4883 QWidget *widget = q;
4884 QWidgetList hiddenWidgets;
4886 if (widget->isHidden()) {
4887 widget->setAttribute(Qt::WA_WState_Hidden, false);
4888 hiddenWidgets.append(widget);
4889 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4890 widget->d_func()->updateGeometry_helper(true);
4892 widget = widget->parentWidget();
4895 // Activate top-level layout.
4896 if (topLevel->d_func()->layout)
4897 topLevel->d_func()->layout->activate();
4899 // Adjust size if necessary.
4900 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4901 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4902 && !topLevel->testAttribute(Qt::WA_Resized)) {
4903 topLevel->adjustSize();
4904 topLevel->setAttribute(Qt::WA_Resized, false);
4907 // Activate child layouts.
4908 topLevel->d_func()->activateChildLayoutsRecursively();
4910 // We're not cheating with WA_WState_Hidden anymore.
4911 for (int i = 0; i < hiddenWidgets.size(); ++i) {
4912 QWidget *widget = hiddenWidgets.at(i);
4913 widget->setAttribute(Qt::WA_WState_Hidden);
4914 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4915 widget->parentWidget()->d_func()->layout->invalidate();
4917 } else if (isVisible) {
4918 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4921 // Calculate the region to be painted.
4922 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4923 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4924 toBePainted &= extra->mask;
4928 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4929 QWidget::RenderFlags renderFlags)
4932 Q_ASSERT(!toBePainted.isEmpty());
4936 const QTransform originalTransform = painter->worldTransform();
4937 const bool useDeviceCoordinates = originalTransform.isScaling();
4938 if (!useDeviceCoordinates) {
4940 // Render via a pixmap.
4941 const QRect rect = toBePainted.boundingRect();
4942 const QSize size = rect.size();
4946 QPixmap pixmap(size);
4947 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4948 pixmap.fill(Qt::transparent);
4949 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4951 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4952 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4954 painter->drawPixmap(targetOffset, pixmap);
4957 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4961 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4962 QTransform transform = originalTransform;
4963 transform.translate(targetOffset.x(), targetOffset.y());
4965 QPaintDevice *device = painter->device();
4968 // Calculate device rect.
4969 const QRectF rect(toBePainted.boundingRect());
4970 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4971 deviceRect &= QRect(0, 0, device->width(), device->height());
4973 QPixmap pixmap(deviceRect.size());
4974 pixmap.fill(Qt::transparent);
4976 // Create a pixmap device coordinate painter.
4977 QPainter pixmapPainter(&pixmap);
4978 pixmapPainter.setRenderHints(painter->renderHints());
4979 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4980 pixmapPainter.setTransform(transform);
4982 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4983 pixmapPainter.end();
4985 // And then draw the pixmap.
4986 painter->setTransform(QTransform());
4987 painter->drawPixmap(deviceRect.topLeft(), pixmap);
4988 painter->setTransform(originalTransform);
4993 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
4994 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5000 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5001 dirtyOnWidget = QRegion();
5003 // We disable the rendering of QToolBar in the backingStore if
5004 // it's supposed to be in the unified toolbar on Mac OS X.
5005 if (backingStore && isInUnifiedToolbar)
5011 #ifndef QT_NO_GRAPHICSEFFECT
5012 if (graphicsEffect && graphicsEffect->isEnabled()) {
5013 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5014 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5016 if (!sourced->context) {
5017 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5018 sourced->context = &context;
5019 if (!sharedPainter) {
5020 setSystemClip(pdev, rgn.translated(offset));
5022 p.translate(offset);
5023 context.painter = &p;
5024 graphicsEffect->draw(&p);
5025 setSystemClip(pdev, QRegion());
5027 context.painter = sharedPainter;
5028 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5029 sourced->invalidateCache();
5030 sourced->lastEffectTransform = sharedPainter->worldTransform();
5032 sharedPainter->save();
5033 sharedPainter->translate(offset);
5034 graphicsEffect->draw(sharedPainter);
5035 sharedPainter->restore();
5037 sourced->context = 0;
5041 #endif //QT_NO_GRAFFICSEFFECT
5043 const bool asRoot = flags & DrawAsRoot;
5044 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5045 const bool recursive = flags & DrawRecursive;
5046 const bool alsoInvisible = flags & DrawInvisible;
5048 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5050 QRegion toBePainted(rgn);
5051 if (asRoot && !alsoInvisible)
5052 toBePainted &= clipRect(); //(rgn & visibleRegion());
5053 if (!(flags & DontSubtractOpaqueChildren))
5054 subtractOpaqueChildren(toBePainted, q->rect());
5056 if (!toBePainted.isEmpty()) {
5057 bool onScreen = paintOnScreen();
5058 if (!onScreen || alsoOnScreen) {
5059 //update the "in paint event" flag
5060 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5061 qWarning("QWidget::repaint: Recursive repaint detected");
5062 q->setAttribute(Qt::WA_WState_InPaintEvent);
5064 //clip away the new area
5065 #ifndef QT_NO_PAINT_DEBUG
5066 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5068 QPaintEngine *paintEngine = pdev->paintEngine();
5070 setRedirected(pdev, -offset);
5073 // (Alien support) Special case for Mac when redirecting: If the paint device
5074 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5075 // outside the paint event is not supported on QWidgets. The attributeis
5076 // restored further down.
5077 if (pdev->devType() == QInternal::Widget)
5078 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5082 setSystemClip(pdev, toBePainted);
5084 paintEngine->d_func()->systemRect = q->data->crect;
5086 //paint the background
5087 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5088 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5090 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5094 setSystemClip(pdev, toBePainted.translated(offset));
5096 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5098 QColor tint = q->palette().window().color();
5099 tint.setAlphaF(qreal(.6));
5100 p.fillRect(toBePainted.boundingRect(), tint);
5105 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5106 qDebug() << "clipping to" << toBePainted << "location == " << offset
5107 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5110 //actually send the paint event
5111 QPaintEvent e(toBePainted);
5112 QCoreApplication::sendSpontaneousEvent(q, &e);
5114 // Native widgets need to be marked dirty on screen so painting will be done in correct context
5115 if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5116 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5121 if (pdev->devType() == QInternal::Widget)
5122 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5124 restoreRedirected();
5126 paintEngine->d_func()->systemRect = QRect();
5128 paintEngine->d_func()->currentClipDevice = 0;
5130 setSystemClip(pdev, QRegion());
5132 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5133 if (q->paintingActive())
5134 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5136 if (paintEngine && paintEngine->autoDestruct()) {
5140 #ifndef QT_NO_PAINT_DEBUG
5142 QWidgetBackingStore::unflushPaint(q, toBePainted);
5144 } else if (q->isWindow()) {
5145 QPaintEngine *engine = pdev->paintEngine();
5148 p.setClipRegion(toBePainted);
5149 const QBrush bg = q->palette().brush(QPalette::Window);
5150 if (bg.style() == Qt::TexturePattern)
5151 p.drawTiledPixmap(q->rect(), bg.texture());
5153 p.fillRect(q->rect(), bg);
5155 if (engine->autoDestruct())
5161 if (recursive && !children.isEmpty()) {
5162 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5163 , sharedPainter, backingStore);
5167 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5168 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5172 qWarning("QWidget::render: null pointer to paint device");
5176 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5177 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5178 ? prepareToRender(sourceRegion, renderFlags)
5180 if (paintRegion.isEmpty())
5184 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5186 // Use the target's shared painter if set (typically set when doing
5187 // "other->render(widget);" in the widget's paintEvent.
5188 if (target->devType() == QInternal::Widget) {
5189 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5190 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5191 QPainter *targetPainter = targetPrivate->sharedPainter();
5192 if (targetPainter && targetPainter->isActive())
5193 setSharedPainter(targetPainter);
5198 // Use the target's redirected device if set and adjust offset and paint
5199 // region accordingly. This is typically the case when people call render
5200 // from the paintEvent.
5201 QPoint offset = targetOffset;
5202 offset -= paintRegion.boundingRect().topLeft();
5203 QPoint redirectionOffset;
5204 QPaintDevice *redirected = 0;
5206 if (target->devType() == QInternal::Widget)
5207 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5209 redirected = QPainter::redirected(target, &redirectionOffset);
5212 target = redirected;
5213 offset -= redirectionOffset;
5216 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5217 if (QPaintEngine *targetEngine = target->paintEngine()) {
5218 const QRegion targetSystemClip = targetEngine->systemClip();
5219 if (!targetSystemClip.isEmpty())
5220 paintRegion &= targetSystemClip.translated(-offset);
5224 // Set backingstore flags.
5225 int flags = DrawPaintOnScreen | DrawInvisible;
5226 if (renderFlags & QWidget::DrawWindowBackground)
5227 flags |= DrawAsRoot;
5229 if (renderFlags & QWidget::DrawChildren)
5230 flags |= DrawRecursive;
5232 flags |= DontSubtractOpaqueChildren;
5234 flags |= DontSetCompositionMode;
5236 if (target->devType() == QInternal::Printer) {
5238 render_helper(&p, targetOffset, paintRegion, renderFlags);
5243 // Render via backingstore.
5244 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5246 // Restore shared painter.
5247 if (oldSharedPainter)
5248 setSharedPainter(oldSharedPainter);
5250 // Render via backingstore (no shared painter).
5251 drawWidget(target, paintRegion, offset, flags, 0);
5255 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5256 const QPoint &offset, int flags
5257 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5261 bool dirtyBoundingRect = true;
5262 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5263 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5266 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5267 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5268 && !(excludeNativeChildren && x->internalWinId())) {
5269 if (dirtyBoundingRect) {
5270 boundingRect = rgn.boundingRect();
5271 dirtyBoundingRect = false;
5274 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5280 } while (index >= 0);
5285 QWidgetPrivate *wd = w->d_func();
5286 const QPoint widgetPos(w->data->crect.topLeft());
5287 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5291 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5292 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5293 , sharedPainter, backingStore);
5296 if (w->updatesEnabled()
5297 #ifndef QT_NO_GRAPHICSVIEW
5298 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5299 #endif //QT_NO_GRAPHICSVIEW
5301 QRegion wRegion(rgn);
5302 wRegion &= wd->effectiveRectFor(w->data->crect);
5303 wRegion.translate(-widgetPos);
5305 wRegion &= wd->extra->mask;
5306 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5310 #ifndef QT_NO_GRAPHICSEFFECT
5311 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5313 if (system != Qt::DeviceCoordinates)
5314 return m_widget->rect();
5317 // Device coordinates without context not yet supported.
5318 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5322 return context->painter->worldTransform().mapRect(m_widget->rect());
5325 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5327 if (!context || context->painter != painter) {
5328 m_widget->render(painter);
5332 // The region saved in the context is neither clipped to the rect
5333 // nor the mask, so we have to clip it here before calling drawWidget.
5334 QRegion toBePainted = context->rgn;
5335 toBePainted &= m_widget->rect();
5336 QWidgetPrivate *wd = qt_widget_private(m_widget);
5337 if (wd->extra && wd->extra->hasMask)
5338 toBePainted &= wd->extra->mask;
5340 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5341 context->sharedPainter, context->backingStore);
5344 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5345 QGraphicsEffect::PixmapPadMode mode) const
5347 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5348 if (!context && deviceCoordinates) {
5349 // Device coordinates without context not yet supported.
5350 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5354 QPoint pixmapOffset;
5355 QRectF sourceRect = m_widget->rect();
5357 if (deviceCoordinates) {
5358 const QTransform &painterTransform = context->painter->worldTransform();
5359 sourceRect = painterTransform.mapRect(sourceRect);
5360 pixmapOffset = painterTransform.map(pixmapOffset);
5365 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5366 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5367 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5368 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5370 effectRect = sourceRect.toAlignedRect();
5373 *offset = effectRect.topLeft();
5375 pixmapOffset -= effectRect.topLeft();
5377 QPixmap pixmap(effectRect.size());
5378 pixmap.fill(Qt::transparent);
5379 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5382 #endif //QT_NO_GRAPHICSEFFECT
5384 #ifndef QT_NO_GRAPHICSVIEW
5388 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5389 widget and its ancestors. The search starts at \a origin (inclusive).
5390 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5393 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5396 QWExtra *extra = origin->d_func()->extra;
5397 if (extra && extra->proxyWidget)
5398 return extra->proxyWidget;
5399 return nearestGraphicsProxyWidget(origin->parentWidget());
5406 \property QWidget::locale
5407 \brief the widget's locale
5410 As long as no special locale has been set, this is either
5411 the parent's locale or (if this widget is a top level widget),
5414 If the widget displays dates or numbers, these should be formatted
5415 using the widget's locale.
5417 \sa QLocale, QLocale::setDefault()
5420 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5423 if (locale == loc && !forceUpdate)
5428 if (!children.isEmpty()) {
5429 for (int i = 0; i < children.size(); ++i) {
5430 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5433 if (w->testAttribute(Qt::WA_SetLocale))
5435 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5437 w->d_func()->setLocale_helper(loc, forceUpdate);
5440 QEvent e(QEvent::LocaleChange);
5441 QApplication::sendEvent(q, &e);
5444 void QWidget::setLocale(const QLocale &locale)
5448 setAttribute(Qt::WA_SetLocale);
5449 d->setLocale_helper(locale);
5452 QLocale QWidget::locale() const
5459 void QWidgetPrivate::resolveLocale()
5463 if (!q->testAttribute(Qt::WA_SetLocale)) {
5464 setLocale_helper(q->isWindow()
5466 : q->parentWidget()->locale());
5470 void QWidget::unsetLocale()
5473 setAttribute(Qt::WA_SetLocale, false);
5477 static QString constructWindowTitleFromFilePath(const QString &filePath)
5479 QFileInfo fi(filePath);
5480 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5482 QString appName = QApplication::applicationName();
5483 if (!appName.isEmpty())
5484 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5490 \property QWidget::windowTitle
5491 \brief the window title (caption)
5493 This property only makes sense for top-level widgets, such as
5494 windows and dialogs. If no caption has been set, the title is based of the
5495 \l windowFilePath. If neither of these is set, then the title is
5498 If you use the \l windowModified mechanism, the window title must
5499 contain a "[*]" placeholder, which indicates where the '*' should
5500 appear. Normally, it should appear right after the file name
5501 (e.g., "document1.txt[*] - Text Editor"). If the \l
5502 windowModified property is false (the default), the placeholder
5505 \sa windowIcon, windowIconText, windowModified, windowFilePath
5507 QString QWidget::windowTitle() const
5510 if (d->extra && d->extra->topextra) {
5511 if (!d->extra->topextra->caption.isEmpty())
5512 return d->extra->topextra->caption;
5513 if (!d->extra->topextra->filePath.isEmpty())
5514 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5520 Returns a modified window title with the [*] place holder
5521 replaced according to the rules described in QWidget::setWindowTitle
5523 This function assumes that "[*]" can be quoted by another
5524 "[*]", so it will replace two place holders by one and
5525 a single last one by either "*" or nothing depending on
5530 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5535 extern QString qt_eval_adapt_window_title(const QString &title);
5536 QString cap = qt_eval_adapt_window_title(title);
5538 QString cap = title;
5544 QLatin1String placeHolder("[*]");
5545 int index = cap.indexOf(placeHolder);
5547 // here the magic begins
5548 while (index != -1) {
5549 index += placeHolder.size();
5551 while (cap.indexOf(placeHolder, index) == index) {
5553 index += placeHolder.size();
5556 if (count%2) { // odd number of [*] -> replace last one
5557 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5558 if (widget->isWindowModified()
5559 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5560 cap.replace(lastIndex, 3, QWidget::tr("*"));
5562 cap.remove(lastIndex, 3);
5565 index = cap.indexOf(placeHolder, index);
5568 cap.replace(QLatin1String("[*][*]"), placeHolder);
5573 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5576 if (q->testAttribute(Qt::WA_WState_Created))
5577 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5580 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5583 if (q->testAttribute(Qt::WA_WState_Created))
5584 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5587 void QWidget::setWindowIconText(const QString &iconText)
5589 if (QWidget::windowIconText() == iconText)
5593 d->topData()->iconText = iconText;
5594 d->setWindowIconText_helper(iconText);
5596 QEvent e(QEvent::IconTextChange);
5597 QApplication::sendEvent(this, &e);
5600 void QWidget::setWindowTitle(const QString &title)
5602 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5606 d->topData()->caption = title;
5607 d->setWindowTitle_helper(title);
5609 QEvent e(QEvent::WindowTitleChange);
5610 QApplication::sendEvent(this, &e);
5615 \property QWidget::windowIcon
5616 \brief the widget's icon
5618 This property only makes sense for windows. If no icon
5619 has been set, windowIcon() returns the application icon
5620 (QApplication::windowIcon()).
5622 \sa windowIconText, windowTitle
5624 QIcon QWidget::windowIcon() const
5626 const QWidget *w = this;
5628 const QWidgetPrivate *d = w->d_func();
5629 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5630 return *d->extra->topextra->icon;
5631 w = w->parentWidget();
5633 return QApplication::windowIcon();
5636 void QWidgetPrivate::setWindowIcon_helper()
5638 QEvent e(QEvent::WindowIconChange);
5639 QApplication::sendEvent(q_func(), &e);
5640 for (int i = 0; i < children.size(); ++i) {
5641 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5642 if (w && !w->isWindow())
5643 QApplication::sendEvent(w, &e);
5647 void QWidget::setWindowIcon(const QIcon &icon)
5651 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5654 if (!d->extra->topextra->icon)
5655 d->extra->topextra->icon = new QIcon();
5656 *d->extra->topextra->icon = icon;
5658 d->setWindowIcon_sys();
5659 d->setWindowIcon_helper();
5664 \property QWidget::windowIconText
5665 \brief the widget's icon text
5667 This property only makes sense for windows. If no icon
5668 text has been set, this functions returns an empty string.
5670 \sa windowIcon, windowTitle
5673 QString QWidget::windowIconText() const
5676 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5680 \property QWidget::windowFilePath
5682 \brief the file path associated with a widget
5684 This property only makes sense for windows. It associates a file path with
5685 a window. If you set the file path, but have not set the window title, Qt
5686 sets the window title to contain a string created using the following
5692 \li The file name of the specified path, obtained using QFileInfo::fileName().
5698 \li The file name of the specified path, obtained using QFileInfo::fileName().
5699 \li An optional \c{*} character, if the \l windowModified property is set.
5700 \li The \c{0x2014} unicode character, padded either side by spaces.
5701 \li The application name, obtained from the application's
5702 \l{QCoreApplication::}{applicationName} property.
5705 If the window title is set at any point, then the window title takes precedence and
5706 will be shown instead of the file path string.
5708 Additionally, on Mac OS X, this has an added benefit that it sets the
5709 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5710 for the window, assuming that the file path exists.
5712 If no file path is set, this property contains an empty string.
5714 By default, this property contains an empty string.
5716 \sa windowTitle, windowIcon
5719 QString QWidget::windowFilePath() const
5722 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5725 void QWidget::setWindowFilePath(const QString &filePath)
5727 if (filePath == windowFilePath())
5733 d->extra->topextra->filePath = filePath;
5734 d->setWindowFilePath_helper(filePath);
5737 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5739 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5741 setWindowTitle_helper(QFileInfo(filePath).fileName());
5745 setWindowTitle_helper(q->windowTitle());
5749 setWindowFilePath_sys(filePath);
5754 Returns the window's role, or an empty string.
5756 \sa windowIcon, windowTitle
5759 QString QWidget::windowRole() const
5762 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5766 Sets the window's role to \a role. This only makes sense for
5769 void QWidget::setWindowRole(const QString &role)
5771 #if defined(Q_WS_X11)
5773 d->topData()->role = role;
5781 \property QWidget::mouseTracking
5782 \brief whether mouse tracking is enabled for the widget
5784 If mouse tracking is disabled (the default), the widget only
5785 receives mouse move events when at least one mouse button is
5786 pressed while the mouse is being moved.
5788 If mouse tracking is enabled, the widget receives mouse move
5789 events even if no buttons are pressed.
5791 \sa mouseMoveEvent()
5796 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5797 function resets this widget to have no focus proxy.
5799 Some widgets can "have focus", but create a child widget, such as
5800 QLineEdit, to actually handle the focus. In this case, the widget
5801 can set the line edit to be its focus proxy.
5803 setFocusProxy() sets the widget which will actually get focus when
5804 "this widget" gets it. If there is a focus proxy, setFocus() and
5805 hasFocus() operate on the focus proxy.
5810 void QWidget::setFocusProxy(QWidget * w)
5813 if (!w && !d->extra)
5816 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5818 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5824 d->extra->focus_proxy = w;
5829 Returns the focus proxy, or 0 if there is no focus proxy.
5834 QWidget * QWidget::focusProxy() const
5837 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5842 \property QWidget::focus
5843 \brief whether this widget (or its focus proxy) has the keyboard
5846 By default, this property is false.
5848 \note Obtaining the value of this property for a widget is effectively equivalent
5849 to checking whether QApplication::focusWidget() refers to the widget.
5851 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5853 bool QWidget::hasFocus() const
5855 const QWidget* w = this;
5856 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5857 w = w->d_func()->extra->focus_proxy;
5858 if (QWidget *window = w->window()) {
5859 #ifndef QT_NO_GRAPHICSVIEW
5860 QWExtra *e = window->d_func()->extra;
5861 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5865 return (QApplication::focusWidget() == w);
5869 Gives the keyboard input focus to this widget (or its focus
5870 proxy) if this widget or one of its parents is the \l{isActiveWindow()}{active window}. The \a reason argument will
5871 be passed into any focus event sent from this function, it is used
5872 to give an explanation of what caused the widget to get focus.
5873 If the window is not active, the widget will be given the focus when
5874 the window becomes active.
5876 First, a focus about to change event is sent to the focus widget (if any) to
5877 tell it that it is about to lose the focus. Then focus is changed, a
5878 focus out event is sent to the previous focus item and a focus in event is sent
5879 to the new item to tell it that it just received the focus.
5880 (Nothing happens if the focus in and focus out widgets are the
5883 \note On embedded platforms, setFocus() will not cause an input panel
5884 to be opened by the input method. If you want this to happen, you
5885 have to send a QEvent::RequestSoftwareInputPanel event to the
5888 setFocus() gives focus to a widget regardless of its focus policy,
5889 but does not clear any keyboard grab (see grabKeyboard()).
5891 Be aware that if the widget is hidden, it will not accept focus
5894 \warning If you call setFocus() in a function which may itself be
5895 called from focusOutEvent() or focusInEvent(), you may get an
5898 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5899 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5900 grabMouse(), {Keyboard Focus in Widgets}, QEvent::RequestSoftwareInputPanel
5903 void QWidget::setFocus(Qt::FocusReason reason)
5909 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5910 f = f->d_func()->extra->focus_proxy;
5912 if (QApplication::focusWidget() == f
5913 #if defined(Q_WS_WIN)
5914 && GetFocus() == f->internalWinId()
5919 #ifndef QT_NO_GRAPHICSVIEW
5920 QWidget *previousProxyFocus = 0;
5921 if (QWExtra *topData = window()->d_func()->extra) {
5922 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5923 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5924 if (previousProxyFocus && previousProxyFocus->focusProxy())
5925 previousProxyFocus = previousProxyFocus->focusProxy();
5926 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5932 #ifndef QT_NO_GRAPHICSVIEW
5933 // Update proxy state
5934 if (QWExtra *topData = window()->d_func()->extra) {
5935 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5936 f->d_func()->updateFocusChild();
5937 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5938 topData->proxyWidget->setFocus(reason);
5939 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5944 if (f->isActiveWindow()) {
5945 QWidget *prev = QApplicationPrivate::focus_widget;
5947 if (reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
5948 && prev->testAttribute(Qt::WA_InputMethodEnabled)) {
5949 qApp->inputMethod()->commit();
5952 if (reason != Qt::NoFocusReason) {
5953 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, reason);
5954 QApplication::sendEvent(prev, &focusAboutToChange);
5958 f->d_func()->updateFocusChild();
5960 QApplicationPrivate::setFocusWidget(f, reason);
5961 #ifndef QT_NO_ACCESSIBILITY
5963 // The negation of the condition in setFocus_sys
5964 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5965 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5968 // menus update the focus manually and this would create bogus events
5969 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5972 QAccessibleEvent event(f, QAccessible::Focus);
5973 QAccessible::updateAccessibility(&event);
5976 #ifndef QT_NO_GRAPHICSVIEW
5977 if (QWExtra *topData = window()->d_func()->extra) {
5978 if (topData->proxyWidget) {
5979 if (previousProxyFocus && previousProxyFocus != f) {
5980 // Send event to self
5981 QFocusEvent event(QEvent::FocusOut, reason);
5982 QPointer<QWidget> that = previousProxyFocus;
5983 QApplication::sendEvent(previousProxyFocus, &event);
5985 QApplication::sendEvent(that->style(), &event);
5988 #ifndef QT_NO_GRAPHICSVIEW
5989 // Update proxy state
5990 if (QWExtra *topData = window()->d_func()->extra)
5991 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
5992 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
5994 // Send event to self
5995 QFocusEvent event(QEvent::FocusIn, reason);
5996 QPointer<QWidget> that = f;
5997 QApplication::sendEvent(f, &event);
5999 QApplication::sendEvent(that->style(), &event);
6005 f->d_func()->updateFocusChild();
6008 if (QTLWExtra *extra = f->window()->d_func()->maybeTopData()) {
6010 emit extra->window->focusObjectChanged(f);
6014 // updates focus_child on parent widgets to point into this widget
6015 void QWidgetPrivate::updateFocusChild()
6020 if (q->isHidden()) {
6021 while (w && w->isHidden()) {
6022 w->d_func()->focus_child = q;
6023 w = w->isWindow() ? 0 : w->parentWidget();
6027 w->d_func()->focus_child = q;
6028 w = w->isWindow() ? 0 : w->parentWidget();
6034 \fn void QWidget::setFocus()
6037 Gives the keyboard input focus to this widget (or its focus
6038 proxy) if this widget or one of its parents is the
6039 \l{isActiveWindow()}{active window}.
6043 Takes keyboard input focus from the widget.
6045 If the widget has active focus, a \l{focusOutEvent()}{focus out event} is sent to this widget to tell it that it has
6048 This widget must enable focus setting in order to get the keyboard
6049 input focus, i.e. it must call setFocusPolicy().
6051 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6052 setFocusPolicy(), QApplication::focusWidget()
6055 void QWidget::clearFocus()
6058 if (testAttribute(Qt::WA_InputMethodEnabled))
6059 qApp->inputMethod()->commit();
6061 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
6062 QApplication::sendEvent(this, &focusAboutToChange);
6067 if (w->d_func()->focus_child == this)
6068 w->d_func()->focus_child = 0;
6069 w = w->parentWidget();
6071 #ifndef QT_NO_GRAPHICSVIEW
6072 QWExtra *topData = d_func()->extra;
6073 if (topData && topData->proxyWidget)
6074 topData->proxyWidget->clearFocus();
6078 // Update proxy state
6079 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6080 #if defined(Q_WS_WIN)
6081 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6086 #ifndef QT_NO_ACCESSIBILITY
6087 QAccessibleEvent event(this, QAccessible::Focus);
6088 QAccessible::updateAccessibility(&event);
6096 \fn bool QWidget::focusNextChild()
6098 Finds a new widget to give the keyboard focus to, as appropriate
6099 for \uicontrol Tab, and returns true if it can find a new widget, or
6102 \sa focusPreviousChild()
6106 \fn bool QWidget::focusPreviousChild()
6108 Finds a new widget to give the keyboard focus to, as appropriate
6109 for \uicontrol Shift+Tab, and returns true if it can find a new widget,
6110 or false if it can't.
6112 \sa focusNextChild()
6116 Finds a new widget to give the keyboard focus to, as appropriate
6117 for Tab and Shift+Tab, and returns true if it can find a new
6118 widget, or false if it can't.
6120 If \a next is true, this function searches forward, if \a next
6121 is false, it searches backward.
6123 Sometimes, you will want to reimplement this function. For
6124 example, a web browser might reimplement it to move its "current
6125 active link" forward or backward, and call
6126 focusNextPrevChild() only when it reaches the last or
6127 first link on the "page".
6129 Child widgets call focusNextPrevChild() on their parent widgets,
6130 but only the window that contains the child widgets decides where
6131 to redirect focus. By reimplementing this function for an object,
6132 you thus gain control of focus traversal for all child widgets.
6134 \sa focusNextChild(), focusPreviousChild()
6137 bool QWidget::focusNextPrevChild(bool next)
6140 QWidget* p = parentWidget();
6141 bool isSubWindow = (windowType() == Qt::SubWindow);
6142 if (!isWindow() && !isSubWindow && p)
6143 return p->focusNextPrevChild(next);
6144 #ifndef QT_NO_GRAPHICSVIEW
6145 if (d->extra && d->extra->proxyWidget)
6146 return d->extra->proxyWidget->focusNextPrevChild(next);
6148 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6149 if (!w) return false;
6151 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6156 Returns the last child of this widget that setFocus had been
6157 called on. For top level widgets this is the widget that will get
6158 focus in case this window gets activated
6160 This is not the same as QApplication::focusWidget(), which returns
6161 the focus widget in the currently active window.
6164 QWidget *QWidget::focusWidget() const
6166 return const_cast<QWidget *>(d_func()->focus_child);
6170 Returns the next widget in this widget's focus chain.
6172 \sa previousInFocusChain()
6174 QWidget *QWidget::nextInFocusChain() const
6176 return const_cast<QWidget *>(d_func()->focus_next);
6180 \brief The previousInFocusChain function returns the previous
6181 widget in this widget's focus chain.
6183 \sa nextInFocusChain()
6187 QWidget *QWidget::previousInFocusChain() const
6189 return const_cast<QWidget *>(d_func()->focus_prev);
6193 \property QWidget::isActiveWindow
6194 \brief whether this widget's window is the active window
6196 The active window is the window that contains the widget that has
6197 keyboard focus (The window may still have focus if it has no
6198 widgets or none of its widgets accepts keyboard focus).
6200 When popup windows are visible, this property is true for both the
6201 active window \e and for the popup.
6203 By default, this property is false.
6205 \sa activateWindow(), QApplication::activeWindow()
6207 bool QWidget::isActiveWindow() const
6209 QWidget *tlw = window();
6210 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6213 #ifndef QT_NO_GRAPHICSVIEW
6214 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6215 if (isVisible() && tlwExtra->proxyWidget)
6216 return tlwExtra->proxyWidget->isActiveWindow();
6220 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6221 if(tlw->windowType() == Qt::Tool &&
6223 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6225 QWidget *w = QApplication::activeWindow();
6226 while(w && tlw->windowType() == Qt::Tool &&
6227 !w->isModal() && w->parentWidget()) {
6228 w = w->parentWidget()->window();
6234 // Check if platform adaptation thinks the window is active. This is necessary for
6235 // example in case of ActiveQt servers that are embedded into another application.
6236 // Those are separate processes that are not part of the parent application Qt window/widget
6237 // hierarchy, so they need to rely on native methods to determine if they are part of the
6239 if (const QWindow *w = tlw->windowHandle()) {
6241 return w->handle()->isActive();
6248 Puts the \a second widget after the \a first widget in the focus order.
6250 Note that since the tab order of the \a second widget is changed, you
6251 should order a chain like this:
6253 \snippet code/src_gui_kernel_qwidget.cpp 9
6257 \snippet code/src_gui_kernel_qwidget.cpp 10
6259 If \a first or \a second has a focus proxy, setTabOrder()
6260 correctly substitutes the proxy.
6262 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus in Widgets}
6264 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6266 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6269 if (first->window() != second->window()) {
6270 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6274 QWidget *fp = first->focusProxy();
6276 // If first is redirected, set first to the last child of first
6277 // that can take keyboard focus so that second is inserted after
6278 // that last child, and the focus order within first is (more
6279 // likely to be) preserved.
6280 QList<QWidget *> l = first->findChildren<QWidget *>();
6281 for (int i = l.size()-1; i >= 0; --i) {
6282 QWidget * next = l.at(i);
6283 if (next->window() == fp->window()) {
6285 if (fp->focusPolicy() != Qt::NoFocus)
6295 if (QWidget *sp = second->focusProxy())
6298 // QWidget *fp = first->d_func()->focus_prev;
6299 QWidget *fn = first->d_func()->focus_next;
6301 if (fn == second || first == second)
6304 QWidget *sp = second->d_func()->focus_prev;
6305 QWidget *sn = second->d_func()->focus_next;
6307 fn->d_func()->focus_prev = second;
6308 first->d_func()->focus_next = second;
6310 second->d_func()->focus_next = fn;
6311 second->d_func()->focus_prev = first;
6313 sp->d_func()->focus_next = sn;
6314 sn->d_func()->focus_prev = sp;
6317 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6318 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6320 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6321 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6326 Moves the relevant subwidgets of this widget from the \a oldtlw's
6327 tab chain to that of the new parent, if there's anything to move and
6330 This function is called from QWidget::reparent() *after* the widget
6331 has been reparented.
6336 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6339 if (oldtlw == q->window())
6340 return; // nothing to do
6343 focus_child->clearFocus();
6345 // separate the focus chain into new (children of myself) and old (the rest)
6346 QWidget *firstOld = 0;
6347 //QWidget *firstNew = q; //invariant
6348 QWidget *o = 0; // last in the old list
6349 QWidget *n = q; // last in the new list
6351 bool prevWasNew = true;
6352 QWidget *w = focus_next;
6354 //Note: for efficiency, we do not maintain the list invariant inside the loop
6355 //we append items to the relevant list, and we optimize by not changing pointers
6356 //when subsequent items are going into the same list.
6358 bool currentIsNew = q->isAncestorOf(w);
6361 //prev was old -- append to new list
6362 n->d_func()->focus_next = w;
6363 w->d_func()->focus_prev = n;
6368 //prev was new -- append to old list, if there is one
6370 o->d_func()->focus_next = w;
6371 w->d_func()->focus_prev = o;
6373 // "create" the old list
6379 w = w->d_func()->focus_next;
6380 prevWasNew = currentIsNew;
6383 //repair the old list:
6385 o->d_func()->focus_next = firstOld;
6386 firstOld->d_func()->focus_prev = o;
6389 if (!q->isWindow()) {
6390 QWidget *topLevel = q->window();
6391 //insert new chain into toplevel's chain
6393 QWidget *prev = topLevel->d_func()->focus_prev;
6395 topLevel->d_func()->focus_prev = n;
6396 prev->d_func()->focus_next = q;
6399 n->d_func()->focus_next = topLevel;
6401 //repair the new list
6402 n->d_func()->focus_next = q;
6410 Measures the shortest distance from a point to a rect.
6412 This function is called from QDesktopwidget::screen(QPoint) to find the
6413 closest screen for a point.
6414 In directional KeypadNavigation, it is called to find the closest
6415 widget to the current focus widget center.
6417 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6421 if (p.x() < r.left())
6422 dx = r.left() - p.x();
6423 else if (p.x() > r.right())
6424 dx = p.x() - r.right();
6425 if (p.y() < r.top())
6426 dy = r.top() - p.y();
6427 else if (p.y() > r.bottom())
6428 dy = p.y() - r.bottom();
6433 \property QWidget::frameSize
6434 \brief the size of the widget including any window frame
6436 By default, this property contains a value that depends on the user's
6437 platform and screen geometry.
6439 QSize QWidget::frameSize() const
6442 if (isWindow() && !(windowType() == Qt::Popup)) {
6443 QRect fs = d->frameStrut();
6444 return QSize(data->crect.width() + fs.left() + fs.right(),
6445 data->crect.height() + fs.top() + fs.bottom());
6447 return data->crect.size();
6450 /*! \fn void QWidget::move(int x, int y)
6454 This corresponds to move(QPoint(\a x, \a y)).
6457 void QWidget::move(const QPoint &p)
6460 setAttribute(Qt::WA_Moved);
6461 if (testAttribute(Qt::WA_WState_Created)) {
6463 d->topData()->posIncludesFrame = false;
6464 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6465 p.y() + geometry().y() - QWidget::y(),
6466 width(), height(), true);
6467 d->setDirtyOpaqueRegion();
6469 // no frame yet: see also QWidgetPrivate::fixPosIncludesFrame(), QWindowPrivate::PositionPolicy.
6471 d->topData()->posIncludesFrame = true;
6472 data->crect.moveTopLeft(p); // no frame yet
6473 setAttribute(Qt::WA_PendingMoveEvent);
6477 /*! \fn void QWidget::resize(int w, int h)
6480 This corresponds to resize(QSize(\a w, \a h)).
6483 void QWidget::resize(const QSize &s)
6486 setAttribute(Qt::WA_Resized);
6487 if (testAttribute(Qt::WA_WState_Created)) {
6488 d->fixPosIncludesFrame();
6489 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6490 d->setDirtyOpaqueRegion();
6492 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6493 setAttribute(Qt::WA_PendingResizeEvent);
6497 void QWidget::setGeometry(const QRect &r)
6500 setAttribute(Qt::WA_Resized);
6501 setAttribute(Qt::WA_Moved);
6503 d->topData()->posIncludesFrame = 0;
6504 if (testAttribute(Qt::WA_WState_Created)) {
6505 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6506 d->setDirtyOpaqueRegion();
6508 data->crect.setTopLeft(r.topLeft());
6509 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6510 setAttribute(Qt::WA_PendingMoveEvent);
6511 setAttribute(Qt::WA_PendingResizeEvent);
6517 Saves the current geometry and state for top-level widgets.
6519 To save the geometry when the window closes, you can
6520 implement a close event like this:
6522 \snippet code/src_gui_kernel_qwidget.cpp 11
6524 See the \l{Window Geometry} documentation for an overview of geometry
6525 issues with windows.
6527 Use QMainWindow::saveState() to save the geometry and the state of
6528 toolbars and dock widgets.
6530 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6532 QByteArray QWidget::saveGeometry() const
6535 // We check if the window was maximized during this invocation. If so, we need to record the
6536 // starting position as 0,0.
6538 QRect newFramePosition = frameGeometry();
6539 QRect newNormalPosition = normalGeometry();
6540 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6541 // Change the starting position
6542 newFramePosition.moveTo(0, 0);
6543 newNormalPosition.moveTo(0, 0);
6547 QDataStream stream(&array, QIODevice::WriteOnly);
6548 stream.setVersion(QDataStream::Qt_4_0);
6549 const quint32 magicNumber = 0x1D9D0CB;
6550 quint16 majorVersion = 1;
6551 quint16 minorVersion = 0;
6552 stream << magicNumber
6557 << newNormalPosition
6562 << qint32(QApplication::desktop()->screenNumber(this))
6563 << quint8(windowState() & Qt::WindowMaximized)
6564 << quint8(windowState() & Qt::WindowFullScreen);
6571 Restores the geometry and state top-level widgets stored in the
6572 byte array \a geometry. Returns true on success; otherwise
6575 If the restored geometry is off-screen, it will be modified to be
6576 inside the available screen geometry.
6578 To restore geometry saved using QSettings, you can use code like
6581 \snippet code/src_gui_kernel_qwidget.cpp 12
6583 See the \l{Window Geometry} documentation for an overview of geometry
6584 issues with windows.
6586 Use QMainWindow::restoreState() to restore the geometry and the
6587 state of toolbars and dock widgets.
6589 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6591 bool QWidget::restoreGeometry(const QByteArray &geometry)
6593 if (geometry.size() < 4)
6595 QDataStream stream(geometry);
6596 stream.setVersion(QDataStream::Qt_4_0);
6598 const quint32 magicNumber = 0x1D9D0CB;
6599 quint32 storedMagicNumber;
6600 stream >> storedMagicNumber;
6601 if (storedMagicNumber != magicNumber)
6604 const quint16 currentMajorVersion = 1;
6605 quint16 majorVersion = 0;
6606 quint16 minorVersion = 0;
6608 stream >> majorVersion >> minorVersion;
6610 if (majorVersion != currentMajorVersion)
6612 // (Allow all minor versions.)
6614 QRect restoredFrameGeometry;
6615 QRect restoredNormalGeometry;
6616 qint32 restoredScreenNumber;
6620 stream >> restoredFrameGeometry
6621 >> restoredNormalGeometry
6622 >> restoredScreenNumber
6626 const int frameHeight = 20;
6627 if (!restoredFrameGeometry.isValid())
6628 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6630 if (!restoredNormalGeometry.isValid())
6631 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6632 if (!restoredNormalGeometry.isValid()) {
6633 // use the widget's adjustedSize if the sizeHint() doesn't help
6634 restoredNormalGeometry.setSize(restoredNormalGeometry
6636 .expandedTo(d_func()->adjustedSize()));
6639 const QDesktopWidget * const desktop = QApplication::desktop();
6640 if (restoredScreenNumber >= desktop->numScreens())
6641 restoredScreenNumber = desktop->primaryScreen();
6643 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6645 // Modify the restored geometry if we are about to restore to coordinates
6646 // that would make the window "lost". This happens if:
6647 // - The restored geometry is completely oustside the available geometry
6648 // - The title bar is outside the available geometry.
6649 // - (Mac only) The window is higher than the available geometry. It must
6650 // be possible to bring the size grip on screen by moving the window.
6652 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6653 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6656 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6657 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6658 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6659 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6661 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6663 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6664 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6665 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6666 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6668 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6670 if (maximized || fullScreen) {
6671 // set geometry before setting the window state to make
6672 // sure the window is maximized to the right screen.
6673 // Skip on windows: the window is restored into a broken
6674 // half-maximized state.
6676 setGeometry(restoredNormalGeometry);
6678 Qt::WindowStates ws = windowState();
6680 ws |= Qt::WindowMaximized;
6682 ws |= Qt::WindowFullScreen;
6684 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6689 offset = d_func()->topData()->fullScreenOffset;
6691 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6692 move(restoredFrameGeometry.topLeft() + offset);
6693 resize(restoredNormalGeometry.size());
6698 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6701 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6705 Sets the margins around the contents of the widget to have the sizes
6706 \a left, \a top, \a right, and \a bottom. The margins are used by
6707 the layout system, and may be used by subclasses to specify the area
6708 to draw in (e.g. excluding the frame).
6710 Changing the margins will trigger a resizeEvent().
6712 \sa contentsRect(), getContentsMargins()
6714 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6717 if (left == d->leftmargin && top == d->topmargin
6718 && right == d->rightmargin && bottom == d->bottommargin)
6720 d->leftmargin = left;
6722 d->rightmargin = right;
6723 d->bottommargin = bottom;
6725 if (QLayout *l=d->layout)
6726 l->update(); //force activate; will do updateGeometry
6732 QResizeEvent e(data->crect.size(), data->crect.size());
6733 QApplication::sendEvent(this, &e);
6735 setAttribute(Qt::WA_PendingResizeEvent, true);
6738 QEvent e(QEvent::ContentsRectChange);
6739 QApplication::sendEvent(this, &e);
6746 \brief The setContentsMargins function sets the margins around the
6749 Sets the margins around the contents of the widget to have the
6750 sizes determined by \a margins. The margins are
6751 used by the layout system, and may be used by subclasses to
6752 specify the area to draw in (e.g. excluding the frame).
6754 Changing the margins will trigger a resizeEvent().
6756 \sa contentsRect(), getContentsMargins()
6758 void QWidget::setContentsMargins(const QMargins &margins)
6760 setContentsMargins(margins.left(), margins.top(),
6761 margins.right(), margins.bottom());
6765 Returns the widget's contents margins for \a left, \a top, \a
6766 right, and \a bottom.
6768 \sa setContentsMargins(), contentsRect()
6770 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6774 *left = d->leftmargin;
6776 *top = d->topmargin;
6778 *right = d->rightmargin;
6780 *bottom = d->bottommargin;
6786 \brief The contentsMargins function returns the widget's contents margins.
6788 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6790 QMargins QWidget::contentsMargins() const
6793 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6798 Returns the area inside the widget's margins.
6800 \sa setContentsMargins(), getContentsMargins()
6802 QRect QWidget::contentsRect() const
6805 return QRect(QPoint(d->leftmargin, d->topmargin),
6806 QPoint(data->crect.width() - 1 - d->rightmargin,
6807 data->crect.height() - 1 - d->bottommargin));
6814 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6816 This signal is emitted when the widget's \l contextMenuPolicy is
6817 Qt::CustomContextMenu, and the user has requested a context menu on
6818 the widget. The position \a pos is the position of the context menu
6819 event that the widget receives. Normally this is in widget
6820 coordinates. The exception to this rule is QAbstractScrollArea and
6821 its subclasses that map the context menu event to coordinates of the
6822 \l{QAbstractScrollArea::viewport()}{viewport()}.
6825 \sa mapToGlobal(), QMenu, contextMenuPolicy
6830 \property QWidget::contextMenuPolicy
6831 \brief how the widget shows a context menu
6833 The default value of this property is Qt::DefaultContextMenu,
6834 which means the contextMenuEvent() handler is called. Other values
6835 are Qt::NoContextMenu, Qt::PreventContextMenu,
6836 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6837 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6840 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6843 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6845 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6848 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6850 data->context_menu_policy = (uint) policy;
6854 \property QWidget::focusPolicy
6855 \brief the way the widget accepts keyboard focus
6857 The policy is Qt::TabFocus if the widget accepts keyboard
6858 focus by tabbing, Qt::ClickFocus if the widget accepts
6859 focus by clicking, Qt::StrongFocus if it accepts both, and
6860 Qt::NoFocus (the default) if it does not accept focus at
6863 You must enable keyboard focus for a widget if it processes
6864 keyboard events. This is normally done from the widget's
6865 constructor. For instance, the QLineEdit constructor calls
6866 setFocusPolicy(Qt::StrongFocus).
6868 If the widget has a focus proxy, then the focus policy will
6869 be propagated to it.
6871 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6875 Qt::FocusPolicy QWidget::focusPolicy() const
6877 return (Qt::FocusPolicy)data->focus_policy;
6880 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6882 data->focus_policy = (uint) policy;
6884 if (d->extra && d->extra->focus_proxy)
6885 d->extra->focus_proxy->setFocusPolicy(policy);
6889 \property QWidget::updatesEnabled
6890 \brief whether updates are enabled
6892 An updates enabled widget receives paint events and has a system
6893 background; a disabled widget does not. This also implies that
6894 calling update() and repaint() has no effect if updates are
6897 By default, this property is true.
6899 setUpdatesEnabled() is normally used to disable updates for a
6900 short period of time, for instance to avoid screen flicker during
6901 large changes. In Qt, widgets normally do not generate screen
6902 flicker, but on X11 the server might erase regions on the screen
6903 when widgets get hidden before they can be replaced by other
6904 widgets. Disabling updates solves this.
6907 \snippet code/src_gui_kernel_qwidget.cpp 13
6909 Disabling a widget implicitly disables all its children. Enabling a widget
6910 enables all child widgets \e except top-level widgets or those that
6911 have been explicitly disabled. Re-enabling updates implicitly calls
6912 update() on the widget.
6916 void QWidget::setUpdatesEnabled(bool enable)
6919 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6920 d->setUpdatesEnabled_helper(enable);
6924 Shows the widget and its child widgets. This function is
6925 equivalent to setVisible(true) in the normal case, and equivalent
6926 to showFullScreen() if the QStyleHints::showIsFullScreen() hint
6929 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6930 showNormal(), isVisible()
6932 void QWidget::show()
6934 if (isWindow() && qApp->styleHints()->showIsFullScreen())
6942 Makes the widget visible in the isVisible() meaning of the word.
6943 It is only called for toplevels or widgets with visible parents.
6945 void QWidgetPrivate::show_recursive()
6948 // polish if necessary
6950 if (!q->testAttribute(Qt::WA_WState_Created))
6951 createRecursively();
6952 q->ensurePolished();
6954 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6955 q->parentWidget()->d_func()->layout->activate();
6956 // activate our layout before we and our children become visible
6963 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6967 disableUpdates = disableUpdates && q->updatesEnabled();
6969 q->setAttribute(Qt::WA_UpdatesDisabled);
6971 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6972 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6973 QApplication::sendEvent(q, &e);
6974 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6977 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6978 QResizeEvent e(data.crect.size(), QSize());
6979 QApplication::sendEvent(q, &e);
6980 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6984 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6989 for (int i = 0; i < children.size(); ++i) {
6990 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6991 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6995 void QWidgetPrivate::activateChildLayoutsRecursively()
6997 sendPendingMoveAndResizeEvents(false, true);
6999 for (int i = 0; i < children.size(); ++i) {
7000 QWidget *child = qobject_cast<QWidget *>(children.at(i));
7001 if (!child || child->isHidden() || child->isWindow())
7004 child->ensurePolished();
7006 // Activate child's layout
7007 QWidgetPrivate *childPrivate = child->d_func();
7008 if (childPrivate->layout)
7009 childPrivate->layout->activate();
7011 // Pretend we're visible.
7012 const bool wasVisible = child->isVisible();
7014 child->setAttribute(Qt::WA_WState_Visible);
7016 // Do the same for all my children.
7017 childPrivate->activateChildLayoutsRecursively();
7019 // We're not cheating anymore.
7021 child->setAttribute(Qt::WA_WState_Visible, false);
7025 void QWidgetPrivate::show_helper()
7028 data.in_show = true; // qws optimization
7029 // make sure we receive pending move and resize events
7030 sendPendingMoveAndResizeEvents();
7032 // become visible before showing all children
7033 q->setAttribute(Qt::WA_WState_Visible);
7035 // finally show all children recursively
7036 showChildren(false);
7040 // popup handling: new popups and tools need to be raised, and
7041 // existing popups must be closed. Also propagate the current
7042 // windows's KeyboardFocusChange status.
7043 if (q->isWindow()) {
7044 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7046 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7047 q->setAttribute(Qt::WA_KeyboardFocusChange);
7049 while (QApplication::activePopupWidget()) {
7050 if (!QApplication::activePopupWidget()->close())
7056 // Automatic embedding of child windows of widgets already embedded into
7057 // QGraphicsProxyWidget when they are shown the first time.
7058 bool isEmbedded = false;
7059 #ifndef QT_NO_GRAPHICSVIEW
7060 if (q->isWindow()) {
7061 isEmbedded = q->graphicsProxyWidget() ? true : false;
7062 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7063 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7064 if (ancestorProxy) {
7066 ancestorProxy->d_func()->embedSubWindow(q);
7071 Q_UNUSED(isEmbedded);
7074 // On Windows, show the popup now so that our own focus handling
7075 // stores the correct old focus widget even if it's stolen in the
7077 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7078 if (!isEmbedded && q->windowType() == Qt::Popup)
7079 qApp->d_func()->openPopup(q);
7082 // send the show event before showing the window
7083 QShowEvent showEvent;
7084 QApplication::sendEvent(q, &showEvent);
7088 if (!isEmbedded && q->windowType() == Qt::Popup)
7089 qApp->d_func()->openPopup(q);
7091 #ifndef QT_NO_ACCESSIBILITY
7092 if (q->windowType() != Qt::ToolTip) { // Tooltips are read aloud twice in MS narrator.
7093 QAccessibleEvent event(q, QAccessible::ObjectShow);
7094 QAccessible::updateAccessibility(&event);
7098 if (QApplicationPrivate::hidden_focus_widget == q) {
7099 QApplicationPrivate::hidden_focus_widget = 0;
7100 q->setFocus(Qt::OtherFocusReason);
7103 // Process events when showing a Qt::SplashScreen widget before the event loop
7104 // is spinnning; otherwise it might not show up on particular platforms.
7105 // This makes QSplashScreen behave the same on all platforms.
7106 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7107 QApplication::processEvents();
7109 data.in_show = false; // reset qws optimization
7113 Hides the widget. This function is equivalent to
7117 \note If you are working with QDialog or its subclasses and you invoke
7118 the show() function after this function, the dialog will be displayed in
7119 its original position.
7121 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7123 void QWidget::hide()
7130 void QWidgetPrivate::hide_helper()
7134 bool isEmbedded = false;
7135 #if !defined QT_NO_GRAPHICSVIEW
7136 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7138 Q_UNUSED(isEmbedded);
7141 if (!isEmbedded && (q->windowType() == Qt::Popup))
7142 qApp->d_func()->closePopup(q);
7144 #if defined(Q_WS_WIN)
7145 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7146 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7147 q->parentWidget()->activateWindow(); // Activate parent
7150 q->setAttribute(Qt::WA_Mapped, false);
7153 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7156 q->setAttribute(Qt::WA_WState_Visible, false);
7160 QHideEvent hideEvent;
7161 QApplication::sendEvent(q, &hideEvent);
7162 hideChildren(false);
7164 // next bit tries to move the focus if the focus widget is now
7167 qApp->d_func()->sendSyntheticEnterLeave(q);
7168 QWidget *fw = QApplication::focusWidget();
7169 while (fw && !fw->isWindow()) {
7171 q->focusNextPrevChild(true);
7174 fw = fw->parentWidget();
7178 if (QWidgetBackingStore *bs = maybeBackingStore())
7179 bs->removeDirtyWidget(q);
7181 #ifndef QT_NO_ACCESSIBILITY
7183 QAccessibleEvent event(q, QAccessible::ObjectHide);
7184 QAccessible::updateAccessibility(&event);
7190 \fn bool QWidget::isHidden() const
7192 Returns true if the widget is hidden, otherwise returns false.
7194 A hidden widget will only become visible when show() is called on
7195 it. It will not be automatically shown when the parent is shown.
7197 To check visibility, use !isVisible() instead (notice the exclamation mark).
7199 isHidden() implies !isVisible(), but a widget can be not visible
7200 and not hidden at the same time. This is the case for widgets that are children of
7201 widgets that are not visible.
7204 Widgets are hidden if:
7206 \li they were created as independent windows,
7207 \li they were created as children of visible widgets,
7208 \li hide() or setVisible(false) was called.
7213 void QWidget::setVisible(bool visible)
7215 if (visible) { // show
7216 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7221 // Designer uses a trick to make grabWidget work without showing
7222 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7223 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7224 parentWidget()->window()->d_func()->createRecursively();
7226 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7227 //but not children of non-visible parents
7228 QWidget *pw = parentWidget();
7229 if (!testAttribute(Qt::WA_WState_Created)
7230 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7234 #if defined(Q_WS_X11)
7235 if (windowType() == Qt::Window)
7236 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7239 bool wasResized = testAttribute(Qt::WA_Resized);
7240 Qt::WindowStates initialWindowState = windowState();
7242 // polish if necessary
7245 // remember that show was called explicitly
7246 setAttribute(Qt::WA_WState_ExplicitShowHide);
7247 // whether we need to inform the parent widget immediately
7248 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7249 // we are no longer hidden
7250 setAttribute(Qt::WA_WState_Hidden, false);
7252 if (needUpdateGeometry)
7253 d->updateGeometry_helper(true);
7255 // activate our layout before we and our children become visible
7257 d->layout->activate();
7260 QWidget *parent = parentWidget();
7261 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7262 parent->d_func()->layout->activate();
7263 if (parent->isWindow())
7265 parent = parent->parentWidget();
7268 parent->d_func()->setDirtyOpaqueRegion();
7271 // adjust size if necessary
7273 && (isWindow() || !parentWidget()->d_func()->layout)) {
7276 if (windowState() != initialWindowState)
7277 setWindowState(initialWindowState);
7281 setAttribute(Qt::WA_Resized, false);
7284 setAttribute(Qt::WA_KeyboardFocusChange, false);
7286 if (isWindow() || parentWidget()->isVisible()) {
7289 qApp->d_func()->sendSyntheticEnterLeave(this);
7292 QEvent showToParentEvent(QEvent::ShowToParent);
7293 QApplication::sendEvent(this, &showToParentEvent);
7295 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7297 #if defined(Q_WS_WIN)
7298 // reset WS_DISABLED style in a Blocked window
7299 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7300 && QApplicationPrivate::isBlockedByModal(this))
7302 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7303 dwStyle &= ~WS_DISABLED;
7304 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7307 if (QApplicationPrivate::hidden_focus_widget == this)
7308 QApplicationPrivate::hidden_focus_widget = 0;
7312 // hw: The test on getOpaqueRegion() needs to be more intelligent
7313 // currently it doesn't work if the widget is hidden (the region will
7314 // be clipped). The real check should be testing the cached region
7315 // (and dirty flag) directly.
7316 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7317 parentWidget()->d_func()->setDirtyOpaqueRegion();
7319 setAttribute(Qt::WA_WState_Hidden);
7320 setAttribute(Qt::WA_WState_ExplicitShowHide);
7321 if (testAttribute(Qt::WA_WState_Created))
7324 // invalidate layout similar to updateGeometry()
7325 if (!isWindow() && parentWidget()) {
7326 if (parentWidget()->d_func()->layout)
7327 parentWidget()->d_func()->layout->invalidate();
7328 else if (parentWidget()->isVisible())
7329 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7332 QEvent hideToParentEvent(QEvent::HideToParent);
7333 QApplication::sendEvent(this, &hideToParentEvent);
7338 Convenience function, equivalent to setVisible(!\a hidden).
7340 void QWidget::setHidden(bool hidden)
7342 setVisible(!hidden);
7345 void QWidgetPrivate::_q_showIfNotHidden()
7348 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7349 q->setVisible(true);
7352 void QWidgetPrivate::showChildren(bool spontaneous)
7354 QList<QObject*> childList = children;
7355 for (int i = 0; i < childList.size(); ++i) {
7356 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7358 || widget->isWindow()
7359 || widget->testAttribute(Qt::WA_WState_Hidden))
7362 widget->setAttribute(Qt::WA_Mapped);
7363 widget->d_func()->showChildren(true);
7365 QApplication::sendSpontaneousEvent(widget, &e);
7367 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7368 widget->d_func()->show_recursive();
7375 void QWidgetPrivate::hideChildren(bool spontaneous)
7377 QList<QObject*> childList = children;
7378 for (int i = 0; i < childList.size(); ++i) {
7379 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7380 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7383 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7384 // When hiding a widget we need to make sure that no mouse_down events are active, because
7385 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7386 // The solution is simple, before going through with this we check if there are any mouse_down events in
7387 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7388 // then we continue.
7389 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7390 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7391 // mouse release event. There are two ways to interpret this:
7392 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7393 // might be waiting for a release event that will never arrive.
7394 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7395 // supposed to trigger because it is not visible.
7396 if(widget == qt_button_down)
7400 widget->setAttribute(Qt::WA_Mapped, false);
7402 widget->setAttribute(Qt::WA_WState_Visible, false);
7403 widget->d_func()->hideChildren(spontaneous);
7406 QApplication::sendSpontaneousEvent(widget, &e);
7408 QApplication::sendEvent(widget, &e);
7409 if (widget->internalWinId()
7410 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7411 // hide_sys() on an ancestor won't have any affect on this
7412 // widget, so it needs an explicit hide_sys() of its own
7413 widget->d_func()->hide_sys();
7416 qApp->d_func()->sendSyntheticEnterLeave(widget);
7417 #ifndef QT_NO_ACCESSIBILITY
7419 QAccessibleEvent event(widget, QAccessible::ObjectHide);
7420 QAccessible::updateAccessibility(&event);
7426 bool QWidgetPrivate::close_helper(CloseMode mode)
7428 if (data.is_closing)
7432 data.is_closing = 1;
7434 QPointer<QWidget> that = q;
7435 QPointer<QWidget> parentWidget = q->parentWidget();
7437 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7438 if (mode != CloseNoEvent) {
7440 if (mode == CloseWithSpontaneousEvent)
7441 QApplication::sendSpontaneousEvent(q, &e);
7443 QApplication::sendEvent(q, &e);
7444 if (!that.isNull() && !e.isAccepted()) {
7445 data.is_closing = 0;
7450 if (!that.isNull() && !q->isHidden())
7453 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7454 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7457 /* if there is no non-withdrawn primary window left (except
7458 the ones without QuitOnClose), we emit the lastWindowClosed
7460 QWidgetList list = QApplication::topLevelWidgets();
7461 bool lastWindowClosed = true;
7462 for (int i = 0; i < list.size(); ++i) {
7463 QWidget *w = list.at(i);
7464 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7466 lastWindowClosed = false;
7469 if (lastWindowClosed) {
7470 QGuiApplicationPrivate::emitLastWindowClosed();
7471 QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7472 applicationPrivate->maybeQuit();
7477 if (!that.isNull()) {
7478 data.is_closing = 0;
7479 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7480 q->setAttribute(Qt::WA_DeleteOnClose, false);
7489 Closes this widget. Returns true if the widget was closed;
7490 otherwise returns false.
7492 First it sends the widget a QCloseEvent. The widget is
7493 \l{hide()}{hidden} if it \l{QCloseEvent::accept()}{accepts}
7494 the close event. If it \l{QCloseEvent::ignore()}{ignores}
7495 the event, nothing happens. The default
7496 implementation of QWidget::closeEvent() accepts the close event.
7498 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7499 is also deleted. A close events is delivered to the widget no
7500 matter if the widget is visible or not.
7502 The \l QApplication::lastWindowClosed() signal is emitted when the
7503 last visible primary window (i.e. window with no parent) with the
7504 Qt::WA_QuitOnClose attribute set is closed. By default this
7505 attribute is set for all widgets except transient windows such as
7506 splash screens, tool windows, and popup menus.
7510 bool QWidget::close()
7512 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7516 \property QWidget::visible
7517 \brief whether the widget is visible
7519 Calling setVisible(true) or show() sets the widget to visible
7520 status if all its parent widgets up to the window are visible. If
7521 an ancestor is not visible, the widget won't become visible until
7522 all its ancestors are shown. If its size or position has changed,
7523 Qt guarantees that a widget gets move and resize events just
7524 before it is shown. If the widget has not been resized yet, Qt
7525 will adjust the widget's size to a useful default using
7528 Calling setVisible(false) or hide() hides a widget explicitly. An
7529 explicitly hidden widget will never become visible, even if all
7530 its ancestors become visible, unless you show it.
7532 A widget receives show and hide events when its visibility status
7533 changes. Between a hide and a show event, there is no need to
7534 waste CPU cycles preparing or displaying information to the user.
7535 A video application, for example, might simply stop generating new
7538 A widget that happens to be obscured by other windows on the
7539 screen is considered to be visible. The same applies to iconified
7540 windows and windows that exist on another virtual
7541 desktop (on platforms that support this concept). A widget
7542 receives spontaneous show and hide events when its mapping status
7543 is changed by the window system, e.g. a spontaneous hide event
7544 when the user minimizes the window, and a spontaneous show event
7545 when the window is restored again.
7547 You almost never have to reimplement the setVisible() function. If
7548 you need to change some settings before a widget is shown, use
7549 showEvent() instead. If you need to do some delayed initialization
7550 use the Polish event delivered to the event() function.
7552 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7553 showEvent(), hideEvent()
7558 Returns true if this widget would become visible if \a ancestor is
7559 shown; otherwise returns false.
7561 The true case occurs if neither the widget itself nor any parent
7562 up to but excluding \a ancestor has been explicitly hidden.
7564 This function will still return true if the widget is obscured by
7565 other windows on the screen, but could be physically visible if it
7566 or they were to be moved.
7568 isVisibleTo(0) is identical to isVisible().
7570 \sa show(), hide(), isVisible()
7573 bool QWidget::isVisibleTo(const QWidget *ancestor) const
7577 const QWidget * w = this;
7578 while (!w->isHidden()
7580 && w->parentWidget()
7581 && w->parentWidget() != ancestor)
7582 w = w->parentWidget();
7583 return !w->isHidden();
7588 Returns the unobscured region where paint events can occur.
7590 For visible widgets, this is an approximation of the area not
7591 covered by other widgets; otherwise, this is an empty region.
7593 The repaint() function calls this function if necessary, so in
7594 general you do not need to call it.
7597 QRegion QWidget::visibleRegion() const
7601 QRect clipRect = d->clipRect();
7602 if (clipRect.isEmpty())
7604 QRegion r(clipRect);
7605 d->subtractOpaqueChildren(r, clipRect);
7606 d->subtractOpaqueSiblings(r);
7611 QSize QWidgetPrivate::adjustedSize() const
7615 QSize s = q->sizeHint();
7617 if (q->isWindow()) {
7618 Qt::Orientations exp;
7620 if (layout->hasHeightForWidth())
7621 s.setHeight(layout->totalHeightForWidth(s.width()));
7622 exp = layout->expandingDirections();
7625 if (q->sizePolicy().hasHeightForWidth())
7626 s.setHeight(q->heightForWidth(s.width()));
7627 exp = q->sizePolicy().expandingDirections();
7629 if (exp & Qt::Horizontal)
7630 s.setWidth(qMax(s.width(), 200));
7631 if (exp & Qt::Vertical)
7632 s.setHeight(qMax(s.height(), 100));
7633 #if defined(Q_WS_X11)
7634 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7636 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7638 #if defined (Q_OS_WINCE)
7639 s.setWidth(qMin(s.width(), screen.width()));
7640 s.setHeight(qMin(s.height(), screen.height()));
7642 s.setWidth(qMin(s.width(), screen.width()*2/3));
7643 s.setHeight(qMin(s.height(), screen.height()*2/3));
7645 if (QTLWExtra *extra = maybeTopData())
7646 extra->sizeAdjusted = true;
7650 QRect r = q->childrenRect(); // get children rectangle
7653 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7660 Adjusts the size of the widget to fit its contents.
7662 This function uses sizeHint() if it is valid, i.e., the size hint's width
7663 and height are \>= 0. Otherwise, it sets the size to the children
7664 rectangle that covers all child widgets (the union of all child widget
7667 For windows, the screen size is also taken into account. If the sizeHint()
7668 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7669 {expanding}, the window will be at least (200, 100). The maximum size of
7670 a window is 2/3 of the screen's width and height.
7672 \sa sizeHint(), childrenRect()
7675 void QWidget::adjustSize()
7679 QSize s = d->adjustedSize();
7682 d->layout->activate();
7690 \property QWidget::sizeHint
7691 \brief the recommended size for the widget
7693 If the value of this property is an invalid size, no size is
7696 The default implementation of sizeHint() returns an invalid size
7697 if there is no layout for this widget, and returns the layout's
7698 preferred size otherwise.
7700 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7701 setMinimumSize(), updateGeometry()
7704 QSize QWidget::sizeHint() const
7708 return d->layout->totalSizeHint();
7709 return QSize(-1, -1);
7713 \property QWidget::minimumSizeHint
7714 \brief the recommended minimum size for the widget
7716 If the value of this property is an invalid size, no minimum size
7719 The default implementation of minimumSizeHint() returns an invalid
7720 size if there is no layout for this widget, and returns the
7721 layout's minimum size otherwise. Most built-in widgets reimplement
7724 \l QLayout will never resize a widget to a size smaller than the
7725 minimum size hint unless minimumSize() is set or the size policy is
7726 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7727 size hint will be ignored.
7729 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7731 QSize QWidget::minimumSizeHint() const
7735 return d->layout->totalMinimumSize();
7736 return QSize(-1, -1);
7741 \fn QWidget *QWidget::parentWidget() const
7743 Returns the parent of this widget, or 0 if it does not have any
7749 Returns true if this widget is a parent, (or grandparent and so on
7750 to any level), of the given \a child, and both widgets are within
7751 the same window; otherwise returns false.
7754 bool QWidget::isAncestorOf(const QWidget *child) const
7759 if (child->isWindow())
7761 child = child->parentWidget();
7766 #if defined(Q_WS_WIN)
7767 inline void setDisabledStyle(QWidget *w, bool setStyle)
7769 // set/reset WS_DISABLED style.
7770 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7771 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7772 LONG newStyle = dwStyle;
7774 newStyle |= WS_DISABLED;
7776 newStyle &= ~WS_DISABLED;
7777 if (newStyle != dwStyle) {
7778 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7779 // we might need to repaint in some situations (eg. menu)
7786 /*****************************************************************************
7787 QWidget event handling
7788 *****************************************************************************/
7791 This is the main event handler; it handles event \a event. You can
7792 reimplement this function in a subclass, but we recommend using
7793 one of the specialized event handlers instead.
7795 Key press and release events are treated differently from other
7796 events. event() checks for Tab and Shift+Tab and tries to move the
7797 focus appropriately. If there is no widget to move the focus to
7798 (or the key press is not Tab or Shift+Tab), event() calls
7801 Mouse and tablet event handling is also slightly special: only
7802 when the widget is \l enabled, event() will call the specialized
7803 handlers such as mousePressEvent(); otherwise it will discard the
7806 This function returns true if the event was recognized, otherwise
7807 it returns false. If the recognized event was accepted (see \l
7808 QEvent::accepted), any further processing such as event
7809 propagation to the parent widget stops.
7811 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7812 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7813 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7814 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7815 QObject::event(), QObject::timerEvent()
7818 bool QWidget::event(QEvent *event)
7822 // ignore mouse and key events when disabled
7824 switch(event->type()) {
7825 case QEvent::TabletPress:
7826 case QEvent::TabletRelease:
7827 case QEvent::TabletMove:
7828 case QEvent::MouseButtonPress:
7829 case QEvent::MouseButtonRelease:
7830 case QEvent::MouseButtonDblClick:
7831 case QEvent::MouseMove:
7832 case QEvent::TouchBegin:
7833 case QEvent::TouchUpdate:
7834 case QEvent::TouchEnd:
7835 case QEvent::TouchCancel:
7836 case QEvent::ContextMenu:
7837 case QEvent::KeyPress:
7838 case QEvent::KeyRelease:
7839 #ifndef QT_NO_WHEELEVENT
7847 switch (event->type()) {
7848 case QEvent::MouseMove:
7849 mouseMoveEvent((QMouseEvent*)event);
7852 case QEvent::MouseButtonPress:
7853 mousePressEvent((QMouseEvent*)event);
7856 case QEvent::MouseButtonRelease:
7857 mouseReleaseEvent((QMouseEvent*)event);
7860 case QEvent::MouseButtonDblClick:
7861 mouseDoubleClickEvent((QMouseEvent*)event);
7863 #ifndef QT_NO_WHEELEVENT
7865 wheelEvent((QWheelEvent*)event);
7868 #ifndef QT_NO_TABLETEVENT
7869 case QEvent::TabletMove:
7870 case QEvent::TabletPress:
7871 case QEvent::TabletRelease:
7872 tabletEvent((QTabletEvent*)event);
7875 case QEvent::KeyPress: {
7876 QKeyEvent *k = (QKeyEvent *)event;
7878 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7879 if (k->key() == Qt::Key_Backtab
7880 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7881 res = focusNextPrevChild(false);
7882 else if (k->key() == Qt::Key_Tab)
7883 res = focusNextPrevChild(true);
7888 #ifdef QT_KEYPAD_NAVIGATION
7889 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7890 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7891 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7892 if (k->key() == Qt::Key_Up)
7893 res = focusNextPrevChild(false);
7894 else if (k->key() == Qt::Key_Down)
7895 res = focusNextPrevChild(true);
7896 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7897 if (k->key() == Qt::Key_Up)
7898 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7899 else if (k->key() == Qt::Key_Right)
7900 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7901 else if (k->key() == Qt::Key_Down)
7902 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7903 else if (k->key() == Qt::Key_Left)
7904 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7912 #ifndef QT_NO_WHATSTHIS
7913 if (!k->isAccepted()
7914 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7915 && d->whatsThis.size()) {
7916 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7923 case QEvent::KeyRelease:
7924 keyReleaseEvent((QKeyEvent*)event);
7926 case QEvent::ShortcutOverride:
7929 case QEvent::InputMethod:
7930 inputMethodEvent((QInputMethodEvent *) event);
7933 case QEvent::InputMethodQuery:
7934 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7935 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7936 Qt::InputMethodQueries queries = query->queries();
7937 for (uint i = 0; i < 32; ++i) {
7938 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7940 QVariant v = inputMethodQuery(q);
7941 if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7942 v = QVariant(true); // special case for Qt4 compatibility
7943 query->setValue(q, v);
7950 case QEvent::PolishRequest:
7954 case QEvent::Polish: {
7955 style()->polish(this);
7956 setAttribute(Qt::WA_WState_Polished);
7957 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7959 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7960 d->resolvePalette();
7964 case QEvent::ApplicationWindowIconChange:
7965 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7966 d->setWindowIcon_sys();
7967 d->setWindowIcon_helper();
7970 case QEvent::FocusIn:
7971 focusInEvent((QFocusEvent*)event);
7972 d->updateWidgetTransform();
7975 case QEvent::FocusOut:
7976 focusOutEvent((QFocusEvent*)event);
7980 #ifndef QT_NO_STATUSTIP
7981 if (d->statusTip.size()) {
7982 QStatusTipEvent tip(d->statusTip);
7983 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7990 #ifndef QT_NO_STATUSTIP
7991 if (d->statusTip.size()) {
7993 QStatusTipEvent tip(empty);
7994 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8000 case QEvent::HoverEnter:
8001 case QEvent::HoverLeave:
8006 // At this point the event has to be delivered, regardless
8007 // whether the widget isVisible() or not because it
8008 // already went through the filters
8009 paintEvent((QPaintEvent*)event);
8013 moveEvent((QMoveEvent*)event);
8014 d->updateWidgetTransform();
8017 case QEvent::Resize:
8018 resizeEvent((QResizeEvent*)event);
8019 d->updateWidgetTransform();
8023 closeEvent((QCloseEvent *)event);
8026 #ifndef QT_NO_CONTEXTMENU
8027 case QEvent::ContextMenu:
8028 switch (data->context_menu_policy) {
8029 case Qt::PreventContextMenu:
8031 case Qt::DefaultContextMenu:
8032 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8034 case Qt::CustomContextMenu:
8035 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8038 case Qt::ActionsContextMenu:
8039 if (d->actions.count()) {
8040 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8051 #endif // QT_NO_CONTEXTMENU
8053 #ifndef QT_NO_DRAGANDDROP
8055 dropEvent((QDropEvent*) event);
8058 case QEvent::DragEnter:
8059 dragEnterEvent((QDragEnterEvent*) event);
8062 case QEvent::DragMove:
8063 dragMoveEvent((QDragMoveEvent*) event);
8066 case QEvent::DragLeave:
8067 dragLeaveEvent((QDragLeaveEvent*) event);
8072 showEvent((QShowEvent*) event);
8076 hideEvent((QHideEvent*) event);
8079 case QEvent::ShowWindowRequest:
8084 case QEvent::ApplicationFontChange:
8087 case QEvent::ApplicationPaletteChange:
8088 if (!(windowType() == Qt::Desktop))
8089 d->resolvePalette();
8092 case QEvent::ToolBarChange:
8093 case QEvent::ActivationChange:
8094 case QEvent::EnabledChange:
8095 case QEvent::FontChange:
8096 case QEvent::StyleChange:
8097 case QEvent::PaletteChange:
8098 case QEvent::WindowTitleChange:
8099 case QEvent::IconTextChange:
8100 case QEvent::ModifiedChange:
8101 case QEvent::MouseTrackingChange:
8102 case QEvent::ParentChange:
8103 case QEvent::WindowStateChange:
8104 case QEvent::LocaleChange:
8105 case QEvent::MacSizeChange:
8106 case QEvent::ContentsRectChange:
8107 case QEvent::ThemeChange:
8111 case QEvent::WindowActivate:
8112 case QEvent::WindowDeactivate: {
8113 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8115 QList<QObject*> childList = d->children;
8116 for (int i = 0; i < childList.size(); ++i) {
8117 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8118 if (w && w->isVisible() && !w->isWindow())
8119 QApplication::sendEvent(w, event);
8123 case QEvent::LanguageChange:
8126 QList<QObject*> childList = d->children;
8127 for (int i = 0; i < childList.size(); ++i) {
8128 QObject *o = childList.at(i);
8130 QApplication::sendEvent(o, event);
8136 case QEvent::ApplicationLayoutDirectionChange:
8137 d->resolveLayoutDirection();
8140 case QEvent::LayoutDirectionChange:
8142 d->layout->invalidate();
8146 case QEvent::UpdateRequest:
8147 d->syncBackingStore();
8149 case QEvent::UpdateLater:
8150 update(static_cast<QUpdateLaterEvent*>(event)->region());
8152 case QEvent::StyleAnimationUpdate:
8156 case QEvent::WindowBlocked:
8157 case QEvent::WindowUnblocked:
8158 if (!d->children.isEmpty()) {
8159 QWidget *modalWidget = QApplication::activeModalWidget();
8160 for (int i = 0; i < d->children.size(); ++i) {
8161 QObject *o = d->children.at(i);
8162 if (o && o != modalWidget && o->isWidgetType()) {
8163 QWidget *w = static_cast<QWidget *>(o);
8164 // do not forward the event to child windows; QApplication does this for us
8166 QApplication::sendEvent(w, event);
8170 #if defined(Q_WS_WIN)
8171 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8174 #ifndef QT_NO_TOOLTIP
8175 case QEvent::ToolTip:
8176 if (!d->toolTip.isEmpty())
8177 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8182 #ifndef QT_NO_WHATSTHIS
8183 case QEvent::WhatsThis:
8184 if (d->whatsThis.size())
8185 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8189 case QEvent::QueryWhatsThis:
8190 if (d->whatsThis.isEmpty())
8194 case QEvent::EmbeddingControl:
8195 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8196 data->fstrut_dirty = false;
8197 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8198 d->topData()->embedded = 1;
8201 #ifndef QT_NO_ACTION
8202 case QEvent::ActionAdded:
8203 case QEvent::ActionRemoved:
8204 case QEvent::ActionChanged:
8205 actionEvent((QActionEvent*)event);
8209 case QEvent::KeyboardLayoutChange:
8213 // inform children of the change
8214 QList<QObject*> childList = d->children;
8215 for (int i = 0; i < childList.size(); ++i) {
8216 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8217 if (w && w->isVisible() && !w->isWindow())
8218 QApplication::sendEvent(w, event);
8223 case QEvent::MacGLWindowChange:
8224 d->needWindowChange = false;
8227 case QEvent::TouchBegin:
8228 case QEvent::TouchUpdate:
8229 case QEvent::TouchEnd:
8230 case QEvent::TouchCancel:
8235 #ifndef QT_NO_GESTURES
8236 case QEvent::Gesture:
8240 #ifndef QT_NO_PROPERTIES
8241 case QEvent::DynamicPropertyChange: {
8242 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8243 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8244 uint value = property(propName.constData()).toUInt();
8247 const char axis = propName.at(12);
8249 d->extra->customDpiX = value;
8250 else if (axis == 'Y')
8251 d->extra->customDpiY = value;
8252 d->updateFont(d->data.fnt);
8258 return QObject::event(event);
8264 This event handler can be reimplemented to handle state changes.
8266 The state being changed in this event can be retrieved through the \a event
8269 Change events include: QEvent::ToolBarChange,
8270 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8271 QEvent::StyleChange, QEvent::PaletteChange,
8272 QEvent::WindowTitleChange, QEvent::IconTextChange,
8273 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8274 QEvent::ParentChange, QEvent::WindowStateChange,
8275 QEvent::LanguageChange, QEvent::LocaleChange,
8276 QEvent::LayoutDirectionChange.
8279 void QWidget::changeEvent(QEvent * event)
8281 switch(event->type()) {
8282 case QEvent::EnabledChange: {
8284 #ifndef QT_NO_ACCESSIBILITY
8285 QAccessible::State s;
8287 QAccessibleStateChangeEvent event(this, s);
8288 QAccessible::updateAccessibility(&event);
8293 case QEvent::FontChange:
8294 case QEvent::StyleChange: {
8299 d->layout->invalidate();
8303 case QEvent::PaletteChange:
8307 case QEvent::ThemeChange:
8308 if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8309 && qApp && !QApplication::closingDown()) {
8310 if (testAttribute(Qt::WA_WState_Polished))
8311 QApplication::style()->unpolish(this);
8312 if (testAttribute(Qt::WA_WState_Polished))
8313 QApplication::style()->polish(this);
8314 QEvent styleChangedEvent(QEvent::StyleChange);
8315 QCoreApplication::sendEvent(this, &styleChangedEvent);
8322 case QEvent::MacSizeChange:
8325 #elif defined Q_WS_MAC
8326 case QEvent::ToolTipChange:
8327 case QEvent::MouseTrackingChange:
8328 qt_mac_update_mouseTracking(this);
8338 This event handler, for event \a event, can be reimplemented in a
8339 subclass to receive mouse move events for the widget.
8341 If mouse tracking is switched off, mouse move events only occur if
8342 a mouse button is pressed while the mouse is being moved. If mouse
8343 tracking is switched on, mouse move events occur even if no mouse
8346 QMouseEvent::pos() reports the position of the mouse cursor,
8347 relative to this widget. For press and release events, the
8348 position is usually the same as the position of the last mouse
8349 move event, but it might be different if the user's hand shakes.
8350 This is a feature of the underlying window system, not Qt.
8352 If you want to show a tooltip immediately, while the mouse is
8353 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8354 and show them as a tooltip), you must first enable mouse tracking
8355 as described above. Then, to ensure that the tooltip is updated
8356 immediately, you must call QToolTip::showText() instead of
8357 setToolTip() in your implementation of mouseMoveEvent().
8359 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8360 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8363 void QWidget::mouseMoveEvent(QMouseEvent *event)
8369 This event handler, for event \a event, can be reimplemented in a
8370 subclass to receive mouse press events for the widget.
8372 If you create new widgets in the mousePressEvent() the
8373 mouseReleaseEvent() may not end up where you expect, depending on
8374 the underlying window system (or X11 window manager), the widgets'
8375 location and maybe more.
8377 The default implementation implements the closing of popup widgets
8378 when you click outside the window. For other widget types it does
8381 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8382 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8385 void QWidget::mousePressEvent(QMouseEvent *event)
8388 if ((windowType() == Qt::Popup)) {
8391 while ((w = QApplication::activePopupWidget()) && w != this){
8393 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8394 w->hide(); // hide at least
8396 if (!rect().contains(event->pos())){
8403 This event handler, for event \a event, can be reimplemented in a
8404 subclass to receive mouse release events for the widget.
8406 \sa mousePressEvent(), mouseDoubleClickEvent(),
8407 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8410 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8416 This event handler, for event \a event, can be reimplemented in a
8417 subclass to receive mouse double click events for the widget.
8419 The default implementation generates a normal mouse press event.
8421 \note The widget will also receive mouse press and mouse release
8422 events in addition to the double click event. It is up to the
8423 developer to ensure that the application interprets these events
8426 \sa mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(),
8427 event(), QMouseEvent
8430 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8435 #ifndef QT_NO_WHEELEVENT
8437 This event handler, for event \a event, can be reimplemented in a
8438 subclass to receive wheel events for the widget.
8440 If you reimplement this handler, it is very important that you
8441 \l{QWheelEvent}{ignore()} the event if you do not handle
8442 it, so that the widget's parent can interpret it.
8444 The default implementation ignores the event.
8446 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8450 void QWidget::wheelEvent(QWheelEvent *event)
8454 #endif // QT_NO_WHEELEVENT
8456 #ifndef QT_NO_TABLETEVENT
8458 This event handler, for event \a event, can be reimplemented in a
8459 subclass to receive tablet events for the widget.
8461 If you reimplement this handler, it is very important that you
8462 \l{QTabletEvent}{ignore()} the event if you do not handle
8463 it, so that the widget's parent can interpret it.
8465 The default implementation ignores the event.
8467 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8471 void QWidget::tabletEvent(QTabletEvent *event)
8475 #endif // QT_NO_TABLETEVENT
8478 This event handler, for event \a event, can be reimplemented in a
8479 subclass to receive key press events for the widget.
8481 A widget must call setFocusPolicy() to accept focus initially and
8482 have focus in order to receive a key press event.
8484 If you reimplement this handler, it is very important that you
8485 call the base class implementation if you do not act upon the key.
8487 The default implementation closes popup widgets if the user
8488 presses Esc. Otherwise the event is ignored, so that the widget's
8489 parent can interpret it.
8491 Note that QKeyEvent starts with isAccepted() == true, so you do not
8492 need to call QKeyEvent::accept() - just do not call the base class
8493 implementation if you act upon the key.
8495 \sa keyReleaseEvent(), setFocusPolicy(),
8496 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8499 void QWidget::keyPressEvent(QKeyEvent *event)
8501 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8510 This event handler, for event \a event, can be reimplemented in a
8511 subclass to receive key release events for the widget.
8513 A widget must \l{setFocusPolicy()}{accept focus}
8514 initially and \l{hasFocus()}{have focus} in order to
8515 receive a key release event.
8517 If you reimplement this handler, it is very important that you
8518 call the base class implementation if you do not act upon the key.
8520 The default implementation ignores the event, so that the widget's
8521 parent can interpret it.
8523 Note that QKeyEvent starts with isAccepted() == true, so you do not
8524 need to call QKeyEvent::accept() - just do not call the base class
8525 implementation if you act upon the key.
8527 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8528 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8531 void QWidget::keyReleaseEvent(QKeyEvent *event)
8537 \fn void QWidget::focusInEvent(QFocusEvent *event)
8539 This event handler can be reimplemented in a subclass to receive
8540 keyboard focus events (focus received) for the widget. The event
8541 is passed in the \a event parameter
8543 A widget normally must setFocusPolicy() to something other than
8544 Qt::NoFocus in order to receive focus events. (Note that the
8545 application programmer can call setFocus() on any widget, even
8546 those that do not normally accept focus.)
8548 The default implementation updates the widget (except for windows
8549 that do not specify a focusPolicy()).
8551 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8552 keyReleaseEvent(), event(), QFocusEvent
8555 void QWidget::focusInEvent(QFocusEvent *)
8557 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8563 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8565 This event handler can be reimplemented in a subclass to receive
8566 keyboard focus events (focus lost) for the widget. The events is
8567 passed in the \a event parameter.
8569 A widget normally must setFocusPolicy() to something other than
8570 Qt::NoFocus in order to receive focus events. (Note that the
8571 application programmer can call setFocus() on any widget, even
8572 those that do not normally accept focus.)
8574 The default implementation updates the widget (except for windows
8575 that do not specify a focusPolicy()).
8577 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8578 keyReleaseEvent(), event(), QFocusEvent
8581 void QWidget::focusOutEvent(QFocusEvent *)
8583 if (focusPolicy() != Qt::NoFocus || !isWindow())
8588 \fn void QWidget::enterEvent(QEvent *event)
8590 This event handler can be reimplemented in a subclass to receive
8591 widget enter events which are passed in the \a event parameter.
8593 An event is sent to the widget when the mouse cursor enters the
8596 \sa leaveEvent(), mouseMoveEvent(), event()
8599 void QWidget::enterEvent(QEvent *)
8603 // ### Qt 6: void QWidget::enterEvent(QEnterEvent *).
8606 \fn void QWidget::leaveEvent(QEvent *event)
8608 This event handler can be reimplemented in a subclass to receive
8609 widget leave events which are passed in the \a event parameter.
8611 A leave event is sent to the widget when the mouse cursor leaves
8614 \sa enterEvent(), mouseMoveEvent(), event()
8617 void QWidget::leaveEvent(QEvent *)
8622 \fn void QWidget::paintEvent(QPaintEvent *event)
8624 This event handler can be reimplemented in a subclass to receive paint
8625 events passed in \a event.
8627 A paint event is a request to repaint all or part of a widget. It can
8628 happen for one of the following reasons:
8631 \li repaint() or update() was invoked,
8632 \li the widget was obscured and has now been uncovered, or
8633 \li many other reasons.
8636 Many widgets can simply repaint their entire surface when asked to, but
8637 some slow widgets need to optimize by painting only the requested region:
8638 QPaintEvent::region(). This speed optimization does not change the result,
8639 as painting is clipped to that region during event processing. QListView
8640 and QTableView do this, for example.
8642 Qt also tries to speed up painting by merging multiple paint events into
8643 one. When update() is called several times or the window system sends
8644 several paint events, Qt merges these events into one event with a larger
8645 region (see QRegion::united()). The repaint() function does not permit this
8646 optimization, so we suggest using update() whenever possible.
8648 When the paint event occurs, the update region has normally been erased, so
8649 you are painting on the widget's background.
8651 The background can be set using setBackgroundRole() and setPalette().
8653 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8654 is no need to write double-buffering code in paintEvent() to avoid flicker.
8656 \b{Note for the X11 platform}: It is possible to toggle global double
8657 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8659 \snippet code/src_gui_kernel_qwidget.cpp 14
8661 \note Generally, you should refrain from calling update() or repaint()
8662 \b{inside} a paintEvent(). For example, calling update() or repaint() on
8663 children inside a paintevent() results in undefined behavior; the child may
8664 or may not get a paint event.
8666 \warning If you are using a custom paint engine without Qt's backingstore,
8667 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8668 never be called; the backingstore will be used instead.
8670 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8671 {Analog Clock Example}
8674 void QWidget::paintEvent(QPaintEvent *)
8680 \fn void QWidget::moveEvent(QMoveEvent *event)
8682 This event handler can be reimplemented in a subclass to receive
8683 widget move events which are passed in the \a event parameter.
8684 When the widget receives this event, it is already at the new
8687 The old position is accessible through QMoveEvent::oldPos().
8689 \sa resizeEvent(), event(), move(), QMoveEvent
8692 void QWidget::moveEvent(QMoveEvent *)
8698 This event handler can be reimplemented in a subclass to receive
8699 widget resize events which are passed in the \a event parameter.
8700 When resizeEvent() is called, the widget already has its new
8701 geometry. The old size is accessible through
8702 QResizeEvent::oldSize().
8704 The widget will be erased and receive a paint event immediately
8705 after processing the resize event. No drawing need be (or should
8706 be) done inside this handler.
8709 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8713 void QWidget::resizeEvent(QResizeEvent * /* event */)
8717 #ifndef QT_NO_ACTION
8719 \fn void QWidget::actionEvent(QActionEvent *event)
8721 This event handler is called with the given \a event whenever the
8722 widget's actions are changed.
8724 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8726 void QWidget::actionEvent(QActionEvent *)
8733 This event handler is called with the given \a event when Qt receives a window
8734 close request for a top-level widget from the window system.
8736 By default, the event is accepted and the widget is closed. You can reimplement
8737 this function to change the way the widget responds to window close requests.
8738 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8741 Main window applications typically use reimplementations of this function to check
8742 whether the user's work has been saved and ask for permission before closing.
8743 For example, the \l{Application Example} uses a helper function to determine whether
8744 or not to close the window:
8746 \snippet mainwindows/application/mainwindow.cpp 3
8747 \snippet mainwindows/application/mainwindow.cpp 4
8749 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8752 void QWidget::closeEvent(QCloseEvent *event)
8757 #ifndef QT_NO_CONTEXTMENU
8759 This event handler, for event \a event, can be reimplemented in a
8760 subclass to receive widget context menu events.
8762 The handler is called when the widget's \l contextMenuPolicy is
8763 Qt::DefaultContextMenu.
8765 The default implementation ignores the context event.
8766 See the \l QContextMenuEvent documentation for more details.
8768 \sa event(), QContextMenuEvent, customContextMenuRequested()
8771 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8775 #endif // QT_NO_CONTEXTMENU
8779 This event handler, for event \a event, can be reimplemented in a
8780 subclass to receive Input Method composition events. This handler
8781 is called when the state of the input method changes.
8783 Note that when creating custom text editing widgets, the
8784 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8785 (using the setAttribute() function) in order to receive input
8788 The default implementation calls event->ignore(), which rejects the
8789 Input Method event. See the \l QInputMethodEvent documentation for more
8792 \sa event(), QInputMethodEvent
8794 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8800 This method is only relevant for input widgets. It is used by the
8801 input method to query a set of properties of the widget to be
8802 able to support complex input method operations as support for
8803 surrounding text and reconversions.
8805 \a query specifies which property is queried.
8807 \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8809 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8812 case Qt::ImCursorRectangle:
8813 return QRect(width()/2, 0, 1, height());
8816 case Qt::ImAnchorPosition:
8818 return inputMethodQuery(Qt::ImCursorPosition);
8820 return (int)inputMethodHints();
8827 \property QWidget::inputMethodHints
8828 \brief What input method specific hints the widget has.
8830 This is only relevant for input widgets. It is used by
8831 the input method to retrieve hints as to how the input method
8832 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8833 is set, the input method may change its visual components to reflect
8834 that only numbers can be entered.
8836 \note The flags are only hints, so the particular input method
8837 implementation is free to ignore them. If you want to be
8838 sure that a certain type of characters are entered,
8839 you should also set a QValidator on the widget.
8841 The default value is Qt::ImhNone.
8845 \sa inputMethodQuery()
8847 Qt::InputMethodHints QWidget::inputMethodHints() const
8850 const QWidgetPrivate *priv = d_func();
8851 while (priv->inheritsInputMethodHints) {
8852 priv = priv->q_func()->parentWidget()->d_func();
8855 return priv->imHints;
8861 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8866 qApp->inputMethod()->update(Qt::ImHints);
8871 #ifndef QT_NO_DRAGANDDROP
8874 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8876 This event handler is called when a drag is in progress and the
8877 mouse enters this widget. The event is passed in the \a event parameter.
8879 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8882 See the \l{dnd.html}{Drag-and-drop documentation} for an
8883 overview of how to provide drag-and-drop in your application.
8885 \sa QDrag, QDragEnterEvent
8887 void QWidget::dragEnterEvent(QDragEnterEvent *)
8892 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8894 This event handler is called if a drag is in progress, and when
8895 any of the following conditions occur: the cursor enters this widget,
8896 the cursor moves within this widget, or a modifier key is pressed on
8897 the keyboard while this widget has the focus. The event is passed
8898 in the \a event parameter.
8900 See the \l{dnd.html}{Drag-and-drop documentation} for an
8901 overview of how to provide drag-and-drop in your application.
8903 \sa QDrag, QDragMoveEvent
8905 void QWidget::dragMoveEvent(QDragMoveEvent *)
8910 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8912 This event handler is called when a drag is in progress and the
8913 mouse leaves this widget. The event is passed in the \a event
8916 See the \l{dnd.html}{Drag-and-drop documentation} for an
8917 overview of how to provide drag-and-drop in your application.
8919 \sa QDrag, QDragLeaveEvent
8921 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8926 \fn void QWidget::dropEvent(QDropEvent *event)
8928 This event handler is called when the drag is dropped on this
8929 widget. The event is passed in the \a event parameter.
8931 See the \l{dnd.html}{Drag-and-drop documentation} for an
8932 overview of how to provide drag-and-drop in your application.
8934 \sa QDrag, QDropEvent
8936 void QWidget::dropEvent(QDropEvent *)
8940 #endif // QT_NO_DRAGANDDROP
8943 \fn void QWidget::showEvent(QShowEvent *event)
8945 This event handler can be reimplemented in a subclass to receive
8946 widget show events which are passed in the \a event parameter.
8948 Non-spontaneous show events are sent to widgets immediately
8949 before they are shown. The spontaneous show events of windows are
8950 delivered afterwards.
8952 Note: A widget receives spontaneous show and hide events when its
8953 mapping status is changed by the window system, e.g. a spontaneous
8954 hide event when the user minimizes the window, and a spontaneous
8955 show event when the window is restored again. After receiving a
8956 spontaneous hide event, a widget is still considered visible in
8957 the sense of isVisible().
8959 \sa visible, event(), QShowEvent
8961 void QWidget::showEvent(QShowEvent *)
8966 \fn void QWidget::hideEvent(QHideEvent *event)
8968 This event handler can be reimplemented in a subclass to receive
8969 widget hide events. The event is passed in the \a event parameter.
8971 Hide events are sent to widgets immediately after they have been
8974 Note: A widget receives spontaneous show and hide events when its
8975 mapping status is changed by the window system, e.g. a spontaneous
8976 hide event when the user minimizes the window, and a spontaneous
8977 show event when the window is restored again. After receiving a
8978 spontaneous hide event, a widget is still considered visible in
8979 the sense of isVisible().
8981 \sa visible, event(), QHideEvent
8983 void QWidget::hideEvent(QHideEvent *)
8988 This special event handler can be reimplemented in a subclass to
8989 receive native platform events identified by \a eventType
8990 which are passed in the \a message parameter.
8992 In your reimplementation of this function, if you want to stop the
8993 event being handled by Qt, return true and set \a result.
8994 If you return false, this native event is passed back to Qt,
8995 which translates the event into a Qt event and sends it to the widget.
8997 \note Events are only delivered to this event handler if the widget is
8998 has a native Window handle.
9000 \note This function superseedes the event filter functions
9001 x11Event(), winEvent() and macEvent() of Qt 4.
9004 \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
9005 \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
9009 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
9011 Q_UNUSED(eventType);
9018 Ensures that the widget has been polished by QStyle (i.e., has a
9019 proper font and palette).
9021 QWidget calls this function after it has been fully constructed
9022 but before it is shown the very first time. You can call this
9023 function if you want to ensure that the widget is polished before
9024 doing an operation, e.g., the correct font size might be needed in
9025 the widget's sizeHint() reimplementation. Note that this function
9026 \e is called from the default implementation of sizeHint().
9028 Polishing is useful for final initialization that must happen after
9029 all constructors (from base classes as well as from subclasses)
9032 If you need to change some settings when a widget is polished,
9033 reimplement event() and handle the QEvent::Polish event type.
9035 \b{Note:} The function is declared const so that it can be called from
9036 other const functions (e.g., sizeHint()).
9040 void QWidget::ensurePolished() const
9044 const QMetaObject *m = metaObject();
9045 if (m == d->polished)
9049 QEvent e(QEvent::Polish);
9050 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9052 // polish children after 'this'
9053 QList<QObject*> children = d->children;
9054 for (int i = 0; i < children.size(); ++i) {
9055 QObject *o = children.at(i);
9056 if(!o->isWidgetType())
9058 if (QWidget *w = qobject_cast<QWidget *>(o))
9059 w->ensurePolished();
9062 if (d->parent && d->sendChildEvents) {
9063 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9064 QCoreApplication::sendEvent(d->parent, &e);
9069 Returns the mask currently set on a widget. If no mask is set the
9070 return value will be an empty region.
9072 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9074 QRegion QWidget::mask() const
9077 return d->extra ? d->extra->mask : QRegion();
9081 Returns the layout manager that is installed on this widget, or 0
9082 if no layout manager is installed.
9084 The layout manager sets the geometry of the widget's children
9085 that have been added to the layout.
9087 \sa setLayout(), sizePolicy(), {Layout Management}
9089 QLayout *QWidget::layout() const
9091 return d_func()->layout;
9096 \fn void QWidget::setLayout(QLayout *layout)
9098 Sets the layout manager for this widget to \a layout.
9100 If there already is a layout manager installed on this widget,
9101 QWidget won't let you install another. You must first delete the
9102 existing layout manager (returned by layout()) before you can
9103 call setLayout() with the new layout.
9105 If \a layout is the layout manger on a different widget, setLayout()
9106 will reparent the layout and make it the layout manager for this widget.
9110 \snippet layouts/layouts.cpp 24
9112 An alternative to calling this function is to pass this widget to
9113 the layout's constructor.
9115 The QWidget will take ownership of \a layout.
9117 \sa layout(), {Layout Management}
9120 void QWidget::setLayout(QLayout *l)
9123 qWarning("QWidget::setLayout: Cannot set layout to 0");
9128 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9129 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9130 objectName().toLocal8Bit().data());
9134 QObject *oldParent = l->parent();
9135 if (oldParent && oldParent != this) {
9136 if (oldParent->isWidgetType()) {
9137 // Steal the layout off a widget parent. Takes effect when
9138 // morphing laid-out container widgets in Designer.
9139 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9140 oldParentWidget->takeLayout();
9142 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9143 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9144 objectName().toLocal8Bit().data());
9150 l->d_func()->topLevel = true;
9152 if (oldParent != this) {
9154 l->d_func()->reparentChildWidgets(this);
9158 if (isWindow() && d->maybeTopData())
9159 d->topData()->sizeAdjusted = false;
9163 \fn QLayout *QWidget::takeLayout()
9165 Remove the layout from the widget.
9169 QLayout *QWidget::takeLayout()
9172 QLayout *l = layout();
9181 \property QWidget::sizePolicy
9182 \brief the default layout behavior of the widget
9184 If there is a QLayout that manages this widget's children, the
9185 size policy specified by that layout is used. If there is no such
9186 QLayout, the result of this function is used.
9188 The default policy is Preferred/Preferred, which means that the
9189 widget can be freely resized, but prefers to be the size
9190 sizeHint() returns. Button-like widgets set the size policy to
9191 specify that they may stretch horizontally, but are fixed
9192 vertically. The same applies to lineedit controls (such as
9193 QLineEdit, QSpinBox or an editable QComboBox) and other
9194 horizontally orientated widgets (such as QProgressBar).
9195 QToolButton's are normally square, so they allow growth in both
9196 directions. Widgets that support different directions (such as
9197 QSlider, QScrollBar or QHeader) specify stretching in the
9198 respective direction only. Widgets that can provide scroll bars
9199 (usually subclasses of QScrollArea) tend to specify that they can
9200 use additional space, and that they can make do with less than
9203 \sa sizeHint(), QLayout, QSizePolicy, updateGeometry()
9205 QSizePolicy QWidget::sizePolicy() const
9208 return d->size_policy;
9211 void QWidget::setSizePolicy(QSizePolicy policy)
9214 setAttribute(Qt::WA_WState_OwnSizePolicy);
9215 if (policy == d->size_policy)
9217 d->size_policy = policy;
9219 #ifndef QT_NO_GRAPHICSVIEW
9220 if (QWExtra *extra = d->extra) {
9221 if (extra->proxyWidget)
9222 extra->proxyWidget->setSizePolicy(policy);
9228 if (isWindow() && d->maybeTopData())
9229 d->topData()->sizeAdjusted = false;
9233 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9236 Sets the size policy of the widget to \a horizontal and \a
9237 vertical, with standard stretch and no height-for-width.
9239 \sa QSizePolicy::QSizePolicy()
9243 Returns the preferred height for this widget, given the width \a w.
9245 If this widget has a layout, the default implementation returns
9246 the layout's preferred height. if there is no layout, the default
9247 implementation returns -1 indicating that the preferred height
9248 does not depend on the width.
9251 int QWidget::heightForWidth(int w) const
9253 if (layout() && layout()->hasHeightForWidth())
9254 return layout()->totalHeightForWidth(w);
9262 Returns true if the widget's preferred height depends on its width; otherwise returns false.
9264 bool QWidget::hasHeightForWidth() const
9267 return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9271 \fn QWidget *QWidget::childAt(int x, int y) const
9273 Returns the visible child widget at the position (\a{x}, \a{y})
9274 in the widget's coordinate system. If there is no visible child
9275 widget at the specified position, the function returns 0.
9281 Returns the visible child widget at point \a p in the widget's own
9285 QWidget *QWidget::childAt(const QPoint &p) const
9287 return d_func()->childAt_helper(p, false);
9290 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9292 if (children.isEmpty())
9297 // Unified tool bars on the Mac require special handling since they live outside
9298 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9299 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9300 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9302 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9305 if (!pointInsideRectAndMask(p))
9307 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9310 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9313 Q_UNUSED(includeFrame);
9315 for (int i = children.size() - 1; i >= 0; --i) {
9316 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9317 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9318 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9322 // Map the point 'p' from parent coordinates to child coordinates.
9323 QPoint childPoint = p;
9325 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9326 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9327 // QWidget::mapFromParent won't do the trick.
9328 if (includeFrame && qobject_cast<QToolBar *>(child))
9329 childPoint = qt_mac_nativeMapFromParent(child, p);
9332 childPoint -= child->data->crect.topLeft();
9334 // Check if the point hits the child.
9335 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9338 // Do the same for the child's descendants.
9339 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9342 // We have found our target; namely the child at position 'p'.
9348 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9352 widgetItem->invalidateSizeCache();
9354 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9355 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9356 if (parent->d_func()->layout)
9357 parent->d_func()->layout->invalidate();
9358 else if (parent->isVisible())
9359 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9365 Notifies the layout system that this widget has changed and may
9366 need to change geometry.
9368 Call this function if the sizeHint() or sizePolicy() have changed.
9370 For explicitly hidden widgets, updateGeometry() is a no-op. The
9371 layout system will be notified as soon as the widget is shown.
9374 void QWidget::updateGeometry()
9377 d->updateGeometry_helper(false);
9380 /*! \property QWidget::windowFlags
9382 Window flags are a combination of a type (e.g. Qt::Dialog) and
9383 zero or more hints to the window system (e.g.
9384 Qt::FramelessWindowHint).
9386 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9387 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9388 0) on the desktop. If the widget is a window and becomes a
9389 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9390 relative to its parent widget.
9392 \note This function calls setParent() when changing the flags for
9393 a window, causing the widget to be hidden. You must call show() to make
9394 the widget visible again..
9396 \sa windowType(), {Window Flags Example}
9398 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9400 if (data->window_flags == flags)
9405 if ((data->window_flags | flags) & Qt::Window) {
9406 // the old type was a window and/or the new type is a window
9407 QPoint oldPos = pos();
9408 bool visible = isVisible();
9409 setParent(parentWidget(), flags);
9411 // if both types are windows or neither of them are, we restore
9413 if (!((data->window_flags ^ flags) & Qt::Window)
9414 && (visible || testAttribute(Qt::WA_Moved))) {
9417 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9418 d->adjustQuitOnCloseAttribute();
9420 data->window_flags = flags;
9425 Sets the window flags for the widget to \a flags,
9426 \e without telling the window system.
9428 \warning Do not call this function unless you really know what
9431 \sa setWindowFlags()
9433 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9435 data->window_flags = flags;
9439 \fn Qt::WindowType QWidget::windowType() const
9441 Returns the window type of this widget. This is identical to
9442 windowFlags() & Qt::WindowType_Mask.
9448 Sets the parent of the widget to \a parent, and resets the window
9449 flags. The widget is moved to position (0, 0) in its new parent.
9451 If the new parent widget is in a different window, the
9452 reparented widget and its children are appended to the end of the
9453 \l{setFocusPolicy()}{tab chain} of the new parent
9454 widget, in the same internal order as before. If one of the moved
9455 widgets had keyboard focus, setParent() calls clearFocus() for that
9458 If the new parent widget is in the same window as the
9459 old parent, setting the parent doesn't change the tab order or
9462 If the "new" parent widget is the old parent widget, this function
9465 \note The widget becomes invisible as part of changing its parent,
9466 even if it was previously visible. You must call show() to make the
9467 widget visible again.
9469 \warning It is very unlikely that you will ever need this
9470 function. If you have a widget that changes its content
9471 dynamically, it is far easier to use \l QStackedWidget.
9473 \sa setWindowFlags()
9475 void QWidget::setParent(QWidget *parent)
9477 if (parent == parentWidget())
9479 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9485 This function also takes widget flags, \a f as an argument.
9488 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9491 bool resized = testAttribute(Qt::WA_Resized);
9492 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9493 QWidget *oldtlw = window();
9495 QWidget *desktopWidget = 0;
9496 if (parent && parent->windowType() == Qt::Desktop)
9497 desktopWidget = parent;
9498 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9500 if (newParent && parent && !desktopWidget) {
9501 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9503 // On Mac, toolbars inside the unified title bar will never overlap with
9504 // siblings in the content view. So we skip enforce native siblings in that case
9505 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9508 parent->d_func()->enforceNativeChildren();
9509 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9510 setAttribute(Qt::WA_NativeWindow);
9514 if (!testAttribute(Qt::WA_WState_Hidden)) {
9516 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9519 QEvent e(QEvent::ParentAboutToChange);
9520 QApplication::sendEvent(this, &e);
9523 if (newParent && isAncestorOf(focusWidget()))
9524 focusWidget()->clearFocus();
9526 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9527 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9529 d->setParent_sys(parent, f);
9531 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9532 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9533 if (oldBsTracker && oldBsTracker != bsTracker)
9534 oldBsTracker->unregisterWidgetSubtree(this);
9539 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9541 oldBs->removeDirtyWidget(this);
9542 // Move the widget and all its static children from
9543 // the old backing store to the new one.
9544 oldBs->moveStaticWidgets(this);
9547 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9550 d->reparentFocusWidgets(oldtlw);
9551 setAttribute(Qt::WA_Resized, resized);
9552 if (!testAttribute(Qt::WA_StyleSheet)
9553 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9555 d->resolvePalette();
9557 d->resolveLayoutDirection();
9560 // Note: GL widgets under WGL or EGL will always need a ParentChange
9561 // event to handle recreation/rebinding of the GL context, hence the
9562 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9565 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9566 || (f & Qt::MSWindowsOwnDC)
9569 // propagate enabled updates enabled state to non-windows
9571 if (!testAttribute(Qt::WA_ForceDisabled))
9572 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9573 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9574 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9578 // send and post remaining QObject events
9579 if (parent && d->sendChildEvents) {
9580 QChildEvent e(QEvent::ChildAdded, this);
9581 QApplication::sendEvent(parent, &e);
9584 //### already hidden above ---> must probably do something smart on the mac
9586 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9587 // if(!qt_mac_is_macdrawer(q)) //special case
9588 // q->setAttribute(Qt::WA_WState_Hidden);
9590 // q->setAttribute(Qt::WA_WState_Hidden);
9593 if (parent && d->sendChildEvents && d->polished) {
9594 QChildEvent e(QEvent::ChildPolished, this);
9595 QCoreApplication::sendEvent(parent, &e);
9598 QEvent e(QEvent::ParentChange);
9599 QApplication::sendEvent(this, &e);
9603 if (isWindow() || parentWidget()->isVisible())
9604 setAttribute(Qt::WA_WState_Hidden, true);
9605 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9606 setAttribute(Qt::WA_WState_Hidden, false);
9609 d->updateIsOpaque();
9611 #ifndef QT_NO_GRAPHICSVIEW
9612 // Embed the widget into a proxy if the parent is embedded.
9613 // ### Doesn't handle reparenting out of an embedded widget.
9614 if (oldtlw->graphicsProxyWidget()) {
9615 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9616 ancestorProxy->d_func()->unembedSubWindow(this);
9618 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9619 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9620 ancestorProxy->d_func()->embedSubWindow(this);
9626 Scrolls the widget including its children \a dx pixels to the
9627 right and \a dy downward. Both \a dx and \a dy may be negative.
9629 After scrolling, the widgets will receive paint events for
9630 the areas that need to be repainted. For widgets that Qt knows to
9631 be opaque, this is only the newly exposed parts.
9632 For example, if an opaque widget is scrolled 8 pixels to the left,
9633 only an 8-pixel wide stripe at the right edge needs updating.
9635 Since widgets propagate the contents of their parents by default,
9636 you need to set the \l autoFillBackground property, or use
9637 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9640 For widgets that use contents propagation, a scroll will cause an
9641 update of the entire scroll area.
9643 \sa {Transparency and Double Buffering}
9646 void QWidget::scroll(int dx, int dy)
9648 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9650 if (dx == 0 && dy == 0)
9653 #ifndef QT_NO_GRAPHICSVIEW
9654 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9655 // Graphics View maintains its own dirty region as a list of rects;
9656 // until we can connect item updates directly to the view, we must
9657 // separately add a translated dirty region.
9658 if (!d->dirty.isEmpty()) {
9659 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9660 proxy->update(rect);
9662 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9666 d->setDirtyOpaqueRegion();
9667 d->scroll_sys(dx, dy);
9673 This version only scrolls \a r and does not move the children of
9676 If \a r is empty or invalid, the result is undefined.
9680 void QWidget::scroll(int dx, int dy, const QRect &r)
9683 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9685 if (dx == 0 && dy == 0)
9688 #ifndef QT_NO_GRAPHICSVIEW
9689 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9690 // Graphics View maintains its own dirty region as a list of rects;
9691 // until we can connect item updates directly to the view, we must
9692 // separately add a translated dirty region.
9693 if (!d->dirty.isEmpty()) {
9694 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9695 proxy->update(rect);
9697 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9701 d->scroll_sys(dx, dy, r);
9705 Repaints the widget directly by calling paintEvent() immediately,
9706 unless updates are disabled or the widget is hidden.
9708 We suggest only using repaint() if you need an immediate repaint,
9709 for example during animation. In almost all circumstances update()
9710 is better, as it permits Qt to optimize for speed and minimize
9713 \warning If you call repaint() in a function which may itself be
9714 called from paintEvent(), you may get infinite recursion. The
9715 update() function never causes recursion.
9717 \sa update(), paintEvent(), setUpdatesEnabled()
9720 void QWidget::repaint()
9727 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9730 If \a w is negative, it is replaced with \c{width() - x}, and if
9731 \a h is negative, it is replaced width \c{height() - y}.
9733 void QWidget::repaint(int x, int y, int w, int h)
9735 if (x > data->crect.width() || y > data->crect.height())
9739 w = data->crect.width() - x;
9741 h = data->crect.height() - y;
9743 repaint(QRect(x, y, w, h));
9748 This version repaints a rectangle \a rect inside the widget.
9750 void QWidget::repaint(const QRect &rect)
9754 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9759 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9762 if (hasBackingStoreSupport()) {
9764 if (qt_widget_private(this)->isInUnifiedToolbar) {
9765 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9769 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9770 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9771 tlwExtra->inRepaint = true;
9772 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9773 tlwExtra->inRepaint = false;
9776 d->repaint_sys(rect);
9783 This version repaints a region \a rgn inside the widget.
9785 void QWidget::repaint(const QRegion &rgn)
9789 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9794 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9797 if (hasBackingStoreSupport()) {
9799 if (qt_widget_private(this)->isInUnifiedToolbar) {
9800 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9804 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9805 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9806 tlwExtra->inRepaint = true;
9807 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9808 tlwExtra->inRepaint = false;
9811 d->repaint_sys(rgn);
9816 Updates the widget unless updates are disabled or the widget is
9819 This function does not cause an immediate repaint; instead it
9820 schedules a paint event for processing when Qt returns to the main
9821 event loop. This permits Qt to optimize for more speed and less
9822 flicker than a call to repaint() does.
9824 Calling update() several times normally results in just one
9827 Qt normally erases the widget's area before the paintEvent() call.
9828 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9829 responsible for painting all its pixels with an opaque color.
9831 \sa repaint(), paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9833 void QWidget::update()
9838 /*! \fn void QWidget::update(int x, int y, int w, int h)
9841 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9848 This version updates a rectangle \a rect inside the widget.
9850 void QWidget::update(const QRect &rect)
9852 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9855 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9856 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9860 if (hasBackingStoreSupport()) {
9862 if (qt_widget_private(this)->isInUnifiedToolbar) {
9863 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9867 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9868 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9869 tlwExtra->backingStoreTracker->markDirty(rect, this);
9871 d_func()->repaint_sys(rect);
9878 This version repaints a region \a rgn inside the widget.
9880 void QWidget::update(const QRegion &rgn)
9882 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9885 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9886 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9890 if (hasBackingStoreSupport()) {
9892 if (qt_widget_private(this)->isInUnifiedToolbar) {
9893 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9897 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9898 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9899 tlwExtra->backingStoreTracker->markDirty(rgn, this);
9901 d_func()->repaint_sys(rgn);
9909 This just sets the corresponding attribute bit to 1 or 0
9911 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9914 if (attribute < int(8*sizeof(uint))) {
9916 data->widget_attributes |= (1<<attribute);
9918 data->widget_attributes &= ~(1<<attribute);
9920 const int x = attribute - 8*sizeof(uint);
9921 const int int_off = x / (8*sizeof(uint));
9923 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9925 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9930 void QWidgetPrivate::macUpdateSizeAttribute()
9933 QEvent event(QEvent::MacSizeChange);
9934 QApplication::sendEvent(q, &event);
9935 for (int i = 0; i < children.size(); ++i) {
9936 QWidget *w = qobject_cast<QWidget *>(children.at(i));
9937 if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
9938 && !q->testAttribute(Qt::WA_MacMiniSize) // no attribute set? inherit from parent
9939 && !w->testAttribute(Qt::WA_MacSmallSize)
9940 && !w->testAttribute(Qt::WA_MacNormalSize))
9941 w->d_func()->macUpdateSizeAttribute();
9948 Sets the attribute \a attribute on this widget if \a on is true;
9949 otherwise clears the attribute.
9953 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9955 if (testAttribute(attribute) == on)
9959 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9960 "QWidget::setAttribute(WidgetAttribute, bool)",
9961 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9963 // ### Don't use PaintOnScreen+paintEngine() to do native painting in some future release
9964 if (attribute == Qt::WA_PaintOnScreen && on && windowType() != Qt::Desktop && !inherits("QGLWidget")) {
9965 // see qwidget_qpa.cpp, ::paintEngine for details
9967 if (d->noPaintOnScreen)
9972 setAttribute_internal(attribute, on, data, d);
9974 switch (attribute) {
9976 #ifndef QT_NO_DRAGANDDROP
9977 case Qt::WA_AcceptDrops: {
9978 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9979 setAttribute(Qt::WA_DropSiteRegistered, true);
9980 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9981 setAttribute(Qt::WA_DropSiteRegistered, false);
9982 QEvent e(QEvent::AcceptDropsChange);
9983 QApplication::sendEvent(this, &e);
9986 case Qt::WA_DropSiteRegistered: {
9987 d->registerDropSite(on);
9988 for (int i = 0; i < d->children.size(); ++i) {
9989 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9990 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9991 w->setAttribute(Qt::WA_DropSiteRegistered, on);
9997 case Qt::WA_NoChildEventsForParent:
9998 d->sendChildEvents = !on;
10000 case Qt::WA_NoChildEventsFromChildren:
10001 d->receiveChildEvents = !on;
10003 case Qt::WA_MacBrushedMetal:
10005 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10006 // fall through since changing the metal attribute affects the opaque size grip.
10007 case Qt::WA_MacOpaqueSizeGrip:
10008 d->macUpdateOpaqueSizeGrip();
10010 case Qt::WA_MacShowFocusRect:
10017 qt_mac_update_mouseTracking(this);
10020 case Qt::WA_MacAlwaysShowToolWindow:
10022 d->macUpdateHideOnSuspend();
10025 case Qt::WA_MacNormalSize:
10026 case Qt::WA_MacSmallSize:
10027 case Qt::WA_MacMiniSize:
10030 // We can only have one of these set at a time
10031 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10032 Qt::WA_MacMiniSize };
10033 for (int i = 0; i < 3; ++i) {
10034 if (MacSizes[i] != attribute)
10035 setAttribute_internal(MacSizes[i], false, data, d);
10037 d->macUpdateSizeAttribute();
10041 case Qt::WA_ShowModal:
10043 // reset modality type to NonModal when clearing WA_ShowModal
10044 data->window_modality = Qt::NonModal;
10045 } else if (data->window_modality == Qt::NonModal) {
10046 // determine the modality type if it hasn't been set prior
10047 // to setting WA_ShowModal. set the default to WindowModal
10048 // if we are the child of a group leader; otherwise use
10049 // ApplicationModal.
10050 QWidget *w = parentWidget();
10053 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10054 w = w->parentWidget();
10058 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10060 : Qt::ApplicationModal;
10061 // Some window managers do not allow us to enter modality after the
10062 // window is visible.The window must be hidden before changing the
10063 // windowModality property and then reshown.
10065 if (testAttribute(Qt::WA_WState_Created)) {
10066 // don't call setModal_sys() before create_sys()
10070 case Qt::WA_MouseTracking: {
10071 QEvent e(QEvent::MouseTrackingChange);
10072 QApplication::sendEvent(this, &e);
10074 case Qt::WA_NativeWindow: {
10075 d->createTLExtra();
10077 QWidget *focusWidget = d->effectiveFocusWidget();
10078 if (on && !internalWinId() && hasFocus()
10079 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10080 qApp->inputMethod()->commit();
10081 qApp->inputMethod()->update(Qt::ImEnabled);
10083 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10085 // On Mac, toolbars inside the unified title bar will never overlap with
10086 // siblings in the content view. So we skip enforce native siblings in that case
10087 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10090 parentWidget()->d_func()->enforceNativeChildren();
10091 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10093 if (isEnabled() && focusWidget->isEnabled()
10094 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10095 qApp->inputMethod()->update(Qt::ImEnabled);
10100 case Qt::WA_PaintOnScreen:
10101 d->updateIsOpaque();
10102 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10103 // Recreate the widget if it's already created as an alien widget and
10104 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10105 // So must their children.
10107 setAttribute(Qt::WA_NativeWindow);
10108 d->enforceNativeChildren();
10112 case Qt::WA_OpaquePaintEvent:
10113 d->updateIsOpaque();
10115 case Qt::WA_NoSystemBackground:
10116 d->updateIsOpaque();
10118 case Qt::WA_UpdatesDisabled:
10119 d->updateSystemBackground();
10121 case Qt::WA_TransparentForMouseEvents:
10123 d->macUpdateIgnoreMouseEvents();
10126 case Qt::WA_InputMethodEnabled: {
10128 if (qApp->focusObject() == this) {
10130 qApp->inputMethod()->commit();
10131 qApp->inputMethod()->update(Qt::ImEnabled);
10136 case Qt::WA_WindowPropagation:
10137 d->resolvePalette();
10139 d->resolveLocale();
10142 case Qt::WA_NoX11EventCompression:
10145 d->extra->compress_events = on;
10147 case Qt::WA_X11OpenGLOverlay:
10148 d->updateIsOpaque();
10150 case Qt::WA_X11DoNotAcceptFocus:
10151 if (testAttribute(Qt::WA_WState_Created))
10152 d->updateX11AcceptFocus();
10155 case Qt::WA_DontShowOnScreen: {
10156 if (on && isVisible()) {
10157 // Make sure we keep the current state and only hide the widget
10158 // from the desktop. show_sys will only update platform specific
10159 // attributes at this point.
10167 case Qt::WA_X11NetWmWindowTypeDesktop:
10168 case Qt::WA_X11NetWmWindowTypeDock:
10169 case Qt::WA_X11NetWmWindowTypeToolBar:
10170 case Qt::WA_X11NetWmWindowTypeMenu:
10171 case Qt::WA_X11NetWmWindowTypeUtility:
10172 case Qt::WA_X11NetWmWindowTypeSplash:
10173 case Qt::WA_X11NetWmWindowTypeDialog:
10174 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10175 case Qt::WA_X11NetWmWindowTypePopupMenu:
10176 case Qt::WA_X11NetWmWindowTypeToolTip:
10177 case Qt::WA_X11NetWmWindowTypeNotification:
10178 case Qt::WA_X11NetWmWindowTypeCombo:
10179 case Qt::WA_X11NetWmWindowTypeDND:
10180 if (testAttribute(Qt::WA_WState_Created))
10181 d->setNetWmWindowTypes();
10185 case Qt::WA_StaticContents:
10186 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10188 bs->addStaticWidget(this);
10190 bs->removeStaticWidget(this);
10193 case Qt::WA_TranslucentBackground:
10195 setAttribute(Qt::WA_NoSystemBackground);
10196 d->updateIsTranslucent();
10200 case Qt::WA_AcceptTouchEvents:
10201 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10203 d->registerTouchWindow();
10211 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10213 Returns true if attribute \a attribute is set on this widget;
10214 otherwise returns false.
10218 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10220 Q_D(const QWidget);
10221 const int x = attribute - 8*sizeof(uint);
10222 const int int_off = x / (8*sizeof(uint));
10223 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10227 \property QWidget::windowOpacity
10229 \brief The level of opacity for the window.
10231 The valid range of opacity is from 1.0 (completely opaque) to
10232 0.0 (completely transparent).
10234 By default the value of this property is 1.0.
10236 This feature is available on Embedded Linux, Mac OS X, Windows,
10237 and X11 platforms that support the Composite extension.
10239 This feature is not available on Windows CE.
10241 Note that under X11 you need to have a composite manager running,
10242 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10243 supported by the window manager you are using.
10245 \warning Changing this property from opaque to transparent might issue a
10246 paint event that needs to be processed before the window is displayed
10247 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10248 that semi-transparent windows update and resize significantly slower than
10253 qreal QWidget::windowOpacity() const
10255 Q_D(const QWidget);
10256 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10259 void QWidget::setWindowOpacity(qreal opacity)
10265 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10266 QTLWExtra *extra = d->topData();
10267 extra->opacity = uint(opacity * 255);
10268 setAttribute(Qt::WA_WState_WindowOpacitySet);
10270 if (!testAttribute(Qt::WA_WState_Created))
10273 #ifndef QT_NO_GRAPHICSVIEW
10274 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10275 // Avoid invalidating the cache if set.
10276 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10278 else if (QGraphicsScene *scene = proxy->scene())
10279 scene->update(proxy->sceneBoundingRect());
10284 d->setWindowOpacity_sys(opacity);
10288 \property QWidget::windowModified
10289 \brief whether the document shown in the window has unsaved changes
10291 A modified window is a window whose content has changed but has
10292 not been saved to disk. This flag will have different effects
10293 varied by the platform. On Mac OS X the close button will have a
10294 modified look; on other platforms, the window title will have an
10297 The window title must contain a "[*]" placeholder, which
10298 indicates where the '*' should appear. Normally, it should appear
10299 right after the file name (e.g., "document1.txt[*] - Text
10300 Editor"). If the window isn't modified, the placeholder is simply
10303 Note that if a widget is set as modified, all its ancestors will
10304 also be set as modified. However, if you call \c
10305 {setWindowModified(false)} on a widget, this will not propagate to
10306 its parent because other children of the parent might have been
10309 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10311 bool QWidget::isWindowModified() const
10313 return testAttribute(Qt::WA_WindowModified);
10316 void QWidget::setWindowModified(bool mod)
10319 setAttribute(Qt::WA_WindowModified, mod);
10321 d->setWindowModified_helper();
10323 QEvent e(QEvent::ModifiedChange);
10324 QApplication::sendEvent(this, &e);
10327 void QWidgetPrivate::setWindowModified_helper()
10330 QWindow *window = q->windowHandle();
10333 QPlatformWindow *platformWindow = window->handle();
10334 if (!platformWindow)
10336 bool on = q->testAttribute(Qt::WA_WindowModified);
10337 if (!platformWindow->setWindowModified(on)) {
10338 if (!q->windowTitle().contains(QLatin1String("[*]")) && on)
10339 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10340 setWindowTitle_helper(q->windowTitle());
10341 setWindowIconText_helper(q->windowIconText());
10345 #ifndef QT_NO_TOOLTIP
10347 \property QWidget::toolTip
10349 \brief the widget's tooltip
10351 Note that by default tooltips are only shown for widgets that are
10352 children of the active window. You can change this behavior by
10353 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10354 not on the widget with the tooltip.
10356 If you want to control a tooltip's behavior, you can intercept the
10357 event() function and catch the QEvent::ToolTip event (e.g., if you
10358 want to customize the area for which the tooltip should be shown).
10360 By default, this property contains an empty string.
10362 \sa QToolTip, statusTip, whatsThis
10364 void QWidget::setToolTip(const QString &s)
10369 QEvent event(QEvent::ToolTipChange);
10370 QApplication::sendEvent(this, &event);
10373 QString QWidget::toolTip() const
10375 Q_D(const QWidget);
10378 #endif // QT_NO_TOOLTIP
10381 #ifndef QT_NO_STATUSTIP
10383 \property QWidget::statusTip
10384 \brief the widget's status tip
10386 By default, this property contains an empty string.
10388 \sa toolTip, whatsThis
10390 void QWidget::setStatusTip(const QString &s)
10396 QString QWidget::statusTip() const
10398 Q_D(const QWidget);
10399 return d->statusTip;
10401 #endif // QT_NO_STATUSTIP
10403 #ifndef QT_NO_WHATSTHIS
10405 \property QWidget::whatsThis
10407 \brief the widget's What's This help text.
10409 By default, this property contains an empty string.
10411 \sa QWhatsThis, QWidget::toolTip, QWidget::statusTip
10413 void QWidget::setWhatsThis(const QString &s)
10419 QString QWidget::whatsThis() const
10421 Q_D(const QWidget);
10422 return d->whatsThis;
10424 #endif // QT_NO_WHATSTHIS
10426 #ifndef QT_NO_ACCESSIBILITY
10428 \property QWidget::accessibleName
10430 \brief the widget's name as seen by assistive technologies
10432 This property is used by accessible clients to identify, find, or announce
10433 the widget for accessible clients.
10435 By default, this property contains an empty string.
10437 \sa QAccessibleInterface::text()
10439 void QWidget::setAccessibleName(const QString &name)
10442 d->accessibleName = name;
10443 QAccessibleEvent event(this, QAccessible::NameChanged);
10444 QAccessible::updateAccessibility(&event);
10447 QString QWidget::accessibleName() const
10449 Q_D(const QWidget);
10450 return d->accessibleName;
10454 \property QWidget::accessibleDescription
10456 \brief the widget's description as seen by assistive technologies
10458 By default, this property contains an empty string.
10460 \sa QAccessibleInterface::text()
10462 void QWidget::setAccessibleDescription(const QString &description)
10465 d->accessibleDescription = description;
10466 QAccessibleEvent event(this, QAccessible::DescriptionChanged);
10467 QAccessible::updateAccessibility(&event);
10470 QString QWidget::accessibleDescription() const
10472 Q_D(const QWidget);
10473 return d->accessibleDescription;
10475 #endif // QT_NO_ACCESSIBILITY
10477 #ifndef QT_NO_SHORTCUT
10479 Adds a shortcut to Qt's shortcut system that watches for the given
10480 \a key sequence in the given \a context. If the \a context is
10481 Qt::ApplicationShortcut, the shortcut applies to the application as a
10482 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10483 or to the window itself, Qt::WindowShortcut.
10485 If the same \a key sequence has been grabbed by several widgets,
10486 when the \a key sequence occurs a QEvent::Shortcut event is sent
10487 to all the widgets to which it applies in a non-deterministic
10488 order, but with the ``ambiguous'' flag set to true.
10490 \warning You should not normally need to use this function;
10491 instead create \l{QAction}s with the shortcut key sequences you
10492 require (if you also want equivalent menu options and toolbar
10493 buttons), or create \l{QShortcut}s if you just need key sequences.
10494 Both QAction and QShortcut handle all the event filtering for you,
10495 and provide signals which are triggered when the user triggers the
10496 key sequence, so are much easier to use than this low-level
10499 \sa releaseShortcut(), setShortcutEnabled()
10501 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10506 setAttribute(Qt::WA_GrabbedShortcut);
10507 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10511 Removes the shortcut with the given \a id from Qt's shortcut
10512 system. The widget will no longer receive QEvent::Shortcut events
10513 for the shortcut's key sequence (unless it has other shortcuts
10514 with the same key sequence).
10516 \warning You should not normally need to use this function since
10517 Qt's shortcut system removes shortcuts automatically when their
10518 parent widget is destroyed. It is best to use QAction or
10519 QShortcut to handle shortcuts, since they are easier to use than
10520 this low-level function. Note also that this is an expensive
10523 \sa grabShortcut(), setShortcutEnabled()
10525 void QWidget::releaseShortcut(int id)
10529 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10533 If \a enable is true, the shortcut with the given \a id is
10534 enabled; otherwise the shortcut is disabled.
10536 \warning You should not normally need to use this function since
10537 Qt's shortcut system enables/disables shortcuts automatically as
10538 widgets become hidden/visible and gain or lose focus. It is best
10539 to use QAction or QShortcut to handle shortcuts, since they are
10540 easier to use than this low-level function.
10542 \sa grabShortcut(), releaseShortcut()
10544 void QWidget::setShortcutEnabled(int id, bool enable)
10548 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10554 If \a enable is true, auto repeat of the shortcut with the
10555 given \a id is enabled; otherwise it is disabled.
10557 \sa grabShortcut(), releaseShortcut()
10559 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10563 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10565 #endif // QT_NO_SHORTCUT
10568 Updates the widget's micro focus.
10570 void QWidget::updateMicroFocus()
10572 // updating everything since this is currently called for any kind of state change
10573 qApp->inputMethod()->update(Qt::ImQueryAll);
10577 Raises this widget to the top of the parent widget's stack.
10579 After this call the widget will be visually in front of any
10580 overlapping sibling widgets.
10582 \note When using activateWindow(), you can call this function to
10583 ensure that the window is stacked on top.
10585 \sa lower(), stackUnder()
10588 void QWidget::raise()
10592 QWidget *p = parentWidget();
10593 const int parentChildCount = p->d_func()->children.size();
10594 if (parentChildCount < 2)
10596 const int from = p->d_func()->children.indexOf(this);
10597 Q_ASSERT(from >= 0);
10598 // Do nothing if the widget is already in correct stacking order _and_ created.
10599 if (from != parentChildCount -1)
10600 p->d_func()->children.move(from, parentChildCount - 1);
10601 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10603 else if (from == parentChildCount - 1)
10606 QRegion region(rect());
10607 d->subtractOpaqueSiblings(region);
10608 d->invalidateBuffer(region);
10610 if (testAttribute(Qt::WA_WState_Created))
10613 QEvent e(QEvent::ZOrderChange);
10614 QApplication::sendEvent(this, &e);
10618 Lowers the widget to the bottom of the parent widget's stack.
10620 After this call the widget will be visually behind (and therefore
10621 obscured by) any overlapping sibling widgets.
10623 \sa raise(), stackUnder()
10626 void QWidget::lower()
10630 QWidget *p = parentWidget();
10631 const int parentChildCount = p->d_func()->children.size();
10632 if (parentChildCount < 2)
10634 const int from = p->d_func()->children.indexOf(this);
10635 Q_ASSERT(from >= 0);
10636 // Do nothing if the widget is already in correct stacking order _and_ created.
10638 p->d_func()->children.move(from, 0);
10639 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10641 else if (from == 0)
10644 if (testAttribute(Qt::WA_WState_Created))
10647 QEvent e(QEvent::ZOrderChange);
10648 QApplication::sendEvent(this, &e);
10653 Places the widget under \a w in the parent widget's stack.
10655 To make this work, the widget itself and \a w must be siblings.
10657 \sa raise(), lower()
10659 void QWidget::stackUnder(QWidget* w)
10662 QWidget *p = parentWidget();
10663 if (!w || isWindow() || p != w->parentWidget() || this == w)
10666 int from = p->d_func()->children.indexOf(this);
10667 int to = p->d_func()->children.indexOf(w);
10668 Q_ASSERT(from >= 0);
10672 // Do nothing if the widget is already in correct stacking order _and_ created.
10674 p->d_func()->children.move(from, to);
10675 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10677 else if (from == to)
10680 if (testAttribute(Qt::WA_WState_Created))
10681 d->stackUnder_sys(w);
10683 QEvent e(QEvent::ZOrderChange);
10684 QApplication::sendEvent(this, &e);
10689 \fn bool QWidget::isTopLevel() const
10692 Use isWindow() instead.
10696 \fn bool QWidget::isRightToLeft() const
10701 \fn bool QWidget::isLeftToRight() const
10706 \macro QWIDGETSIZE_MAX
10709 Defines the maximum size for a QWidget object.
10711 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10712 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10714 \sa QWidget::setMaximumSize()
10718 \fn QWidget::setupUi(QWidget *widget)
10720 Sets up the user interface for the specified \a widget.
10722 \note This function is available with widgets that derive from user
10723 interface descriptions created using \l{uic}.
10725 \sa {Using a Designer UI File in Your Application}
10728 QRect QWidgetPrivate::frameStrut() const
10730 Q_Q(const QWidget);
10731 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10732 // x2 = x1 + w - 1, so w/h = 1
10733 return QRect(0, 0, 1, 1);
10736 if (data.fstrut_dirty
10738 // ### Fix properly for 4.3
10741 && q->testAttribute(Qt::WA_WState_Created))
10742 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10744 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10747 #ifdef QT_KEYPAD_NAVIGATION
10751 Changes the focus from the current focusWidget to a widget in
10754 Returns true, if there was a widget in that direction
10756 bool QWidgetPrivate::navigateToDirection(Direction direction)
10758 QWidget *targetWidget = widgetInNavigationDirection(direction);
10760 targetWidget->setFocus();
10761 return (targetWidget != 0);
10767 Searches for a widget that is positioned in the \a direction, starting
10768 from the current focusWidget.
10770 Returns the pointer to a found widget or 0, if there was no widget in
10773 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10775 const QWidget *sourceWidget = QApplication::focusWidget();
10778 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10779 const int sourceX =
10780 (direction == DirectionNorth || direction == DirectionSouth) ?
10781 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10782 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10783 const int sourceY =
10784 (direction == DirectionEast || direction == DirectionWest) ?
10785 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10786 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10787 const QPoint sourcePoint(sourceX, sourceY);
10788 const QPoint sourceCenter = sourceRect.center();
10789 const QWidget *sourceWindow = sourceWidget->window();
10791 QWidget *targetWidget = 0;
10792 int shortestDistance = INT_MAX;
10793 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10795 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10797 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10798 // but the owner of the proxy cannot.
10799 // Additionally, empty widgets should be ignored.
10800 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10803 // Only navigate to a target widget that...
10804 if ( targetCandidate != sourceWidget
10805 // ...takes the focus,
10806 && targetCandidate->focusPolicy() & Qt::TabFocus
10807 // ...is above if DirectionNorth,
10808 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10809 // ...is on the right if DirectionEast,
10810 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
10811 // ...is below if DirectionSouth,
10812 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
10813 // ...is on the left if DirectionWest,
10814 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
10816 && targetCandidate->isEnabled()
10818 && targetCandidate->isVisible()
10819 // ...is in the same window,
10820 && targetCandidate->window() == sourceWindow) {
10821 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10822 if (targetCandidateDistance < shortestDistance) {
10823 shortestDistance = targetCandidateDistance;
10824 targetWidget = targetCandidate;
10828 return targetWidget;
10834 Tells us if it there is currently a reachable widget by keypad navigation in
10835 a certain \a orientation.
10836 If no navigation is possible, occurring key events in that \a orientation may
10837 be used to interact with the value in the focused widget, even though it
10838 currently has not the editFocus.
10840 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10842 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10844 return orientation == Qt::Horizontal?
10845 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10846 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10847 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10848 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10853 Checks, if the \a widget is inside a QTabWidget. If is is inside
10854 one, left/right key events will be used to switch between tabs in keypad
10855 navigation. If there is no QTabWidget, the horizontal key events can be used
10857 interact with the value in the focused widget, even though it currently has
10860 \sa QWidget::hasEditFocus()
10862 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10864 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10865 if (qobject_cast<const QTabWidget*>(tabWidget))
10875 Sets the backing store to be the \a store specified.
10876 The QWidget will take ownership of the \a store.
10878 void QWidget::setBackingStore(QBackingStore *store)
10880 // ### createWinId() ??
10887 QTLWExtra *topData = d->topData();
10888 if (topData->backingStore == store)
10891 QBackingStore *oldStore = topData->backingStore;
10892 delete topData->backingStore;
10893 topData->backingStore = store;
10895 QWidgetBackingStore *bs = d->maybeBackingStore();
10899 if (isTopLevel()) {
10900 if (bs->store != oldStore && bs->store != store)
10909 Returns the QBackingStore this widget will be drawn into.
10911 QBackingStore *QWidget::backingStore() const
10913 Q_D(const QWidget);
10914 QTLWExtra *extra = d->maybeTopData();
10915 if (extra && extra->backingStore)
10916 return extra->backingStore;
10918 QWidgetBackingStore *bs = d->maybeBackingStore();
10920 return bs ? bs->store : 0;
10923 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10926 *left = (int)leftLayoutItemMargin;
10928 *top = (int)topLayoutItemMargin;
10930 *right = (int)rightLayoutItemMargin;
10932 *bottom = (int)bottomLayoutItemMargin;
10935 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10937 if (leftLayoutItemMargin == left
10938 && topLayoutItemMargin == top
10939 && rightLayoutItemMargin == right
10940 && bottomLayoutItemMargin == bottom)
10944 leftLayoutItemMargin = (signed char)left;
10945 topLayoutItemMargin = (signed char)top;
10946 rightLayoutItemMargin = (signed char)right;
10947 bottomLayoutItemMargin = (signed char)bottom;
10948 q->updateGeometry();
10951 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10954 QStyleOption myOpt;
10957 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
10961 QRect liRect = q->style()->subElementRect(element, opt, q);
10962 if (liRect.isValid()) {
10963 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10964 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10965 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10966 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10968 leftLayoutItemMargin = 0;
10969 topLayoutItemMargin = 0;
10970 rightLayoutItemMargin = 0;
10971 bottomLayoutItemMargin = 0;
10974 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10975 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10979 if (!q->parentWidget()) {
10980 Qt::WindowType type = q->windowType();
10981 if (type == Qt::Widget || type == Qt::SubWindow)
10983 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10984 q->setAttribute(Qt::WA_QuitOnClose, false);
10990 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10992 return widget->data;
10995 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10997 return widget->d_func();
11001 #ifndef QT_NO_GRAPHICSVIEW
11005 Returns the proxy widget for the corresponding embedded widget in a graphics
11006 view; otherwise returns 0.
11008 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11009 QGraphicsScene::addWidget()
11011 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11013 Q_D(const QWidget);
11015 return d->extra->proxyWidget;
11021 #ifndef QT_NO_GESTURES
11023 Subscribes the widget to a given \a gesture with specific \a flags.
11025 \sa ungrabGesture(), QGestureEvent
11028 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11031 d->gestureContext.insert(gesture, flags);
11032 (void)QGestureManager::instance(); // create a gesture manager
11036 Unsubscribes the widget from a given \a gesture type
11038 \sa grabGesture(), QGestureEvent
11041 void QWidget::ungrabGesture(Qt::GestureType gesture)
11044 if (d->gestureContext.remove(gesture)) {
11045 if (QGestureManager *manager = QGestureManager::instance())
11046 manager->cleanupCachedGestures(this, gesture);
11049 #endif // QT_NO_GESTURES
11052 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11054 Frees up window system resources. Destroys the widget window if \a
11055 destroyWindow is true.
11057 destroy() calls itself recursively for all the child widgets,
11058 passing \a destroySubWindows for the \a destroyWindow parameter.
11059 To have more control over destruction of subwidgets, destroy
11060 subwidgets selectively first.
11062 This function is usually called from the QWidget destructor.
11066 \fn QPaintEngine *QWidget::paintEngine() const
11068 Returns the widget's paint engine.
11070 Note that this function should not be called explicitly by the
11071 user, since it's meant for reimplementation purposes only. The
11072 function is called by Qt internally, and the default
11073 implementation may not always return a valid pointer.
11077 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11079 Translates the widget coordinate \a pos to global screen
11080 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11081 the global coordinates of the top-left pixel of the widget.
11083 \sa mapFromGlobal(), mapTo(), mapToParent()
11087 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11089 Translates the global screen coordinate \a pos to widget
11092 \sa mapToGlobal(), mapFrom(), mapFromParent()
11096 \fn void QWidget::grabMouse()
11098 Grabs the mouse input.
11100 This widget receives all mouse events until releaseMouse() is
11101 called; other widgets get no mouse events at all. Keyboard
11102 events are not affected. Use grabKeyboard() if you want to grab
11105 \warning Bugs in mouse-grabbing applications very often lock the
11106 terminal. Use this function with extreme caution, and consider
11107 using the \c -nograb command line option while debugging.
11109 It is almost never necessary to grab the mouse when using Qt, as
11110 Qt grabs and releases it sensibly. In particular, Qt grabs the
11111 mouse when a mouse button is pressed and keeps it until the last
11112 button is released.
11114 \note Only visible widgets can grab mouse input. If isVisible()
11115 returns false for a widget, that widget cannot call grabMouse().
11117 \note \b{(Mac OS X developers)} For \e Cocoa, calling
11118 grabMouse() on a widget only works when the mouse is inside the
11119 frame of that widget. For \e Carbon, it works outside the widget's
11120 frame as well, like for Windows and X11.
11122 \sa releaseMouse(), grabKeyboard(), releaseKeyboard()
11126 \fn void QWidget::grabMouse(const QCursor &cursor)
11127 \overload grabMouse()
11129 Grabs the mouse input and changes the cursor shape.
11131 The cursor will assume shape \a cursor (for as long as the mouse
11132 focus is grabbed) and this widget will be the only one to receive
11133 mouse events until releaseMouse() is called().
11135 \warning Grabbing the mouse might lock the terminal.
11137 \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11139 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11143 \fn void QWidget::releaseMouse()
11145 Releases the mouse grab.
11147 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11151 \fn void QWidget::grabKeyboard()
11153 Grabs the keyboard input.
11155 This widget receives all keyboard events until releaseKeyboard()
11156 is called; other widgets get no keyboard events at all. Mouse
11157 events are not affected. Use grabMouse() if you want to grab that.
11159 The focus widget is not affected, except that it doesn't receive
11160 any keyboard events. setFocus() moves the focus as usual, but the
11161 new focus widget receives keyboard events only after
11162 releaseKeyboard() is called.
11164 If a different widget is currently grabbing keyboard input, that
11165 widget's grab is released first.
11167 \sa releaseKeyboard(), grabMouse(), releaseMouse(), focusWidget()
11171 \fn void QWidget::releaseKeyboard()
11173 Releases the keyboard grab.
11175 \sa grabKeyboard(), grabMouse(), releaseMouse()
11179 \fn QWidget *QWidget::mouseGrabber()
11181 Returns the widget that is currently grabbing the mouse input.
11183 If no widget in this application is currently grabbing the mouse,
11186 \sa grabMouse(), keyboardGrabber()
11190 \fn QWidget *QWidget::keyboardGrabber()
11192 Returns the widget that is currently grabbing the keyboard input.
11194 If no widget in this application is currently grabbing the
11195 keyboard, 0 is returned.
11197 \sa grabMouse(), mouseGrabber()
11201 \fn void QWidget::activateWindow()
11203 Sets the top-level widget containing this widget to be the active
11206 An active window is a visible top-level window that has the
11207 keyboard input focus.
11209 This function performs the same operation as clicking the mouse on
11210 the title bar of a top-level window. On X11, the result depends on
11211 the Window Manager. If you want to ensure that the window is
11212 stacked on top as well you should also call raise(). Note that the
11213 window must be visible, otherwise activateWindow() has no effect.
11215 On Windows, if you are calling this when the application is not
11216 currently the active one then it will not make it the active
11217 window. It will change the color of the taskbar entry to indicate
11218 that the window has changed in some way. This is because Microsoft
11219 does not allow an application to interrupt what the user is currently
11220 doing in another application.
11222 \sa isActiveWindow(), window(), show()
11226 \fn int QWidget::metric(PaintDeviceMetric m) const
11228 Internal implementation of the virtual QPaintDevice::metric()
11231 \a m is the metric to get.
11235 Initializes the \a painter pen, background and font to the same as
11236 the given widget's. This function is called automatically when the
11237 painter is opened on a QWidget.
11239 void QWidget::initPainter(QPainter *painter) const
11241 const QPalette &pal = palette();
11242 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 1);
11243 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11244 QFont f(font(), const_cast<QWidget *>(this));
11245 painter->d_func()->state->deviceFont = f;
11246 painter->d_func()->state->font = f;
11249 QPaintDevice *QWidget::redirected(QPoint *offset) const
11251 return d_func()->redirected(offset);
11254 QPainter *QWidget::sharedPainter() const
11256 // Someone sent a paint event directly to the widget
11257 if (!d_func()->redirectDev)
11260 QPainter *sp = d_func()->sharedPainter();
11261 if (!sp || !sp->isActive())
11264 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11271 \fn void QWidget::setMask(const QRegion ®ion)
11274 Causes only the parts of the widget which overlap \a region to be
11275 visible. If the region includes pixels outside the rect() of the
11276 widget, window system controls in that area may or may not be
11277 visible, depending on the platform.
11279 Note that this effect can be slow if the region is particularly
11284 void QWidget::setMask(const QRegion &newMask)
11289 if (newMask == d->extra->mask)
11292 #ifndef QT_NO_BACKINGSTORE
11293 const QRegion oldMask(d->extra->mask);
11296 d->extra->mask = newMask;
11297 d->extra->hasMask = !newMask.isEmpty();
11300 if (!testAttribute(Qt::WA_WState_Created))
11304 d->setMask_sys(newMask);
11306 #ifndef QT_NO_BACKINGSTORE
11310 if (!d->extra->hasMask) {
11311 // Mask was cleared; update newly exposed area.
11312 QRegion expose(rect());
11314 if (!expose.isEmpty()) {
11315 d->setDirtyOpaqueRegion();
11322 // Update newly exposed area on the parent widget.
11323 QRegion parentExpose(rect());
11324 parentExpose -= newMask;
11325 if (!parentExpose.isEmpty()) {
11326 d->setDirtyOpaqueRegion();
11327 parentExpose.translate(data->crect.topLeft());
11328 parentWidget()->update(parentExpose);
11331 // Update newly exposed area on this widget
11332 if (!oldMask.isEmpty())
11333 update(newMask - oldMask);
11339 \fn void QWidget::setMask(const QBitmap &bitmap)
11341 Causes only the pixels of the widget for which \a bitmap has a
11342 corresponding 1 bit to be visible. If the region includes pixels
11343 outside the rect() of the widget, window system controls in that
11344 area may or may not be visible, depending on the platform.
11346 Note that this effect can be slow if the region is particularly
11349 The following code shows how an image with an alpha channel can be
11350 used to generate a mask for a widget:
11352 \snippet widget-mask/main.cpp 0
11354 The label shown by this code is masked using the image it contains,
11355 giving the appearance that an irregularly-shaped image is being drawn
11356 directly onto the screen.
11358 Masked widgets receive mouse events only on their visible
11361 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11363 void QWidget::setMask(const QBitmap &bitmap)
11365 setMask(QRegion(bitmap));
11369 \fn void QWidget::clearMask()
11371 Removes any mask set by setMask().
11375 void QWidget::clearMask()
11377 setMask(QRegion());
11381 void QWidgetPrivate::syncUnifiedMode() {
11382 // The whole purpose of this method is to keep the unifiedToolbar in sync.
11383 // That means making sure we either exchange the drawing methods or we let
11384 // the toolbar know that it does not require to draw the baseline.
11386 // This function makes sense only if this is a top level
11389 OSWindowRef window = qt_mac_window_for(q);
11390 if(changeMethods) {
11391 // Ok, we are in documentMode.
11392 if(originalDrawMethod)
11393 qt_mac_replaceDrawRect(window, this);
11395 if(!originalDrawMethod)
11396 qt_mac_replaceDrawRectOriginal(window, this);
11404 #include "moc_qwidget.cpp"