QtWidgets: cleanup several Q3* items
[profile/ivi/qtbase.git] / src / widgets / kernel / qwidget.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qapplication.h"
43 #include "qapplication_p.h"
44 #include "qbrush.h"
45 #include "qcursor.h"
46 #include "qdesktopwidget.h"
47 #include "qevent.h"
48 #include "qhash.h"
49 #include "qlayout.h"
50 #include "qmenu.h"
51 #include "qmetaobject.h"
52 #include "qpixmap.h"
53 #include "qpointer.h"
54 #include "qstack.h"
55 #include "qstyle.h"
56 #include "qstylefactory.h"
57 #include "qvariant.h"
58 #include "qwidget.h"
59 #include "qstyleoption.h"
60 #ifndef QT_NO_ACCESSIBILITY
61 # include "qaccessible.h"
62 #endif
63 #ifdef Q_WS_MAC
64 # include "qt_mac_p.h"
65 # include "qt_cocoa_helpers_mac_p.h"
66 # include "qmainwindow.h"
67 # include "qtoolbar.h"
68 # include <private/qmainwindowlayout_p.h>
69 #endif
70 #include "qplatformwindow_qpa.h"
71 #include "private/qwidgetwindow_qpa_p.h"
72 #include "qpainter.h"
73 #include "qtooltip.h"
74 #include "qwhatsthis.h"
75 #include "qdebug.h"
76 #include "private/qstylesheetstyle_p.h"
77 #include "private/qstyle_p.h"
78 #include "qfileinfo.h"
79 #include "private/qsoftkeymanager_p.h"
80 #include <QtGui/qinputmethod.h>
81
82 #include <private/qgraphicseffect_p.h>
83 #include <qbackingstore.h>
84 #include <private/qwidgetbackingstore_p.h>
85 #ifdef Q_WS_MAC
86 # include <private/qpaintengine_mac_p.h>
87 #endif
88 #include <private/qpaintengine_raster_p.h>
89
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"
100
101 #include "private/qgesturemanager_p.h"
102
103 #ifdef QT_KEYPAD_NAVIGATION
104 #include "qtabwidget.h" // Needed in inTabWidget()
105 #endif // QT_KEYPAD_NAVIGATION
106
107
108 // widget/widget data creation count
109 //#define QWIDGET_EXTRA_DEBUG
110 //#define ALIEN_DEBUG
111
112 QT_BEGIN_NAMESPACE
113
114 static bool qt_enable_backingstore = true;
115 #ifdef Q_WS_X11
116 // for compatibility with Qt 4.0
117 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
118 {
119     qt_enable_backingstore = enable;
120 }
121 #endif
122
123 #ifdef Q_WS_MAC
124 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
125 #endif
126
127 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
128 {
129     return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
130             qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
131 }
132
133 static inline bool hasBackingStoreSupport()
134 {
135     return true;
136 }
137
138 #ifdef Q_WS_MAC
139 #  define QT_NO_PAINT_DEBUG
140 #endif
141
142 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
143 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
144
145 /*!
146     \internal
147     \class QWidgetBackingStoreTracker
148     \brief Class which allows tracking of which widgets are using a given backing store
149
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.
153  */
154
155 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
156     :   m_ptr(0)
157 {
158
159 }
160
161 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
162 {
163     delete m_ptr;
164 }
165
166 /*!
167     \internal
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
170     the QWidget.
171  */
172 void QWidgetBackingStoreTracker::create(QWidget *widget)
173 {
174     destroy();
175     m_ptr = new QWidgetBackingStore(widget);
176 }
177
178 /*!
179     \internal
180     Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181     widgets using the backing store.
182  */
183 void QWidgetBackingStoreTracker::destroy()
184 {
185     delete m_ptr;
186     m_ptr = 0;
187     m_widgets.clear();
188 }
189
190 /*!
191     \internal
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.
194  */
195 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
196 {
197     Q_ASSERT(m_ptr);
198     Q_ASSERT(w->internalWinId());
199     Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
200     m_widgets.insert(w);
201 }
202
203 /*!
204     \internal
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.
209  */
210 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
211 {
212     if (m_widgets.remove(w) && m_widgets.isEmpty()) {
213         delete m_ptr;
214         m_ptr = 0;
215     }
216 }
217
218 /*!
219     \internal
220     Recursively remove widget and all of its descendents.
221  */
222 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
223 {
224     unregisterWidget(widget);
225     foreach (QObject *child, widget->children())
226         if (QWidget *childWidget = qobject_cast<QWidget *>(child))
227             unregisterWidgetSubtree(childWidget);
228 }
229
230 QWidgetPrivate::QWidgetPrivate(int version)
231     : QObjectPrivate(version)
232       , extra(0)
233       , focus_next(0)
234       , focus_prev(0)
235       , focus_child(0)
236       , layout(0)
237       , needsFlush(0)
238       , redirectDev(0)
239       , widgetItem(0)
240       , extraPaintEngine(0)
241       , polished(0)
242       , graphicsEffect(0)
243 #if !defined(QT_NO_IM)
244       , imHints(Qt::ImhNone)
245 #endif
246       , inheritedFontResolveMask(0)
247       , inheritedPaletteResolveMask(0)
248       , leftmargin(0)
249       , topmargin(0)
250       , rightmargin(0)
251       , bottommargin(0)
252       , leftLayoutItemMargin(0)
253       , topLayoutItemMargin(0)
254       , rightLayoutItemMargin(0)
255       , bottomLayoutItemMargin(0)
256       , hd(0)
257       , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
258       , fg_role(QPalette::NoRole)
259       , bg_role(QPalette::NoRole)
260       , dirtyOpaqueChildren(1)
261       , isOpaque(0)
262       , inDirtyList(0)
263       , isScrolled(0)
264       , isMoved(0)
265       , isGLWidget(0)
266       , usesDoubleBufferedGLContext(0)
267 #ifndef QT_NO_IM
268       , inheritsInputMethodHints(0)
269 #endif
270       , inSetParent(0)
271 #if defined(Q_WS_X11)
272       , picture(0)
273 #elif defined(Q_WS_WIN)
274       , noPaintOnScreen(0)
275   #ifndef QT_NO_GESTURES
276       , nativeGesturePanEnabled(0)
277   #endif
278 #elif defined(Q_WS_MAC)
279       , needWindowChange(0)
280       , window_event(0)
281       , qd_hd(0)
282 #endif
283 {
284     if (!qApp) {
285         qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
286         return;
287     }
288
289     if (version != QObjectPrivateVersion)
290         qFatal("Cannot mix incompatible Qt libraries");
291
292     isWidget = true;
293     memset(high_attributes, 0, sizeof(high_attributes));
294 #ifdef Q_WS_MAC
295     drawRectOriginalAdded = false;
296     originalDrawMethod = true;
297     changeMethods = false;
298     isInUnifiedToolbar = false;
299     unifiedSurface = 0;
300     toolbar_ancestor = 0;
301     flushRequested = false;
302     touchEventsEnabled = false;
303 #endif // Q_WS_MAC
304 #ifdef QWIDGET_EXTRA_DEBUG
305     static int count = 0;
306     qDebug() << "widgets" << ++count;
307 #endif
308 }
309
310
311 QWidgetPrivate::~QWidgetPrivate()
312 {
313     if (widgetItem)
314         widgetItem->wid = 0;
315
316     if (extra)
317         deleteExtra();
318
319 #ifndef QT_NO_GRAPHICSEFFECT
320     delete graphicsEffect;
321 #endif //QT_NO_GRAPHICSEFFECT
322 }
323
324 /*!
325     \internal
326 */
327 void QWidgetPrivate::scrollChildren(int dx, int dy)
328 {
329     Q_Q(QWidget);
330     if (q->children().size() > 0) {        // scroll children
331         QPoint pd(dx, dy);
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());
338                 w->data->crect = r;
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);
344             }
345         }
346     }
347 }
348
349 void QWidgetPrivate::updateWidgetTransform()
350 {
351     Q_Q(QWidget);
352     if (q == qGuiApp->focusObject()) {
353         QTransform t;
354         QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
355         t.translate(p.x(), p.y());
356         qApp->inputMethod()->setInputItemTransform(t);
357     }
358 }
359
360 #ifdef QT_KEYPAD_NAVIGATION
361 QPointer<QWidget> QWidgetPrivate::editingWidget;
362
363 /*!
364     Returns true if this widget currently has edit focus; otherwise false.
365
366     This feature is only available in Qt for Embedded Linux.
367
368     \sa setEditFocus(), QApplication::keypadNavigationEnabled()
369 */
370 bool QWidget::hasEditFocus() const
371 {
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;
376 }
377
378 /*!
379     \fn void QWidget::setEditFocus(bool enable)
380
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
384     change focus.
385
386     This feature is only available in Qt for Embedded Linux.
387
388     \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
389 */
390 void QWidget::setEditFocus(bool on)
391 {
392     QWidget *f = this;
393     while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
394         f = f->d_func()->extra->focus_proxy;
395
396     if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
397         QWidgetPrivate::editingWidget->setEditFocus(false);
398
399     if (on && !f->hasFocus())
400         f->setFocus();
401
402     if ((!on && !QWidgetPrivate::editingWidget)
403         || (on && QWidgetPrivate::editingWidget == f)) {
404         return;
405     }
406
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);
412     } else if (on) {
413         QWidgetPrivate::editingWidget = f;
414         QEvent event(QEvent::EnterEditFocus);
415         QApplication::sendEvent(f, &event);
416         QApplication::sendEvent(f->style(), &event);
417     }
418 }
419 #endif
420
421 /*!
422     \property QWidget::autoFillBackground
423     \brief whether the widget background is filled automatically
424     \since 4.1
425
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}.
429
430     In addition, Windows are always filled with QPalette::Window, unless the
431     WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
432
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.
435
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.
439
440     By default, this property is false.
441
442     \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
443     {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
444 */
445 bool QWidget::autoFillBackground() const
446 {
447     Q_D(const QWidget);
448     return d->extra && d->extra->autoFillBackground;
449 }
450
451 void QWidget::setAutoFillBackground(bool enabled)
452 {
453     Q_D(QWidget);
454     if (!d->extra)
455         d->createExtra();
456     if (d->extra->autoFillBackground == enabled)
457         return;
458
459     d->extra->autoFillBackground = enabled;
460     d->updateIsOpaque();
461     update();
462     d->updateIsOpaque();
463 }
464
465 /*!
466     \class QWidget
467     \brief The QWidget class is the base class of all user interface objects.
468
469     \ingroup basicwidgets
470     \inmodule QtWidgets
471
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
476     it.
477
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.
483
484     Every widget's constructor accepts one or two standard arguments:
485
486     \list 1
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
494             special flags.
495     \endlist
496
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.
501
502
503     \section1 Top-Level and Child Widgets
504
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.
508
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.
513
514     \image parent-child-widgets.png A parent widget containing various child widgets.
515
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.
519
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
522     information.
523
524
525     \section1 Composite Widgets
526
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 \l{Qt Designer}.
532
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}.
538
539
540     \section1 Custom Widgets and Painting
541
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.
548
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.
552
553     The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
554     can handle paint events.
555
556
557     \section1 Size Hints and Size Policies
558
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().
562
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.
565
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
570     widgets.
571
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
574     inadequate.
575
576
577     \section1 Events
578
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.
582
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
586     mousePressEvent().
587
588     The \l{widgets/scribble}{Scribble example} implements a wider set of
589     events to handle mouse movement, button presses, and window resizing.
590
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:
594
595     \list
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.)
623     \endlist
624
625     Widgets that accept keyboard input need to reimplement a few more event
626     handlers:
627
628     \list
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             \key Tab and \key 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
634             QWidget::event().
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
638             way.
639         \li  focusOutEvent() is called when the widget loses keyboard focus.
640     \endlist
641
642     You may be required to also reimplement some of the less common event
643     handlers:
644
645     \list
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 \key Tab and \key 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
662             children.)
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
665             leaveEvent().
666         \li  moveEvent() is called when the widget has been moved relative to
667             its parent.
668         \li  closeEvent() is called when the user closes the widget (or when
669             close() is called).
670     \endlist
671
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()
674     directly.
675
676     The default implementation of event() handles \key Tab and \key 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.
679
680     Events and the mechanism used to deliver them are covered in 
681     \l{The Event System}.
682
683     \section1 Groups of Functions and Properties
684
685     \table
686     \header \li Context \li Functions and Properties
687
688     \row \li Window functions \li
689         show(),
690         hide(),
691         raise(),
692         lower(),
693         close().
694
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(),
699         showNormal().
700
701     \row \li Window contents \li
702         update(),
703         repaint(),
704         scroll().
705
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,
711         adjustSize(),
712         mapFromGlobal(), mapToGlobal(),
713         mapFromParent(), mapToParent(),
714         \l maximumSize, \l minimumSize, \l sizeIncrement,
715         \l baseSize, setFixedSize()
716
717     \row \li Mode \li
718         \l visible, isVisibleTo(),
719         \l enabled, isEnabledTo(),
720         \l modal,
721         isWindow(),
722         \l mouseTracking,
723         \l updatesEnabled,
724         visibleRegion().
725
726     \row \li Look and feel \li
727         style(),
728         setStyle(),
729         \l styleSheet,
730         \l cursor,
731         \l font,
732         \l palette,
733         backgroundRole(), setBackgroundRole(),
734         fontInfo(), fontMetrics().
735
736     \row \li Keyboard focus functions \li
737         \l focus, \l focusPolicy,
738         setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
739         focusNextChild(), focusPreviousChild().
740
741     \row \li Mouse and keyboard grabbing \li
742         grabMouse(), releaseMouse(),
743         grabKeyboard(), releaseKeyboard(),
744         mouseGrabber(), keyboardGrabber().
745
746     \row \li Event handlers \li
747         event(),
748         mousePressEvent(),
749         mouseReleaseEvent(),
750         mouseDoubleClickEvent(),
751         mouseMoveEvent(),
752         keyPressEvent(),
753         keyReleaseEvent(),
754         focusInEvent(),
755         focusOutEvent(),
756         wheelEvent(),
757         enterEvent(),
758         leaveEvent(),
759         paintEvent(),
760         moveEvent(),
761         resizeEvent(),
762         closeEvent(),
763         dragEnterEvent(),
764         dragMoveEvent(),
765         dragLeaveEvent(),
766         dropEvent(),
767         childEvent(),
768         showEvent(),
769         hideEvent(),
770         customEvent().
771         changeEvent(),
772
773     \row \li System functions \li
774         parentWidget(), window(), setParent(), winId(),
775         find(), metric().
776
777     \row \li Interactive help \li
778         setToolTip(), setWhatsThis()
779
780     \endtable
781
782
783     \section1 Widget Style Sheets
784
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.
791
792     The use of widget style sheets is described in more detail in the
793     \l{Qt Style Sheets} document.
794
795
796     \section1 Transparency and Double Buffering
797
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
800     flicker.
801
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.
810
811     \image propagation-custom.png
812
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:
817
818     \list
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.
835     \endlist
836
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().
842
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.
847
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.
852
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
856     below.
857
858     \image propagation-standard.png
859
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.
864
865
866     \section1 Creating Translucent Windows
867
868     Since Qt 4.5, it has been possible to create windows with translucent regions
869     on window systems that support compositing.
870
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.
874
875     Platform notes:
876
877     \list
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.
882     \endlist
883
884
885     \section1 Native Widgets vs Alien Widgets
886
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.
890
891     Should you require the old behavior with native windows, you can choose
892     one of the following options:
893
894     \list 1
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
903             (this implies 3).
904     \endlist
905
906     \sa QEvent, QPainter, QGridLayout, QBoxLayout
907
908     \section1 Softkeys
909
910     Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
911     other visual representation on the screen that is generally located next to its
912     physical counterpart. They are most often found on mobile phone platforms. In
913     modern touch based user interfaces it is also possible to have softkeys that do
914     not correspond to any physical keys. Softkeys differ from other onscreen labels
915     in that they are contextual.
916
917     In Qt, contextual softkeys are added to a widget by calling addAction() and
918     passing a \c QAction with a softkey role set on it. When the widget
919     containing the softkey actions has focus, its softkeys should appear in
920     the user interface. Softkeys are discovered by traversing the widget
921     hierarchy so it is possible to define a single set of softkeys that are
922     present at all times by calling addAction() for a given top level widget.
923
924     On some platforms, this concept overlaps with \c QMenuBar such that if no
925     other softkeys are found and the top level widget is a QMainWindow containing
926     a QMenuBar, the menubar actions may appear on one of the softkeys.
927
928     Note: Currently softkeys are only supported on the Symbian Platform.
929
930     \sa addAction(), QAction, QMenuBar
931
932 */
933
934 QWidgetMapper *QWidgetPrivate::mapper = 0;          // widget with wid
935 QWidgetSet *QWidgetPrivate::allWidgets = 0;         // widgets with no wid
936
937
938 /*****************************************************************************
939   QWidget utility functions
940  *****************************************************************************/
941
942 QRegion qt_dirtyRegion(QWidget *widget)
943 {
944     if (!widget)
945         return QRegion();
946
947     QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
948     if (!bs)
949         return QRegion();
950
951     return bs->dirtyRegion(widget);
952 }
953
954 /*****************************************************************************
955   QWidget member functions
956  *****************************************************************************/
957
958 /*
959     Widget state flags:
960   \list
961   \li Qt::WA_WState_Created The widget has a valid winId().
962   \li Qt::WA_WState_Visible The widget is currently visible.
963   \li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
964   become visible unless you call show() on it. Qt::WA_WState_Hidden
965   implies !Qt::WA_WState_Visible.
966   \li Qt::WA_WState_CompressKeys Compress keyboard events.
967   \li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
968   \li Qt::WA_WState_InPaintEvent Currently processing a paint event.
969   \li Qt::WA_WState_Reparented The widget has been reparented.
970   \li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
971   \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
972   \endlist
973 */
974
975 struct QWidgetExceptionCleaner
976 {
977     /* this cleans up when the constructor throws an exception */
978     static inline void cleanup(QWidget *that, QWidgetPrivate *d)
979     {
980 #ifdef QT_NO_EXCEPTIONS
981         Q_UNUSED(that);
982         Q_UNUSED(d);
983 #else
984         QWidgetPrivate::allWidgets->remove(that);
985         if (d->focus_next != that) {
986             if (d->focus_next)
987                 d->focus_next->d_func()->focus_prev = d->focus_prev;
988             if (d->focus_prev)
989                 d->focus_prev->d_func()->focus_next = d->focus_next;
990         }
991 #endif
992     }
993 };
994
995 /*!
996     Constructs a widget which is a child of \a parent, with  widget
997     flags set to \a f.
998
999     If \a parent is 0, the new widget becomes a window. If
1000     \a parent is another widget, this widget becomes a child window
1001     inside \a parent. The new widget is deleted when its \a parent is
1002     deleted.
1003
1004     The widget flags argument, \a f, is normally 0, but it can be set
1005     to customize the frame of a window (i.e. \a
1006     parent must be 0). To customize the frame, use a value composed
1007     from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1008
1009     If you add a child widget to an already visible widget you must
1010     explicitly show the child to make it visible.
1011
1012     Note that the X11 version of Qt may not be able to deliver all
1013     combinations of style flags on all systems. This is because on
1014     X11, Qt can only ask the window manager, and the window manager
1015     can override the application's settings. On Windows, Qt can set
1016     whatever flags you want.
1017
1018     \sa windowFlags
1019 */
1020 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1021     : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1022 {
1023     QT_TRY {
1024         d_func()->init(parent, f);
1025     } QT_CATCH(...) {
1026         QWidgetExceptionCleaner::cleanup(this, d_func());
1027         QT_RETHROW;
1028     }
1029 }
1030
1031
1032 /*! \internal
1033 */
1034 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1035     : QObject(dd, 0), QPaintDevice()
1036 {
1037     Q_D(QWidget);
1038     QT_TRY {
1039         d->init(parent, f);
1040     } QT_CATCH(...) {
1041         QWidgetExceptionCleaner::cleanup(this, d_func());
1042         QT_RETHROW;
1043     }
1044 }
1045
1046 /*!
1047     \internal
1048 */
1049 int QWidget::devType() const
1050 {
1051     return QInternal::Widget;
1052 }
1053
1054
1055 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1056 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1057 {
1058     bool customize =  (flags & (Qt::CustomizeWindowHint
1059             | Qt::FramelessWindowHint
1060             | Qt::WindowTitleHint
1061             | Qt::WindowSystemMenuHint
1062             | Qt::WindowMinimizeButtonHint
1063             | Qt::WindowMaximizeButtonHint
1064             | Qt::WindowCloseButtonHint
1065             | Qt::WindowContextHelpButtonHint));
1066
1067     uint type = (flags & Qt::WindowType_Mask);
1068
1069     if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1070         type = Qt::Window;
1071         flags |= Qt::Window;
1072     }
1073
1074     if (flags & Qt::CustomizeWindowHint) {
1075         // modify window flags to make them consistent.
1076         // Only enable this on non-Mac platforms. Since the old way of doing this would
1077         // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1078         // we can't just add this in.
1079 #ifndef Q_WS_MAC
1080         if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1081             flags |= Qt::WindowSystemMenuHint;
1082 #else
1083         if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1084                      | Qt::WindowSystemMenuHint)) {
1085 #endif
1086             flags |= Qt::WindowTitleHint;
1087             flags &= ~Qt::FramelessWindowHint;
1088         }
1089     } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1090         // if any of the window hints that affect the titlebar are set
1091         // and the window is supposed to have frame, we add a titlebar
1092         // and system menu by default.
1093         flags |= Qt::WindowSystemMenuHint;
1094         flags |= Qt::WindowTitleHint;
1095     }
1096     if (customize)
1097         ; // don't modify window flags if the user explicitly set them.
1098     else if (type == Qt::Dialog || type == Qt::Sheet)
1099 #ifndef Q_OS_WINCE
1100         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1101 #else
1102         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1103 #endif
1104     else if (type == Qt::Tool)
1105         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1106     else
1107         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1108
1109
1110 }
1111
1112 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1113 {
1114     Q_Q(QWidget);
1115     if (QApplication::type() == QApplication::Tty)
1116         qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1117
1118     Q_ASSERT(allWidgets);
1119     if (allWidgets)
1120         allWidgets->insert(q);
1121
1122     QWidget *desktopWidget = 0;
1123     if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1124         desktopWidget = parentWidget;
1125         parentWidget = 0;
1126     }
1127
1128     q->data = &data;
1129
1130 #ifndef QT_NO_THREAD
1131     if (!parent) {
1132         Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1133                    "Widgets must be created in the GUI thread.");
1134     }
1135 #endif
1136
1137 #if defined(Q_WS_X11)
1138     if (desktopWidget) {
1139         // make sure the widget is created on the same screen as the
1140         // programmer specified desktop widget
1141         xinfo = desktopWidget->d_func()->xinfo;
1142     }
1143 #endif
1144     if (desktopWidget) {
1145         const int screen = desktopWidget->d_func()->topData()->screenIndex;
1146         if (QWindow *window = q->windowHandle())
1147             window->setScreen(QGuiApplication::screens().value(screen, 0));
1148     }
1149
1150     data.fstrut_dirty = true;
1151
1152     data.winid = 0;
1153     data.widget_attributes = 0;
1154     data.window_flags = f;
1155     data.window_state = 0;
1156     data.focus_policy = 0;
1157     data.context_menu_policy = Qt::DefaultContextMenu;
1158     data.window_modality = Qt::NonModal;
1159
1160     data.sizehint_forced = 0;
1161     data.is_closing = 0;
1162     data.in_show = 0;
1163     data.in_set_window_state = 0;
1164     data.in_destructor = false;
1165
1166     // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1167     if (f & Qt::MSWindowsOwnDC)
1168         q->setAttribute(Qt::WA_NativeWindow);
1169
1170 //#ifdef Q_WS_MAC
1171 //    q->setAttribute(Qt::WA_NativeWindow);
1172 //#endif
1173
1174     q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1175     adjustQuitOnCloseAttribute();
1176
1177     q->setAttribute(Qt::WA_WState_Hidden);
1178
1179     //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1180     data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1181     focus_next = focus_prev = q;
1182
1183     if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1184         q->create();
1185     else if (parentWidget)
1186         q->setParent(parentWidget, data.window_flags);
1187     else {
1188         adjustFlags(data.window_flags, q);
1189         resolveLayoutDirection();
1190         // opaque system background?
1191         const QBrush &background = q->palette().brush(QPalette::Window);
1192         setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1193     }
1194     data.fnt = QFont(data.fnt, q);
1195 #if defined(Q_WS_X11)
1196     data.fnt.x11SetScreen(xinfo.screen());
1197 #endif // Q_WS_X11
1198
1199     q->setAttribute(Qt::WA_PendingMoveEvent);
1200     q->setAttribute(Qt::WA_PendingResizeEvent);
1201
1202     if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1203         QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1204
1205     if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1206         q->create();
1207
1208     QEvent e(QEvent::Create);
1209     QApplication::sendEvent(q, &e);
1210     QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1211
1212     extraPaintEngine = 0;
1213
1214 #ifdef Q_WS_MAC
1215     // If we add a child to the unified toolbar, we have to redirect the painting.
1216     if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1217         if (parentWidget->d_func()->unifiedSurface) {
1218             QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1219             parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1220         }
1221     }
1222 #endif // Q_WS_MAC
1223 }
1224
1225
1226
1227 void QWidgetPrivate::createRecursively()
1228 {
1229     Q_Q(QWidget);
1230     q->create(0, true, true);
1231     for (int i = 0; i < children.size(); ++i) {
1232         QWidget *child = qobject_cast<QWidget *>(children.at(i));
1233         if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1234             child->d_func()->createRecursively();
1235     }
1236 }
1237
1238
1239
1240
1241 /*!
1242     Creates a new widget window if \a window is 0, otherwise sets the
1243     widget's window to \a window.
1244
1245     Initializes the window (sets the geometry etc.) if \a
1246     initializeWindow is true. If \a initializeWindow is false, no
1247     initialization is performed. This parameter only makes sense if \a
1248     window is a valid window.
1249
1250     Destroys the old window if \a destroyOldWindow is true. If \a
1251     destroyOldWindow is false, you are responsible for destroying the
1252     window yourself (using platform native code).
1253
1254     The QWidget constructor calls create(0,true,true) to create a
1255     window for this widget.
1256 */
1257
1258 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1259 {
1260     Q_D(QWidget);
1261     if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1262         return;
1263
1264     if (d->data.in_destructor)
1265         return;
1266
1267     Qt::WindowType type = windowType();
1268     Qt::WindowFlags &flags = data->window_flags;
1269
1270     if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1271         type = Qt::Window;
1272         flags |= Qt::Window;
1273     }
1274
1275     if (QWidget *parent = parentWidget()) {
1276         if (type & Qt::Window) {
1277             if (!parent->testAttribute(Qt::WA_WState_Created))
1278                 parent->createWinId();
1279         } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1280                    && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1281             // We're about to create a native child widget that doesn't have a native parent;
1282             // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1283             // attribute is set.
1284             d->createWinId(window);
1285             // Nothing more to do.
1286             Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1287             Q_ASSERT(internalWinId());
1288             return;
1289         }
1290     }
1291
1292
1293     static int paintOnScreenEnv = -1;
1294     if (paintOnScreenEnv == -1)
1295         paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1296     if (paintOnScreenEnv == 1)
1297         setAttribute(Qt::WA_PaintOnScreen);
1298
1299     if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1300         setAttribute(Qt::WA_NativeWindow);
1301
1302 #ifdef ALIEN_DEBUG
1303     qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1304              << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1305 #endif
1306
1307 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1308     // Unregister the dropsite (if already registered) before we
1309     // re-create the widget with a native window.
1310     if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1311             && d->extra && d->extra->dropTarget) {
1312         d->registerDropSite(false);
1313     }
1314 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1315
1316     d->updateIsOpaque();
1317
1318     setAttribute(Qt::WA_WState_Created);                        // set created flag
1319     d->create_sys(window, initializeWindow, destroyOldWindow);
1320
1321     // a real toplevel window needs a backing store
1322     if (isWindow() && windowType() != Qt::Desktop) {
1323         d->topData()->backingStoreTracker.destroy();
1324         if (hasBackingStoreSupport())
1325             d->topData()->backingStoreTracker.create(this);
1326     }
1327
1328     d->setModal_sys();
1329
1330     if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1331         setAttribute(Qt::WA_DropSiteRegistered, true);
1332
1333 #ifdef QT_EVAL
1334     extern void qt_eval_init_widget(QWidget *w);
1335     qt_eval_init_widget(this);
1336 #endif
1337
1338     // need to force the resting of the icon after changing parents
1339     if (testAttribute(Qt::WA_SetWindowIcon))
1340         d->setWindowIcon_sys(true);
1341     if (isWindow() && !d->topData()->iconText.isEmpty())
1342         d->setWindowIconText_helper(d->topData()->iconText);
1343     if (isWindow() && !d->topData()->caption.isEmpty())
1344         d->setWindowTitle_helper(d->topData()->caption);
1345     if (windowType() != Qt::Desktop) {
1346         d->updateSystemBackground();
1347
1348         if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1349             d->setWindowIcon_sys();
1350     }
1351 }
1352
1353 /*!
1354     Destroys the widget.
1355
1356     All this widget's children are deleted first. The application
1357     exits if this widget is the main widget.
1358 */
1359
1360 QWidget::~QWidget()
1361 {
1362     Q_D(QWidget);
1363     d->data.in_destructor = true;
1364
1365 #if defined (QT_CHECK_STATE)
1366     if (paintingActive())
1367         qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1368 #endif
1369
1370 #ifndef QT_NO_GESTURES
1371     foreach (Qt::GestureType type, d->gestureContext.keys())
1372         ungrabGesture(type);
1373 #endif
1374
1375     // force acceptDrops false before winId is destroyed.
1376     d->registerDropSite(false);
1377
1378 #ifndef QT_NO_ACTION
1379     // remove all actions from this widget
1380     for (int i = 0; i < d->actions.size(); ++i) {
1381         QActionPrivate *apriv = d->actions.at(i)->d_func();
1382         apriv->widgets.removeAll(this);
1383     }
1384     d->actions.clear();
1385 #endif
1386
1387 #ifndef QT_NO_SHORTCUT
1388     // Remove all shortcuts grabbed by this
1389     // widget, unless application is closing
1390     if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1391         qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1392 #endif
1393
1394     // delete layout while we still are a valid widget
1395     delete d->layout;
1396     d->layout = 0;
1397     // Remove myself from focus list
1398
1399     Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1400     Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1401
1402     if (d->focus_next != this) {
1403         d->focus_next->d_func()->focus_prev = d->focus_prev;
1404         d->focus_prev->d_func()->focus_next = d->focus_next;
1405         d->focus_next = d->focus_prev = 0;
1406     }
1407
1408
1409     QT_TRY {
1410         clearFocus();
1411     } QT_CATCH(...) {
1412         // swallow this problem because we are in a destructor
1413     }
1414
1415     d->setDirtyOpaqueRegion();
1416
1417     if (isWindow() && isVisible() && internalWinId()) {
1418         QT_TRY {
1419             d->close_helper(QWidgetPrivate::CloseNoEvent);
1420         } QT_CATCH(...) {
1421             // if we're out of memory, at least hide the window.
1422             QT_TRY {
1423                 hide();
1424             } QT_CATCH(...) {
1425                 // and if that also doesn't work, then give up
1426             }
1427         }
1428     }
1429
1430 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1431     else if (!internalWinId() && isVisible()) {
1432         qApp->d_func()->sendSyntheticEnterLeave(this);
1433     }
1434 #endif
1435     else if (isVisible()) {
1436         qApp->d_func()->sendSyntheticEnterLeave(this);
1437     }
1438
1439     if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1440         bs->removeDirtyWidget(this);
1441         if (testAttribute(Qt::WA_StaticContents))
1442             bs->removeStaticWidget(this);
1443     }
1444
1445     delete d->needsFlush;
1446     d->needsFlush = 0;
1447
1448     if (d->declarativeData) {
1449         QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1450         d->declarativeData = 0;                 // don't activate again in ~QObject
1451     }
1452
1453 #ifdef Q_WS_MAC
1454     // QCocoaView holds a pointer back to this widget. Clear it now
1455     // to make sure it's not followed later on. The lifetime of the
1456     // QCocoaView might exceed the lifetime of this widget in cases
1457     // where Cocoa itself holds references to it.
1458     extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1459     qt_mac_clearCocoaViewQWidgetPointers(this);
1460 #endif
1461
1462     if (!d->children.isEmpty())
1463         d->deleteChildren();
1464
1465     QApplication::removePostedEvents(this);
1466
1467     QT_TRY {
1468         destroy();                                        // platform-dependent cleanup
1469     } QT_CATCH(...) {
1470         // if this fails we can't do anything about it but at least we are not allowed to throw.
1471     }
1472     --QWidgetPrivate::instanceCounter;
1473
1474     if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1475         QWidgetPrivate::allWidgets->remove(this);
1476
1477     QT_TRY {
1478         QEvent e(QEvent::Destroy);
1479         QCoreApplication::sendEvent(this, &e);
1480     } QT_CATCH(const std::exception&) {
1481         // if this fails we can't do anything about it but at least we are not allowed to throw.
1482     }
1483 }
1484
1485 int QWidgetPrivate::instanceCounter = 0;  // Current number of widget instances
1486 int QWidgetPrivate::maxInstances = 0;     // Maximum number of widget instances
1487
1488 void QWidgetPrivate::setWinId(WId id)                // set widget identifier
1489 {
1490     Q_Q(QWidget);
1491     // the user might create a widget with Qt::Desktop window
1492     // attribute (or create another QDesktopWidget instance), which
1493     // will have the same windowid (the root window id) as the
1494     // qt_desktopWidget. We should not add the second desktop widget
1495     // to the mapper.
1496     bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1497     if (mapper && data.winid && !userDesktopWidget) {
1498         mapper->remove(data.winid);
1499     }
1500
1501     const WId oldWinId = data.winid;
1502
1503     data.winid = id;
1504 #if defined(Q_WS_X11)
1505     hd = id; // X11: hd == ident
1506 #endif
1507     if (mapper && id && !userDesktopWidget) {
1508         mapper->insert(data.winid, q);
1509     }
1510
1511     if(oldWinId != id) {
1512         QEvent e(QEvent::WinIdChange);
1513         QCoreApplication::sendEvent(q, &e);
1514     }
1515 }
1516
1517 void QWidgetPrivate::createTLExtra()
1518 {
1519     if (!extra)
1520         createExtra();
1521     if (!extra->topextra) {
1522         QTLWExtra* x = extra->topextra = new QTLWExtra;
1523         x->icon = 0;
1524         x->iconPixmap = 0;
1525         x->backingStore = 0;
1526         x->sharedPainter = 0;
1527         x->incw = x->inch = 0;
1528         x->basew = x->baseh = 0;
1529         x->frameStrut.setCoords(0, 0, 0, 0);
1530         x->normalGeometry = QRect(0,0,-1,-1);
1531         x->savedFlags = 0;
1532         x->opacity = 255;
1533         x->posFromMove = false;
1534         x->sizeAdjusted = false;
1535         x->inTopLevelResize = false;
1536         x->inRepaint = false;
1537         x->embedded = 0;
1538 #ifdef Q_WS_MAC
1539         x->wasMaximized = false;
1540 #endif // Q_WS_MAC
1541         createTLSysExtra();
1542 #ifdef QWIDGET_EXTRA_DEBUG
1543         static int count = 0;
1544         qDebug() << "tlextra" << ++count;
1545 #endif
1546     }
1547 }
1548
1549 /*!
1550   \internal
1551   Creates the widget extra data.
1552 */
1553
1554 void QWidgetPrivate::createExtra()
1555 {
1556     if (!extra) {                                // if not exists
1557         extra = new QWExtra;
1558         extra->glContext = 0;
1559         extra->topextra = 0;
1560 #ifndef QT_NO_GRAPHICSVIEW
1561         extra->proxyWidget = 0;
1562 #endif
1563 #ifndef QT_NO_CURSOR
1564         extra->curs = 0;
1565 #endif
1566         extra->minw = 0;
1567         extra->minh = 0;
1568         extra->maxw = QWIDGETSIZE_MAX;
1569         extra->maxh = QWIDGETSIZE_MAX;
1570         extra->customDpiX = 0;
1571         extra->customDpiY = 0;
1572         extra->explicitMinSize = 0;
1573         extra->explicitMaxSize = 0;
1574         extra->autoFillBackground = 0;
1575         extra->nativeChildrenForced = 0;
1576         extra->inRenderWithPainter = 0;
1577         extra->hasMask = 0;
1578         createSysExtra();
1579 #ifdef QWIDGET_EXTRA_DEBUG
1580         static int count = 0;
1581         qDebug() << "extra" << ++count;
1582 #endif
1583     }
1584 }
1585
1586
1587 /*!
1588   \internal
1589   Deletes the widget extra data.
1590 */
1591
1592 void QWidgetPrivate::deleteExtra()
1593 {
1594     if (extra) {                                // if exists
1595 #ifndef QT_NO_CURSOR
1596         delete extra->curs;
1597 #endif
1598         deleteSysExtra();
1599 #ifndef QT_NO_STYLE_STYLESHEET
1600         // dereference the stylesheet style
1601         if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1602             proxy->deref();
1603 #endif
1604         if (extra->topextra) {
1605             deleteTLSysExtra();
1606             extra->topextra->backingStoreTracker.destroy();
1607             delete extra->topextra->icon;
1608             delete extra->topextra->iconPixmap;
1609             delete extra->topextra->backingStore;
1610             delete extra->topextra;
1611         }
1612         delete extra;
1613         // extra->xic destroyed in QWidget::destroy()
1614         extra = 0;
1615     }
1616 }
1617
1618 /*
1619   Returns true if there are widgets above this which overlap with
1620   \a rect, which is in parent's coordinate system (same as crect).
1621 */
1622
1623 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1624 {
1625     Q_Q(const QWidget);
1626
1627     const QWidget *w = q;
1628     QRect r = rect;
1629     while (w) {
1630         if (w->isWindow())
1631             return false;
1632         QWidgetPrivate *pd = w->parentWidget()->d_func();
1633         bool above = false;
1634         for (int i = 0; i < pd->children.size(); ++i) {
1635             QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1636             if (!sibling || !sibling->isVisible() || sibling->isWindow())
1637                 continue;
1638             if (!above) {
1639                 above = (sibling == w);
1640                 continue;
1641             }
1642
1643             if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1644                 const QWExtra *siblingExtra = sibling->d_func()->extra;
1645                 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1646                     && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1647                     continue;
1648                 }
1649                 return true;
1650             }
1651         }
1652         w = w->parentWidget();
1653         r.translate(pd->data.crect.topLeft());
1654     }
1655     return false;
1656 }
1657
1658 void QWidgetPrivate::syncBackingStore()
1659 {
1660     if (paintOnScreen()) {
1661         repaint_sys(dirty);
1662         dirty = QRegion();
1663     } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1664         bs->sync();
1665     }
1666 }
1667
1668 void QWidgetPrivate::syncBackingStore(const QRegion &region)
1669 {
1670     if (paintOnScreen())
1671         repaint_sys(region);
1672     else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1673         bs->sync(q_func(), region);
1674     }
1675 }
1676
1677 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1678 {
1679     Q_Q(QWidget);
1680
1681     if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1682         return; // nothing we can do
1683
1684     if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1685         return; // nothing to do
1686
1687     q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1688     if (enable)
1689         q->update();
1690
1691     Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1692     for (int i = 0; i < children.size(); ++i) {
1693         QWidget *w = qobject_cast<QWidget *>(children.at(i));
1694         if (w && !w->isWindow() && !w->testAttribute(attribute))
1695             w->d_func()->setUpdatesEnabled_helper(enable);
1696     }
1697 }
1698
1699 /*!
1700     \internal
1701
1702     Propagate this widget's palette to all children, except style sheet
1703     widgets, and windows that don't enable window propagation (palettes don't
1704     normally propagate to windows).
1705 */
1706 void QWidgetPrivate::propagatePaletteChange()
1707 {
1708     Q_Q(QWidget);
1709     // Propagate a new inherited mask to all children.
1710 #ifndef QT_NO_GRAPHICSVIEW
1711     if (!q->parentWidget() && extra && extra->proxyWidget) {
1712         QGraphicsProxyWidget *p = extra->proxyWidget;
1713         inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1714     } else
1715 #endif //QT_NO_GRAPHICSVIEW
1716         if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1717         inheritedPaletteResolveMask = 0;
1718     }
1719     int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1720
1721     QEvent pc(QEvent::PaletteChange);
1722     QApplication::sendEvent(q, &pc);
1723     for (int i = 0; i < children.size(); ++i) {
1724         QWidget *w = qobject_cast<QWidget*>(children.at(i));
1725         if (w && !w->testAttribute(Qt::WA_StyleSheet)
1726             && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1727             QWidgetPrivate *wd = w->d_func();
1728             wd->inheritedPaletteResolveMask = mask;
1729             wd->resolvePalette();
1730         }
1731     }
1732 }
1733
1734 /*
1735   Returns the widget's clipping rectangle.
1736 */
1737 QRect QWidgetPrivate::clipRect() const
1738 {
1739     Q_Q(const QWidget);
1740     const QWidget * w = q;
1741     if (!w->isVisible())
1742         return QRect();
1743     QRect r = effectiveRectFor(q->rect());
1744     int ox = 0;
1745     int oy = 0;
1746     while (w
1747             && w->isVisible()
1748             && !w->isWindow()
1749             && w->parentWidget()) {
1750         ox -= w->x();
1751         oy -= w->y();
1752         w = w->parentWidget();
1753         r &= QRect(ox, oy, w->width(), w->height());
1754     }
1755     return r;
1756 }
1757
1758 /*
1759   Returns the widget's clipping region (without siblings).
1760 */
1761 QRegion QWidgetPrivate::clipRegion() const
1762 {
1763     Q_Q(const QWidget);
1764     if (!q->isVisible())
1765         return QRegion();
1766     QRegion r(q->rect());
1767     const QWidget * w = q;
1768     const QWidget *ignoreUpTo;
1769     int ox = 0;
1770     int oy = 0;
1771     while (w
1772            && w->isVisible()
1773            && !w->isWindow()
1774            && w->parentWidget()) {
1775         ox -= w->x();
1776         oy -= w->y();
1777         ignoreUpTo = w;
1778         w = w->parentWidget();
1779         r &= QRegion(ox, oy, w->width(), w->height());
1780
1781         int i = 0;
1782         while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1783             ;
1784         for ( ; i < w->d_func()->children.size(); ++i) {
1785             if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1786                 if(sibling->isVisible() && !sibling->isWindow()) {
1787                     QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1788                                       sibling->width(), sibling->height());
1789                     if (qRectIntersects(siblingRect, q->rect()))
1790                         r -= QRegion(siblingRect);
1791                 }
1792             }
1793         }
1794     }
1795     return r;
1796 }
1797
1798 #ifndef QT_NO_GRAPHICSEFFECT
1799 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1800 {
1801     Q_Q(QWidget);
1802     QWidget *w = q;
1803     do {
1804         if (w->graphicsEffect()) {
1805             QWidgetEffectSourcePrivate *sourced =
1806                 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1807             if (!sourced->updateDueToGraphicsEffect)
1808                 w->graphicsEffect()->source()->d_func()->invalidateCache();
1809         }
1810         w = w->parentWidget();
1811     } while (w);
1812 }
1813 #endif //QT_NO_GRAPHICSEFFECT
1814
1815 void QWidgetPrivate::setDirtyOpaqueRegion()
1816 {
1817     Q_Q(QWidget);
1818
1819     dirtyOpaqueChildren = true;
1820
1821 #ifndef QT_NO_GRAPHICSEFFECT
1822     invalidateGraphicsEffectsRecursively();
1823 #endif //QT_NO_GRAPHICSEFFECT
1824
1825     if (q->isWindow())
1826         return;
1827
1828     QWidget *parent = q->parentWidget();
1829     if (!parent)
1830         return;
1831
1832     // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1833     QWidgetPrivate *pd = parent->d_func();
1834     if (!pd->dirtyOpaqueChildren)
1835         pd->setDirtyOpaqueRegion();
1836 }
1837
1838 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1839 {
1840     if (!dirtyOpaqueChildren)
1841         return opaqueChildren;
1842
1843     QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1844     that->opaqueChildren = QRegion();
1845
1846     for (int i = 0; i < children.size(); ++i) {
1847         QWidget *child = qobject_cast<QWidget *>(children.at(i));
1848         if (!child || !child->isVisible() || child->isWindow())
1849             continue;
1850
1851         const QPoint offset = child->geometry().topLeft();
1852         QWidgetPrivate *childd = child->d_func();
1853         QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1854         if (childd->extra && childd->extra->hasMask)
1855             r &= childd->extra->mask;
1856         if (r.isEmpty())
1857             continue;
1858         r.translate(offset);
1859         that->opaqueChildren += r;
1860     }
1861
1862     that->opaqueChildren &= q_func()->rect();
1863     that->dirtyOpaqueChildren = false;
1864
1865     return that->opaqueChildren;
1866 }
1867
1868 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1869 {
1870     if (children.isEmpty() || clipRect.isEmpty())
1871         return;
1872
1873     const QRegion &r = getOpaqueChildren();
1874     if (!r.isEmpty())
1875         source -= (r & clipRect);
1876 }
1877
1878 //subtract any relatives that are higher up than me --- this is too expensive !!!
1879 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1880                                             bool alsoNonOpaque) const
1881 {
1882     Q_Q(const QWidget);
1883     static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1884     if (disableSubtractOpaqueSiblings || q->isWindow())
1885         return;
1886
1887 #ifdef Q_WS_MAC
1888     if (q->d_func()->isInUnifiedToolbar)
1889         return;
1890 #endif // Q_WS_MAC
1891
1892     QRect clipBoundingRect;
1893     bool dirtyClipBoundingRect = true;
1894
1895     QRegion parentClip;
1896     bool dirtyParentClip = true;
1897
1898     QPoint parentOffset = data.crect.topLeft();
1899
1900     const QWidget *w = q;
1901
1902     while (w) {
1903         if (w->isWindow())
1904             break;
1905         QWidgetPrivate *pd = w->parentWidget()->d_func();
1906         const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1907         const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1908         for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1909             QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1910             if (!sibling || !sibling->isVisible() || sibling->isWindow())
1911                 continue;
1912
1913             const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1914             if (!qRectIntersects(siblingGeometry, widgetGeometry))
1915                 continue;
1916
1917             if (dirtyClipBoundingRect) {
1918                 clipBoundingRect = sourceRegion.boundingRect();
1919                 dirtyClipBoundingRect = false;
1920             }
1921
1922             if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1923                 continue;
1924
1925             if (dirtyParentClip) {
1926                 parentClip = sourceRegion.translated(parentOffset);
1927                 dirtyParentClip = false;
1928             }
1929
1930             const QPoint siblingPos(sibling->data->crect.topLeft());
1931             const QRect siblingClipRect(sibling->d_func()->clipRect());
1932             QRegion siblingDirty(parentClip);
1933             siblingDirty &= (siblingClipRect.translated(siblingPos));
1934             const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1935                                  && !sibling->d_func()->graphicsEffect;
1936             if (hasMask)
1937                 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1938             if (siblingDirty.isEmpty())
1939                 continue;
1940
1941             if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1942                 if (hasMask) {
1943                     siblingDirty.translate(-parentOffset);
1944                     sourceRegion -= siblingDirty;
1945                 } else {
1946                     sourceRegion -= siblingGeometry.translated(-parentOffset);
1947                 }
1948             } else {
1949                 if (hasDirtySiblingsAbove)
1950                     *hasDirtySiblingsAbove = true;
1951                 if (sibling->d_func()->children.isEmpty())
1952                     continue;
1953                 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1954                 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1955                 sourceRegion -= opaqueSiblingChildren;
1956             }
1957             if (sourceRegion.isEmpty())
1958                 return;
1959
1960             dirtyClipBoundingRect = true;
1961             dirtyParentClip = true;
1962         }
1963
1964         w = w->parentWidget();
1965         parentOffset += pd->data.crect.topLeft();
1966         dirtyParentClip = true;
1967     }
1968 }
1969
1970 void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const
1971 {
1972     Q_Q(const QWidget);
1973
1974     const QWidget *w = q;
1975     QPoint offset;
1976
1977 #ifndef QT_NO_GRAPHICSEFFECT
1978     if (graphicsEffect) {
1979         w = q->parentWidget();
1980         offset -= data.crect.topLeft();
1981     }
1982 #endif //QT_NO_GRAPHICSEFFECT
1983
1984     while (w) {
1985         const QWidgetPrivate *wd = w->d_func();
1986         if (wd->extra && wd->extra->hasMask)
1987             region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
1988         if (w->isWindow())
1989             return;
1990         offset -= wd->data.crect.topLeft();
1991         w = w->parentWidget();
1992     }
1993 }
1994
1995 bool QWidgetPrivate::paintOnScreen() const
1996 {
1997 #if defined(QT_NO_BACKINGSTORE)
1998     return true;
1999 #else
2000     Q_Q(const QWidget);
2001     if (q->testAttribute(Qt::WA_PaintOnScreen)
2002             || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2003         return true;
2004     }
2005
2006     return !qt_enable_backingstore;
2007 #endif
2008 }
2009
2010 void QWidgetPrivate::updateIsOpaque()
2011 {
2012     // hw: todo: only needed if opacity actually changed
2013     setDirtyOpaqueRegion();
2014
2015 #ifndef QT_NO_GRAPHICSEFFECT
2016     if (graphicsEffect) {
2017         // ### We should probably add QGraphicsEffect::isOpaque at some point.
2018         setOpaque(false);
2019         return;
2020     }
2021 #endif //QT_NO_GRAPHICSEFFECT
2022
2023     Q_Q(QWidget);
2024 #ifdef Q_WS_X11
2025     if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2026         setOpaque(false);
2027         return;
2028     }
2029 #endif
2030
2031     if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2032         setOpaque(true);
2033         return;
2034     }
2035
2036     const QPalette &pal = q->palette();
2037
2038     if (q->autoFillBackground()) {
2039         const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2040         if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2041             setOpaque(true);
2042             return;
2043         }
2044     }
2045
2046     if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2047         const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2048         if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2049             setOpaque(true);
2050             return;
2051         }
2052     }
2053     setOpaque(false);
2054 }
2055
2056 void QWidgetPrivate::setOpaque(bool opaque)
2057 {
2058     if (isOpaque == opaque)
2059         return;
2060     isOpaque = opaque;
2061 #ifdef Q_WS_MAC
2062     macUpdateIsOpaque();
2063 #endif
2064 #ifdef Q_WS_X11
2065     x11UpdateIsOpaque();
2066 #endif
2067 #ifdef Q_WS_WIN
2068     winUpdateIsOpaque();
2069 #endif
2070 }
2071
2072 void QWidgetPrivate::updateIsTranslucent()
2073 {
2074 #ifdef Q_WS_MAC
2075     macUpdateIsOpaque();
2076 #endif
2077 #ifdef Q_WS_X11
2078     x11UpdateIsOpaque();
2079 #endif
2080 #ifdef Q_WS_WIN
2081     winUpdateIsOpaque();
2082 #endif
2083 }
2084
2085 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2086 {
2087     Q_ASSERT(painter);
2088
2089     if (brush.style() == Qt::TexturePattern) {
2090 #ifdef Q_WS_MAC
2091         // Optimize pattern filling on mac by using HITheme directly
2092         // when filling with the standard widget background.
2093         // Defined in qmacstyle_mac.cpp
2094         extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2095         qt_mac_fill_background(painter, rgn, brush);
2096 #else
2097         {
2098             const QRect rect(rgn.boundingRect());
2099             painter->setClipRegion(rgn);
2100             painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2101         }
2102 #endif // Q_WS_MAC
2103
2104     } else if (brush.gradient()
2105                && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2106         painter->save();
2107         painter->setClipRegion(rgn);
2108         painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2109         painter->restore();
2110     } else {
2111         const QVector<QRect> &rects = rgn.rects();
2112         for (int i = 0; i < rects.size(); ++i)
2113             painter->fillRect(rects.at(i), brush);
2114     }
2115 }
2116
2117 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2118 {
2119     Q_Q(const QWidget);
2120
2121 #ifndef QT_NO_SCROLLAREA
2122     bool resetBrushOrigin = false;
2123     QPointF oldBrushOrigin;
2124     //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2125     QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2126     if (scrollArea && scrollArea->viewport() == q) {
2127         QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2128         QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2129         oldBrushOrigin = painter->brushOrigin();
2130         resetBrushOrigin = true;
2131         painter->setBrushOrigin(-priv->contentsOffset());
2132
2133     }
2134 #endif // QT_NO_SCROLLAREA
2135
2136     const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2137
2138     if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2139         const QBrush bg = q->palette().brush(QPalette::Window);
2140         fillRegion(painter, rgn, bg);
2141     }
2142
2143     if (q->autoFillBackground())
2144         fillRegion(painter, rgn, autoFillBrush);
2145
2146     if (q->testAttribute(Qt::WA_StyledBackground)) {
2147         painter->setClipRegion(rgn);
2148         QStyleOption opt;
2149         opt.initFrom(q);
2150         q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2151     }
2152
2153 #ifndef QT_NO_SCROLLAREA
2154     if (resetBrushOrigin)
2155         painter->setBrushOrigin(oldBrushOrigin);
2156 #endif // QT_NO_SCROLLAREA
2157 }
2158
2159 /*
2160   \internal
2161   This function is called when a widget is hidden or destroyed.
2162   It resets some application global pointers that should only refer active,
2163   visible widgets.
2164 */
2165
2166 #ifdef Q_WS_MAC
2167     extern QPointer<QWidget> qt_button_down;
2168 #else
2169     extern QWidget *qt_button_down;
2170 #endif
2171
2172 void QWidgetPrivate::deactivateWidgetCleanup()
2173 {
2174     Q_Q(QWidget);
2175     // If this was the active application window, reset it
2176     if (QApplication::activeWindow() == q)
2177         QApplication::setActiveWindow(0);
2178     // If the is the active mouse press widget, reset it
2179     if (q == qt_button_down)
2180         qt_button_down = 0;
2181 }
2182
2183
2184 /*!
2185     Returns a pointer to the widget with window identifer/handle \a
2186     id.
2187
2188     The window identifier type depends on the underlying window
2189     system, see \c qwindowdefs.h for the actual definition. If there
2190     is no widget with this identifier, 0 is returned.
2191 */
2192
2193 QWidget *QWidget::find(WId id)
2194 {
2195     return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2196 }
2197
2198
2199
2200 /*!
2201     \fn WId QWidget::internalWinId() const
2202     \internal
2203     Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2204
2205 */
2206
2207 /*!
2208     \fn WId QWidget::winId() const
2209
2210     Returns the window system identifier of the widget.
2211
2212     Portable in principle, but if you use it you are probably about to
2213     do something non-portable. Be careful.
2214
2215     If a widget is non-native (alien) and winId() is invoked on it, that widget
2216     will be provided a native handle.
2217
2218     On Mac OS X, the type returned depends on which framework Qt was linked
2219     against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2220     is using Cocoa, {WId} is a pointer to an NSView.
2221
2222     This value may change at run-time. An event with type QEvent::WinIdChange
2223     will be sent to the widget following a change in window system identifier.
2224
2225     \sa find()
2226 */
2227 WId QWidget::winId() const
2228 {
2229     if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2230 #ifdef ALIEN_DEBUG
2231         qDebug() << "QWidget::winId: creating native window for" << this;
2232 #endif
2233         QWidget *that = const_cast<QWidget*>(this);
2234         that->setAttribute(Qt::WA_NativeWindow);
2235         that->d_func()->createWinId();
2236         return that->data->winid;
2237     }
2238     return data->winid;
2239 }
2240
2241
2242 void QWidgetPrivate::createWinId(WId winid)
2243 {
2244     Q_Q(QWidget);
2245
2246 #ifdef ALIEN_DEBUG
2247     qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2248 #endif
2249     const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2250     if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2251         if (!q->isWindow()) {
2252             QWidget *parent = q->parentWidget();
2253             QWidgetPrivate *pd = parent->d_func();
2254             if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2255                 parent->setAttribute(Qt::WA_NativeWindow);
2256             if (!parent->internalWinId()) {
2257                 pd->createWinId();
2258             }
2259
2260             for (int i = 0; i < pd->children.size(); ++i) {
2261                 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2262                 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2263                                             || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2264                     if (w!=q) {
2265                         w->create();
2266                     } else {
2267                         w->create(winid);
2268                         // if the window has already been created, we
2269                         // need to raise it to its proper stacking position
2270                         if (winid)
2271                             w->raise();
2272                     }
2273                 }
2274             }
2275         } else {
2276             q->create();
2277         }
2278     }
2279 }
2280
2281
2282 /*!
2283 \internal
2284 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2285
2286 */
2287
2288 void QWidget::createWinId()
2289 {
2290     Q_D(QWidget);
2291 #ifdef ALIEN_DEBUG
2292     qDebug()  << "QWidget::createWinId" << this;
2293 #endif
2294 //    qWarning("QWidget::createWinId is obsolete, please fix your code.");
2295     d->createWinId();
2296 }
2297
2298 /*!
2299     \since 4.4
2300
2301     Returns the effective window system identifier of the widget, i.e. the
2302     native parent's window system identifier.
2303
2304     If the widget is native, this function returns the native widget ID.
2305     Otherwise, the window ID of the first native parent widget, i.e., the
2306     top-level widget that contains this widget, is returned.
2307
2308     \note We recommend that you do not store this value as it is likely to
2309     change at run-time.
2310
2311     \sa nativeParentWidget()
2312 */
2313 WId QWidget::effectiveWinId() const
2314 {
2315     WId id = internalWinId();
2316     if (id || !testAttribute(Qt::WA_WState_Created))
2317         return id;
2318     QWidget *realParent = nativeParentWidget();
2319     if (!realParent && d_func()->inSetParent) {
2320         // In transitional state. This is really just a workaround. The real problem
2321         // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2322         // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2323         // attribute to false. The correct way is to do it the other way around, and
2324         // in that case the Qt::WA_WState_Created logic above will kick in and
2325         // return 0 whenever the widget is in a transitional state. However, changing
2326         // the original logic for all platforms is far more intrusive and might
2327         // break existing applications.
2328         // Note: The widget can only be in a transitional state when changing its
2329         // parent -- everything else is an internal error -- hence explicitly checking
2330         // against 'inSetParent' rather than doing an unconditional return whenever
2331         // 'realParent' is 0 (which may cause strange artifacts and headache later).
2332         return 0;
2333     }
2334     // This widget *must* have a native parent widget.
2335     Q_ASSERT(realParent);
2336     Q_ASSERT(realParent->internalWinId());
2337     return realParent->internalWinId();
2338 }
2339
2340 #ifndef QT_NO_STYLE_STYLESHEET
2341
2342 /*!
2343     \property QWidget::styleSheet
2344     \brief the widget's style sheet
2345     \since 4.2
2346
2347     The style sheet contains a textual description of customizations to the
2348     widget's style, as described in the \l{Qt Style Sheets} document.
2349
2350     Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2351
2352     \warning Qt style sheets are currently not supported for custom QStyle
2353     subclasses. We plan to address this in some future release.
2354
2355     \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2356 */
2357 QString QWidget::styleSheet() const
2358 {
2359     Q_D(const QWidget);
2360     if (!d->extra)
2361         return QString();
2362     return d->extra->styleSheet;
2363 }
2364
2365 void QWidget::setStyleSheet(const QString& styleSheet)
2366 {
2367     Q_D(QWidget);
2368     d->createExtra();
2369
2370     QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2371     d->extra->styleSheet = styleSheet;
2372     if (styleSheet.isEmpty()) { // stylesheet removed
2373         if (!proxy)
2374             return;
2375
2376         d->inheritStyle();
2377         return;
2378     }
2379
2380     if (proxy) { // style sheet update
2381         proxy->repolish(this);
2382         return;
2383     }
2384
2385     if (testAttribute(Qt::WA_SetStyle)) {
2386         d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2387     } else {
2388         d->setStyle_helper(new QStyleSheetStyle(0), true);
2389     }
2390 }
2391
2392 #endif // QT_NO_STYLE_STYLESHEET
2393
2394 /*!
2395     \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2396 */
2397
2398 QStyle *QWidget::style() const
2399 {
2400     Q_D(const QWidget);
2401
2402     if (d->extra && d->extra->style)
2403         return d->extra->style;
2404     return QApplication::style();
2405 }
2406
2407 /*!
2408     Sets the widget's GUI style to \a style. The ownership of the style
2409     object is not transferred.
2410
2411     If no style is set, the widget uses the application's style,
2412     QApplication::style() instead.
2413
2414     Setting a widget's style has no effect on existing or future child
2415     widgets.
2416
2417     \warning This function is particularly useful for demonstration
2418     purposes, where you want to show Qt's styling capabilities. Real
2419     applications should avoid it and use one consistent GUI style
2420     instead.
2421
2422     \warning Qt style sheets are currently not supported for custom QStyle
2423     subclasses. We plan to address this in some future release.
2424
2425     \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2426 */
2427
2428 void QWidget::setStyle(QStyle *style)
2429 {
2430     Q_D(QWidget);
2431     setAttribute(Qt::WA_SetStyle, style != 0);
2432     d->createExtra();
2433 #ifndef QT_NO_STYLE_STYLESHEET
2434     if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2435         //if for some reason someone try to set a QStyleSheetStyle, ref it
2436         //(this may happen for exemple in QButtonDialogBox which propagates its style)
2437         proxy->ref();
2438         d->setStyle_helper(style, false);
2439     } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2440         // if we have an application stylesheet or have a proxy already, propagate
2441         d->setStyle_helper(new QStyleSheetStyle(style), true);
2442     } else
2443 #endif
2444         d->setStyle_helper(style, false);
2445 }
2446
2447 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2448 #ifdef Q_WS_MAC
2449         metalHack
2450 #endif
2451         )
2452 {
2453     Q_Q(QWidget);
2454     QStyle *oldStyle  = q->style();
2455 #ifndef QT_NO_STYLE_STYLESHEET
2456     QWeakPointer<QStyle> origStyle;
2457 #endif
2458
2459 #ifdef Q_WS_MAC
2460     // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2461     // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2462     // set when changing that attribute and passes the widget's CURRENT style.
2463     // therefore no need to do a reassignment.
2464     if (!metalHack)
2465 #endif
2466     {
2467         createExtra();
2468
2469 #ifndef QT_NO_STYLE_STYLESHEET
2470         origStyle = extra->style.data();
2471 #endif
2472         extra->style = newStyle;
2473     }
2474
2475     // repolish
2476     if (q->windowType() != Qt::Desktop) {
2477         if (polished) {
2478             oldStyle->unpolish(q);
2479 #ifdef Q_WS_MAC
2480             if (metalHack)
2481                 macUpdateMetalAttribute();
2482 #endif
2483             q->style()->polish(q);
2484 #ifdef Q_WS_MAC
2485         } else if (metalHack) {
2486             macUpdateMetalAttribute();
2487 #endif
2488         }
2489     }
2490
2491     if (propagate) {
2492         for (int i = 0; i < children.size(); ++i) {
2493             QWidget *c = qobject_cast<QWidget*>(children.at(i));
2494             if (c)
2495                 c->d_func()->inheritStyle();
2496         }
2497     }
2498
2499 #ifndef QT_NO_STYLE_STYLESHEET
2500     if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2501         if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2502             cssStyle->clearWidgetFont(q);
2503         }
2504     }
2505 #endif
2506
2507     QEvent e(QEvent::StyleChange);
2508     QApplication::sendEvent(q, &e);
2509
2510 #ifndef QT_NO_STYLE_STYLESHEET
2511     // dereference the old stylesheet style
2512     if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2513         proxy->deref();
2514 #endif
2515 }
2516
2517 // Inherits style from the current parent and propagates it as necessary
2518 void QWidgetPrivate::inheritStyle()
2519 {
2520 #ifndef QT_NO_STYLE_STYLESHEET
2521     Q_Q(QWidget);
2522
2523     QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2524
2525     if (!q->styleSheet().isEmpty()) {
2526         Q_ASSERT(proxy);
2527         proxy->repolish(q);
2528         return;
2529     }
2530
2531     QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2532     QWidget *parent = q->parentWidget();
2533     QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2534     // If we have stylesheet on app or parent has stylesheet style, we need
2535     // to be running a proxy
2536     if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2537         QStyle *newStyle = parentStyle;
2538         if (q->testAttribute(Qt::WA_SetStyle))
2539             newStyle = new QStyleSheetStyle(origStyle);
2540         else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2541             newProxy->ref();
2542
2543         setStyle_helper(newStyle, true);
2544         return;
2545     }
2546
2547     // So, we have no stylesheet on parent/app and we have an empty stylesheet
2548     // we just need our original style back
2549     if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2550         return;
2551
2552     // We could have inherited the proxy from our parent (which has a custom style)
2553     // In such a case we need to start following the application style (i.e revert
2554     // the propagation behavior of QStyleSheetStyle)
2555     if (!q->testAttribute(Qt::WA_SetStyle))
2556         origStyle = 0;
2557
2558     setStyle_helper(origStyle, true);
2559 #endif // QT_NO_STYLE_STYLESHEET
2560 }
2561
2562
2563 /*!
2564     \fn bool QWidget::isWindow() const
2565
2566     Returns true if the widget is an independent window, otherwise
2567     returns false.
2568
2569     A window is a widget that isn't visually the child of any other
2570     widget and that usually has a frame and a
2571     \l{QWidget::setWindowTitle()}{window title}.
2572
2573     A window can have a \l{QWidget::parentWidget()}{parent widget}.
2574     It will then be grouped with its parent and deleted when the
2575     parent is deleted, minimized when the parent is minimized etc. If
2576     supported by the window manager, it will also have a common
2577     taskbar entry with its parent.
2578
2579     QDialog and QMainWindow widgets are by default windows, even if a
2580     parent widget is specified in the constructor. This behavior is
2581     specified by the Qt::Window flag.
2582
2583     \sa window(), isModal(), parentWidget()
2584 */
2585
2586 /*!
2587     \property QWidget::modal
2588     \brief whether the widget is a modal widget
2589
2590     This property only makes sense for windows. A modal widget
2591     prevents widgets in all other windows from getting any input.
2592
2593     By default, this property is false.
2594
2595     \sa isWindow(), windowModality, QDialog
2596 */
2597
2598 /*!
2599     \property QWidget::windowModality
2600     \brief which windows are blocked by the modal widget
2601     \since 4.1
2602
2603     This property only makes sense for windows. A modal widget
2604     prevents widgets in other windows from getting input. The value of
2605     this property controls which windows are blocked when the widget
2606     is visible. Changing this property while the window is visible has
2607     no effect; you must hide() the widget first, then show() it again.
2608
2609     By default, this property is Qt::NonModal.
2610
2611     \sa isWindow(), QWidget::modal, QDialog
2612 */
2613
2614 Qt::WindowModality QWidget::windowModality() const
2615 {
2616     return static_cast<Qt::WindowModality>(data->window_modality);
2617 }
2618
2619 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2620 {
2621     data->window_modality = windowModality;
2622     // setModal_sys() will be called by setAttribute()
2623     setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2624     setAttribute(Qt::WA_SetWindowModality, true);
2625 }
2626
2627 /*!
2628     \fn bool QWidget::underMouse() const
2629
2630     Returns true if the widget is under the mouse cursor; otherwise
2631     returns false.
2632
2633     This value is not updated properly during drag and drop
2634     operations.
2635
2636     \sa enterEvent(), leaveEvent()
2637 */
2638
2639 /*!
2640     \property QWidget::minimized
2641     \brief whether this widget is minimized (iconified)
2642
2643     This property is only relevant for windows.
2644
2645     By default, this property is false.
2646
2647     \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2648 */
2649 bool QWidget::isMinimized() const
2650 { return data->window_state & Qt::WindowMinimized; }
2651
2652 /*!
2653     Shows the widget minimized, as an icon.
2654
2655     Calling this function only affects \l{isWindow()}{windows}.
2656
2657     \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2658         isMinimized()
2659 */
2660 void QWidget::showMinimized()
2661 {
2662     bool isMin = isMinimized();
2663     if (isMin && isVisible())
2664         return;
2665
2666     ensurePolished();
2667
2668     if (!isMin)
2669         setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2670     show();
2671 }
2672
2673 /*!
2674     \property QWidget::maximized
2675     \brief whether this widget is maximized
2676
2677     This property is only relevant for windows.
2678
2679     \note Due to limitations on some window systems, this does not always
2680     report the expected results (e.g., if the user on X11 maximizes the
2681     window via the window manager, Qt has no way of distinguishing this
2682     from any other resize). This is expected to improve as window manager
2683     protocols evolve.
2684
2685     By default, this property is false.
2686
2687     \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2688 */
2689 bool QWidget::isMaximized() const
2690 { return data->window_state & Qt::WindowMaximized; }
2691
2692
2693
2694 /*!
2695     Returns the current window state. The window state is a OR'ed
2696     combination of Qt::WindowState: Qt::WindowMinimized,
2697     Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2698
2699   \sa Qt::WindowState setWindowState()
2700  */
2701 Qt::WindowStates QWidget::windowState() const
2702 {
2703     return Qt::WindowStates(data->window_state);
2704 }
2705
2706 /*!\internal
2707
2708    The function sets the window state on child widgets similar to
2709    setWindowState(). The difference is that the window state changed
2710    event has the isOverride() flag set. It exists mainly to keep
2711    QWorkspace working.
2712  */
2713 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2714 {
2715     QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2716     data->window_state  = newstate;
2717     QApplication::sendEvent(this, &e);
2718 }
2719
2720 /*!
2721     \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2722
2723     Sets the window state to \a windowState. The window state is a OR'ed
2724     combination of Qt::WindowState: Qt::WindowMinimized,
2725     Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2726
2727     If the window is not visible (i.e. isVisible() returns false), the
2728     window state will take effect when show() is called. For visible
2729     windows, the change is immediate. For example, to toggle between
2730     full-screen and normal mode, use the following code:
2731
2732     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2733
2734     In order to restore and activate a minimized window (while
2735     preserving its maximized and/or full-screen state), use the following:
2736
2737     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2738
2739     Calling this function will hide the widget. You must call show() to make
2740     the widget visible again.
2741
2742     \note On some window systems Qt::WindowActive is not immediate, and may be
2743     ignored in certain cases.
2744
2745     When the window state changes, the widget receives a changeEvent()
2746     of type QEvent::WindowStateChange.
2747
2748     \sa Qt::WindowState windowState()
2749 */
2750
2751 /*!
2752     \property QWidget::fullScreen
2753     \brief whether the widget is shown in full screen mode
2754
2755     A widget in full screen mode occupies the whole screen area and does not
2756     display window decorations, such as a title bar.
2757
2758     By default, this property is false.
2759
2760     \sa windowState(), minimized, maximized
2761 */
2762 bool QWidget::isFullScreen() const
2763 { return data->window_state & Qt::WindowFullScreen; }
2764
2765 /*!
2766     Shows the widget in full-screen mode.
2767
2768     Calling this function only affects \l{isWindow()}{windows}.
2769
2770     To return from full-screen mode, call showNormal().
2771
2772     Full-screen mode works fine under Windows, but has certain
2773     problems under X. These problems are due to limitations of the
2774     ICCCM protocol that specifies the communication between X11
2775     clients and the window manager. ICCCM simply does not understand
2776     the concept of non-decorated full-screen windows. Therefore, the
2777     best we can do is to request a borderless window and place and
2778     resize it to fill the entire screen. Depending on the window
2779     manager, this may or may not work. The borderless window is
2780     requested using MOTIF hints, which are at least partially
2781     supported by virtually all modern window managers.
2782
2783     An alternative would be to bypass the window manager entirely and
2784     create a window with the Qt::X11BypassWindowManagerHint flag. This
2785     has other severe problems though, like totally broken keyboard focus
2786     and very strange effects on desktop changes or when the user raises
2787     other windows.
2788
2789     X11 window managers that follow modern post-ICCCM specifications
2790     support full-screen mode properly.
2791
2792     \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2793 */
2794 void QWidget::showFullScreen()
2795 {
2796 #ifdef Q_WS_MAC
2797     // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2798     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2799     if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2800         mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2801         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2802         mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2803     }
2804 #endif // Q_WS_MAC
2805     ensurePolished();
2806
2807     setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2808                    | Qt::WindowFullScreen);
2809     show();
2810     activateWindow();
2811 }
2812
2813 /*!
2814     Shows the widget maximized.
2815
2816     Calling this function only affects \l{isWindow()}{windows}.
2817
2818     On X11, this function may not work properly with certain window
2819     managers. See the \l{Window Geometry} documentation for an explanation.
2820
2821     \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2822 */
2823 void QWidget::showMaximized()
2824 {
2825     ensurePolished();
2826
2827     setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2828                    | Qt::WindowMaximized);
2829 #ifdef Q_WS_MAC
2830     // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2831     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2832     if (mainWindow)
2833     {
2834         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2835         if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2836             mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2837             mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2838         }
2839     }
2840 #endif // Q_WS_MAC
2841     show();
2842 }
2843
2844 /*!
2845     Restores the widget after it has been maximized or minimized.
2846
2847     Calling this function only affects \l{isWindow()}{windows}.
2848
2849     \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2850 */
2851 void QWidget::showNormal()
2852 {
2853     ensurePolished();
2854
2855     setWindowState(windowState() & ~(Qt::WindowMinimized
2856                                      | Qt::WindowMaximized
2857                                      | Qt::WindowFullScreen));
2858 #ifdef Q_WS_MAC
2859     // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2860     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2861     if (mainWindow)
2862     {
2863         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2864         if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2865             mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2866             mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2867         }
2868     }
2869 #endif // Q_WS_MAC
2870     show();
2871 }
2872
2873 /*!
2874     Returns true if this widget would become enabled if \a ancestor is
2875     enabled; otherwise returns false.
2876
2877
2878
2879     This is the case if neither the widget itself nor every parent up
2880     to but excluding \a ancestor has been explicitly disabled.
2881
2882     isEnabledTo(0) is equivalent to isEnabled().
2883
2884     \sa setEnabled() enabled
2885 */
2886
2887 bool QWidget::isEnabledTo(QWidget* ancestor) const
2888 {
2889     const QWidget * w = this;
2890     while (!w->testAttribute(Qt::WA_ForceDisabled)
2891             && !w->isWindow()
2892             && w->parentWidget()
2893             && w->parentWidget() != ancestor)
2894         w = w->parentWidget();
2895     return !w->testAttribute(Qt::WA_ForceDisabled);
2896 }
2897
2898 #ifndef QT_NO_ACTION
2899 /*!
2900     Appends the action \a action to this widget's list of actions.
2901
2902     All QWidgets have a list of \l{QAction}s, however they can be
2903     represented graphically in many different ways. The default use of
2904     the QAction list (as returned by actions()) is to create a context
2905     QMenu.
2906
2907     A QWidget should only have one of each action and adding an action
2908     it already has will not cause the same action to be in the widget twice.
2909
2910     The ownership of \a action is not transferred to this QWidget.
2911
2912     \sa removeAction(), insertAction(), actions(), QMenu
2913 */
2914 void QWidget::addAction(QAction *action)
2915 {
2916     insertAction(0, action);
2917 }
2918
2919 /*!
2920     Appends the actions \a actions to this widget's list of actions.
2921
2922     \sa removeAction(), QMenu, addAction()
2923 */
2924 void QWidget::addActions(QList<QAction*> actions)
2925 {
2926     for(int i = 0; i < actions.count(); i++)
2927         insertAction(0, actions.at(i));
2928 }
2929
2930 /*!
2931     Inserts the action \a action to this widget's list of actions,
2932     before the action \a before. It appends the action if \a before is 0 or
2933     \a before is not a valid action for this widget.
2934
2935     A QWidget should only have one of each action.
2936
2937     \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2938 */
2939 void QWidget::insertAction(QAction *before, QAction *action)
2940 {
2941     if(!action) {
2942         qWarning("QWidget::insertAction: Attempt to insert null action");
2943         return;
2944     }
2945
2946     Q_D(QWidget);
2947     if(d->actions.contains(action))
2948         removeAction(action);
2949
2950     int pos = d->actions.indexOf(before);
2951     if (pos < 0) {
2952         before = 0;
2953         pos = d->actions.size();
2954     }
2955     d->actions.insert(pos, action);
2956
2957     QActionPrivate *apriv = action->d_func();
2958     apriv->widgets.append(this);
2959
2960     QActionEvent e(QEvent::ActionAdded, action, before);
2961     QApplication::sendEvent(this, &e);
2962 }
2963
2964 /*!
2965     Inserts the actions \a actions to this widget's list of actions,
2966     before the action \a before. It appends the action if \a before is 0 or
2967     \a before is not a valid action for this widget.
2968
2969     A QWidget can have at most one of each action.
2970
2971     \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2972 */
2973 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2974 {
2975     for(int i = 0; i < actions.count(); ++i)
2976         insertAction(before, actions.at(i));
2977 }
2978
2979 /*!
2980     Removes the action \a action from this widget's list of actions.
2981     \sa insertAction(), actions(), insertAction()
2982 */
2983 void QWidget::removeAction(QAction *action)
2984 {
2985     if (!action)
2986         return;
2987
2988     Q_D(QWidget);
2989
2990     QActionPrivate *apriv = action->d_func();
2991     apriv->widgets.removeAll(this);
2992
2993     if (d->actions.removeAll(action)) {
2994         QActionEvent e(QEvent::ActionRemoved, action);
2995         QApplication::sendEvent(this, &e);
2996     }
2997 }
2998
2999 /*!
3000     Returns the (possibly empty) list of this widget's actions.
3001
3002     \sa contextMenuPolicy, insertAction(), removeAction()
3003 */
3004 QList<QAction*> QWidget::actions() const
3005 {
3006     Q_D(const QWidget);
3007     return d->actions;
3008 }
3009 #endif // QT_NO_ACTION
3010
3011 /*!
3012   \fn bool QWidget::isEnabledToTLW() const
3013   \obsolete
3014
3015   This function is deprecated. It is equivalent to isEnabled()
3016 */
3017
3018 /*!
3019     \property QWidget::enabled
3020     \brief whether the widget is enabled
3021
3022     In general an enabled widget handles keyboard and mouse events; a disabled
3023     widget does not. An exception is made with \l{QAbstractButton}.
3024
3025     Some widgets display themselves differently when they are
3026     disabled. For example a button might draw its label grayed out. If
3027     your widget needs to know when it becomes enabled or disabled, you
3028     can use the changeEvent() with type QEvent::EnabledChange.
3029
3030     Disabling a widget implicitly disables all its children. Enabling
3031     respectively enables all child widgets unless they have been
3032     explicitly disabled.
3033
3034     By default, this property is true.
3035
3036     \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3037 */
3038 void QWidget::setEnabled(bool enable)
3039 {
3040     Q_D(QWidget);
3041     setAttribute(Qt::WA_ForceDisabled, !enable);
3042     d->setEnabled_helper(enable);
3043 }
3044
3045 void QWidgetPrivate::setEnabled_helper(bool enable)
3046 {
3047     Q_Q(QWidget);
3048
3049     if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3050         return; // nothing we can do
3051
3052     if (enable != q->testAttribute(Qt::WA_Disabled))
3053         return; // nothing to do
3054
3055     q->setAttribute(Qt::WA_Disabled, !enable);
3056     updateSystemBackground();
3057
3058     if (!enable && q->window()->focusWidget() == q) {
3059         bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3060         if (!parentIsEnabled || !q->focusNextChild())
3061             q->clearFocus();
3062     }
3063
3064     Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3065     for (int i = 0; i < children.size(); ++i) {
3066         QWidget *w = qobject_cast<QWidget *>(children.at(i));
3067         if (w && !w->testAttribute(attribute))
3068             w->d_func()->setEnabled_helper(enable);
3069     }
3070 #if defined(Q_WS_X11)
3071     if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3072         // enforce the windows behavior of clearing the cursor on
3073         // disabled widgets
3074         qt_x11_enforce_cursor(q);
3075     }
3076 #endif
3077     if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3078         // enforce the windows behavior of clearing the cursor on
3079         // disabled widgets
3080         qt_qpa_set_cursor(q, false);
3081     }
3082 #if defined(Q_WS_MAC)
3083     setEnabled_helper_sys(enable);
3084 #endif
3085 #ifndef QT_NO_IM
3086     if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3087         QWidget *focusWidget = effectiveFocusWidget();
3088
3089         if (enable) {
3090             if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3091                 qApp->inputMethod()->update(Qt::ImEnabled);
3092         } else {
3093             qApp->inputMethod()->reset();
3094             qApp->inputMethod()->update(Qt::ImEnabled);
3095         }
3096     }
3097 #endif //QT_NO_IM
3098     QEvent e(QEvent::EnabledChange);
3099     QApplication::sendEvent(q, &e);
3100 }
3101
3102 /*!
3103     \property QWidget::acceptDrops
3104     \brief whether drop events are enabled for this widget
3105
3106     Setting this property to true announces to the system that this
3107     widget \e may be able to accept drop events.
3108
3109     If the widget is the desktop (windowType() == Qt::Desktop), this may
3110     fail if another application is using the desktop; you can call
3111     acceptDrops() to test if this occurs.
3112
3113     \warning Do not modify this property in a drag and drop event handler.
3114
3115     By default, this property is false.
3116
3117     \sa {Drag and Drop}
3118 */
3119 bool QWidget::acceptDrops() const
3120 {
3121     return testAttribute(Qt::WA_AcceptDrops);
3122 }
3123
3124 void QWidget::setAcceptDrops(bool on)
3125 {
3126     setAttribute(Qt::WA_AcceptDrops, on);
3127
3128 }
3129
3130
3131 /*!
3132     Disables widget input events if \a disable is true; otherwise
3133     enables input events.
3134
3135     See the \l enabled documentation for more information.
3136
3137     \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3138 */
3139 void QWidget::setDisabled(bool disable)
3140 {
3141     setEnabled(!disable);
3142 }
3143
3144 /*!
3145     \property QWidget::frameGeometry
3146     \brief geometry of the widget relative to its parent including any
3147     window frame
3148
3149     See the \l{Window Geometry} documentation for an overview of geometry
3150     issues with windows.
3151
3152     By default, this property contains a value that depends on the user's
3153     platform and screen geometry.
3154
3155     \sa geometry() x() y() pos()
3156 */
3157 QRect QWidget::frameGeometry() const
3158 {
3159     Q_D(const QWidget);
3160     if (isWindow() && ! (windowType() == Qt::Popup)) {
3161         QRect fs = d->frameStrut();
3162         return QRect(data->crect.x() - fs.left(),
3163                      data->crect.y() - fs.top(),
3164                      data->crect.width() + fs.left() + fs.right(),
3165                      data->crect.height() + fs.top() + fs.bottom());
3166     }
3167     return data->crect;
3168 }
3169
3170 /*!
3171     \property QWidget::x
3172
3173     \brief the x coordinate of the widget relative to its parent including
3174     any window frame
3175
3176     See the \l{Window Geometry} documentation for an overview of geometry
3177     issues with windows.
3178
3179     By default, this property has a value of 0.
3180
3181     \sa frameGeometry, y, pos
3182 */
3183 int QWidget::x() const
3184 {
3185     Q_D(const QWidget);
3186     if (isWindow() && ! (windowType() == Qt::Popup))
3187         return data->crect.x() - d->frameStrut().left();
3188     return data->crect.x();
3189 }
3190
3191 /*!
3192     \property QWidget::y
3193     \brief the y coordinate of the widget relative to its parent and
3194     including any window frame
3195
3196     See the \l{Window Geometry} documentation for an overview of geometry
3197     issues with windows.
3198
3199     By default, this property has a value of 0.
3200
3201     \sa frameGeometry, x, pos
3202 */
3203 int QWidget::y() const
3204 {
3205     Q_D(const QWidget);
3206     if (isWindow() && ! (windowType() == Qt::Popup))
3207         return data->crect.y() - d->frameStrut().top();
3208     return data->crect.y();
3209 }
3210
3211 /*!
3212     \property QWidget::pos
3213     \brief the position of the widget within its parent widget
3214
3215     If the widget is a window, the position is that of the widget on
3216     the desktop, including its frame.
3217
3218     When changing the position, the widget, if visible, receives a
3219     move event (moveEvent()) immediately. If the widget is not
3220     currently visible, it is guaranteed to receive an event before it
3221     is shown.
3222
3223     By default, this property contains a position that refers to the
3224     origin.
3225
3226     \warning Calling move() or setGeometry() inside moveEvent() can
3227     lead to infinite recursion.
3228
3229     See the \l{Window Geometry} documentation for an overview of geometry
3230     issues with windows.
3231
3232     \sa frameGeometry, size x(), y()
3233 */
3234 QPoint QWidget::pos() const
3235 {
3236     Q_D(const QWidget);
3237     if (isWindow() && ! (windowType() == Qt::Popup)) {
3238         QRect fs = d->frameStrut();
3239         return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3240     }
3241     return data->crect.topLeft();
3242 }
3243
3244 /*!
3245     \property QWidget::geometry
3246     \brief the geometry of the widget relative to its parent and
3247     excluding the window frame
3248
3249     When changing the geometry, the widget, if visible, receives a
3250     move event (moveEvent()) and/or a resize event (resizeEvent())
3251     immediately. If the widget is not currently visible, it is
3252     guaranteed to receive appropriate events before it is shown.
3253
3254     The size component is adjusted if it lies outside the range
3255     defined by minimumSize() and maximumSize().
3256
3257     \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3258     can lead to infinite recursion.
3259
3260     See the \l{Window Geometry} documentation for an overview of geometry
3261     issues with windows.
3262
3263     By default, this property contains a value that depends on the user's
3264     platform and screen geometry.
3265
3266     \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3267         resizeEvent(), minimumSize(), maximumSize()
3268 */
3269
3270 /*!
3271     \property QWidget::normalGeometry
3272
3273     \brief the geometry of the widget as it will appear when shown as
3274     a normal (not maximized or full screen) top-level widget
3275
3276     For child widgets this property always holds an empty rectangle.
3277
3278     By default, this property contains an empty rectangle.
3279
3280     \sa QWidget::windowState(), QWidget::geometry
3281 */
3282
3283 /*!
3284     \property QWidget::size
3285     \brief the size of the widget excluding any window frame
3286
3287     If the widget is visible when it is being resized, it receives a resize event
3288     (resizeEvent()) immediately. If the widget is not currently
3289     visible, it is guaranteed to receive an event before it is shown.
3290
3291     The size is adjusted if it lies outside the range defined by
3292     minimumSize() and maximumSize().
3293
3294     By default, this property contains a value that depends on the user's
3295     platform and screen geometry.
3296
3297     \warning Calling resize() or setGeometry() inside resizeEvent() can
3298     lead to infinite recursion.
3299
3300     \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3301     appear on screen. This also applies to windows.
3302
3303     \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3304 */
3305
3306 /*!
3307     \property QWidget::width
3308     \brief the width of the widget excluding any window frame
3309
3310     See the \l{Window Geometry} documentation for an overview of geometry
3311     issues with windows.
3312
3313     \note Do not use this function to find the width of a screen on
3314     a \l{QDesktopWidget}{multiple screen desktop}. Read
3315     \l{QDesktopWidget#Screen Geometry}{this note} for details.
3316
3317     By default, this property contains a value that depends on the user's
3318     platform and screen geometry.
3319
3320     \sa geometry, height, size
3321 */
3322
3323 /*!
3324     \property QWidget::height
3325     \brief the height of the widget excluding any window frame
3326
3327     See the \l{Window Geometry} documentation for an overview of geometry
3328     issues with windows.
3329
3330     \note Do not use this function to find the height of a screen
3331     on a \l{QDesktopWidget}{multiple screen desktop}. Read
3332     \l{QDesktopWidget#Screen Geometry}{this note} for details.
3333
3334     By default, this property contains a value that depends on the user's
3335     platform and screen geometry.
3336
3337     \sa geometry, width, size
3338 */
3339
3340 /*!
3341     \property QWidget::rect
3342     \brief the internal geometry of the widget excluding any window
3343     frame
3344
3345     The rect property equals QRect(0, 0, width(), height()).
3346
3347     See the \l{Window Geometry} documentation for an overview of geometry
3348     issues with windows.
3349
3350     By default, this property contains a value that depends on the user's
3351     platform and screen geometry.
3352
3353     \sa size
3354 */
3355
3356
3357 QRect QWidget::normalGeometry() const
3358 {
3359     Q_D(const QWidget);
3360     if (!d->extra || !d->extra->topextra)
3361         return QRect();
3362
3363     if (!isMaximized() && !isFullScreen())
3364         return geometry();
3365
3366     return d->topData()->normalGeometry;
3367 }
3368
3369
3370 /*!
3371     \property QWidget::childrenRect
3372     \brief the bounding rectangle of the widget's children
3373
3374     Hidden children are excluded.
3375
3376     By default, for a widget with no children, this property contains a
3377     rectangle with zero width and height located at the origin.
3378
3379     \sa childrenRegion() geometry()
3380 */
3381
3382 QRect QWidget::childrenRect() const
3383 {
3384     Q_D(const QWidget);
3385     QRect r(0, 0, 0, 0);
3386     for (int i = 0; i < d->children.size(); ++i) {
3387         QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3388         if (w && !w->isWindow() && !w->isHidden())
3389             r |= w->geometry();
3390     }
3391     return r;
3392 }
3393
3394 /*!
3395     \property QWidget::childrenRegion
3396     \brief the combined region occupied by the widget's children
3397
3398     Hidden children are excluded.
3399
3400     By default, for a widget with no children, this property contains an
3401     empty region.
3402
3403     \sa childrenRect() geometry() mask()
3404 */
3405
3406 QRegion QWidget::childrenRegion() const
3407 {
3408     Q_D(const QWidget);
3409     QRegion r;
3410     for (int i = 0; i < d->children.size(); ++i) {
3411         QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3412         if (w && !w->isWindow() && !w->isHidden()) {
3413             QRegion mask = w->mask();
3414             if (mask.isEmpty())
3415                 r |= w->geometry();
3416             else
3417                 r |= mask.translated(w->pos());
3418         }
3419     }
3420     return r;
3421 }
3422
3423
3424 /*!
3425     \property QWidget::minimumSize
3426     \brief the widget's minimum size
3427
3428     The widget cannot be resized to a smaller size than the minimum
3429     widget size. The widget's size is forced to the minimum size if
3430     the current size is smaller.
3431
3432     The minimum size set by this function will override the minimum size
3433     defined by QLayout. In order to unset the minimum size, use a
3434     value of \c{QSize(0, 0)}.
3435
3436     By default, this property contains a size with zero width and height.
3437
3438     \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3439 */
3440
3441 QSize QWidget::minimumSize() const
3442 {
3443     Q_D(const QWidget);
3444     return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3445 }
3446
3447 /*!
3448     \property QWidget::maximumSize
3449     \brief the widget's maximum size in pixels
3450
3451     The widget cannot be resized to a larger size than the maximum
3452     widget size.
3453
3454     By default, this property contains a size in which both width and height
3455     have values of 16777215.
3456
3457     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3458     of widgets.
3459
3460     \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3461 */
3462
3463 QSize QWidget::maximumSize() const
3464 {
3465     Q_D(const QWidget);
3466     return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3467                  : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3468 }
3469
3470
3471 /*!
3472     \property QWidget::minimumWidth
3473     \brief the widget's minimum width in pixels
3474
3475     This property corresponds to the width held by the \l minimumSize property.
3476
3477     By default, this property has a value of 0.
3478
3479     \sa minimumSize, minimumHeight
3480 */
3481
3482 /*!
3483     \property QWidget::minimumHeight
3484     \brief the widget's minimum height in pixels
3485
3486     This property corresponds to the height held by the \l minimumSize property.
3487
3488     By default, this property has a value of 0.
3489
3490     \sa minimumSize, minimumWidth
3491 */
3492
3493 /*!
3494     \property QWidget::maximumWidth
3495     \brief the widget's maximum width in pixels
3496
3497     This property corresponds to the width held by the \l maximumSize property.
3498
3499     By default, this property contains a value of 16777215.
3500
3501     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3502     of widgets.
3503
3504     \sa maximumSize, maximumHeight
3505 */
3506
3507 /*!
3508     \property QWidget::maximumHeight
3509     \brief the widget's maximum height in pixels
3510
3511     This property corresponds to the height held by the \l maximumSize property.
3512
3513     By default, this property contains a value of 16777215.
3514
3515     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3516     of widgets.
3517
3518     \sa maximumSize, maximumWidth
3519 */
3520
3521 /*!
3522     \property QWidget::sizeIncrement
3523     \brief the size increment of the widget
3524
3525     When the user resizes the window, the size will move in steps of
3526     sizeIncrement().width() pixels horizontally and
3527     sizeIncrement.height() pixels vertically, with baseSize() as the
3528     basis. Preferred widget sizes are for non-negative integers \e i
3529     and \e j:
3530     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3531
3532     Note that while you can set the size increment for all widgets, it
3533     only affects windows.
3534
3535     By default, this property contains a size with zero width and height.
3536
3537     \warning The size increment has no effect under Windows, and may
3538     be disregarded by the window manager on X11.
3539
3540     \sa size, minimumSize, maximumSize
3541 */
3542 QSize QWidget::sizeIncrement() const
3543 {
3544     Q_D(const QWidget);
3545     return (d->extra && d->extra->topextra)
3546         ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3547         : QSize(0, 0);
3548 }
3549
3550 /*!
3551     \property QWidget::baseSize
3552     \brief the base size of the widget
3553
3554     The base size is used to calculate a proper widget size if the
3555     widget defines sizeIncrement().
3556
3557     By default, for a newly-created widget, this property contains a size with
3558     zero width and height.
3559
3560     \sa setSizeIncrement()
3561 */
3562
3563 QSize QWidget::baseSize() const
3564 {
3565     Q_D(const QWidget);
3566     return (d->extra != 0 && d->extra->topextra != 0)
3567         ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3568         : QSize(0, 0);
3569 }
3570
3571 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3572 {
3573     Q_Q(QWidget);
3574
3575     int mw = minw, mh = minh;
3576     if (mw == QWIDGETSIZE_MAX)
3577         mw = 0;
3578     if (mh == QWIDGETSIZE_MAX)
3579         mh = 0;
3580     if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3581         qWarning("QWidget::setMinimumSize: (%s/%s) "
3582                 "The largest allowed size is (%d,%d)",
3583                  q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3584                 QWIDGETSIZE_MAX);
3585         minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3586         minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3587     }
3588     if (minw < 0 || minh < 0) {
3589         qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3590                 "are not possible",
3591                 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3592         minw = mw = qMax(minw, 0);
3593         minh = mh = qMax(minh, 0);
3594     }
3595     createExtra();
3596     if (extra->minw == mw && extra->minh == mh)
3597         return false;
3598     extra->minw = mw;
3599     extra->minh = mh;
3600     extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3601     return true;
3602 }
3603
3604 /*!
3605     \overload
3606
3607     This function corresponds to setMinimumSize(QSize(minw, minh)).
3608     Sets the minimum width to \a minw and the minimum height to \a
3609     minh.
3610 */
3611
3612 void QWidget::setMinimumSize(int minw, int minh)
3613 {
3614     Q_D(QWidget);
3615     if (!d->setMinimumSize_helper(minw, minh))
3616         return;
3617
3618     if (isWindow())
3619         d->setConstraints_sys();
3620     if (minw > width() || minh > height()) {
3621         bool resized = testAttribute(Qt::WA_Resized);
3622         bool maximized = isMaximized();
3623         resize(qMax(minw,width()), qMax(minh,height()));
3624         setAttribute(Qt::WA_Resized, resized); //not a user resize
3625         if (maximized)
3626             data->window_state = data->window_state | Qt::WindowMaximized;
3627     }
3628 #ifndef QT_NO_GRAPHICSVIEW
3629     if (d->extra) {
3630         if (d->extra->proxyWidget)
3631             d->extra->proxyWidget->setMinimumSize(minw, minh);
3632     }
3633 #endif
3634     d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3635 }
3636
3637 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3638 {
3639     Q_Q(QWidget);
3640     if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3641         qWarning("QWidget::setMaximumSize: (%s/%s) "
3642                 "The largest allowed size is (%d,%d)",
3643                  q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3644                 QWIDGETSIZE_MAX);
3645         maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3646         maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3647     }
3648     if (maxw < 0 || maxh < 0) {
3649         qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3650                 "are not possible",
3651                 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3652         maxw = qMax(maxw, 0);
3653         maxh = qMax(maxh, 0);
3654     }
3655     createExtra();
3656     if (extra->maxw == maxw && extra->maxh == maxh)
3657         return false;
3658     extra->maxw = maxw;
3659     extra->maxh = maxh;
3660     extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3661                              (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3662     return true;
3663 }
3664
3665 /*!
3666     \overload
3667
3668     This function corresponds to setMaximumSize(QSize(\a maxw, \a
3669     maxh)). Sets the maximum width to \a maxw and the maximum height
3670     to \a maxh.
3671 */
3672 void QWidget::setMaximumSize(int maxw, int maxh)
3673 {
3674     Q_D(QWidget);
3675     if (!d->setMaximumSize_helper(maxw, maxh))
3676         return;
3677
3678     if (isWindow())
3679         d->setConstraints_sys();
3680     if (maxw < width() || maxh < height()) {
3681         bool resized = testAttribute(Qt::WA_Resized);
3682         resize(qMin(maxw,width()), qMin(maxh,height()));
3683         setAttribute(Qt::WA_Resized, resized); //not a user resize
3684     }
3685
3686 #ifndef QT_NO_GRAPHICSVIEW
3687     if (d->extra) {
3688         if (d->extra->proxyWidget)
3689             d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3690     }
3691 #endif
3692
3693     d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3694 }
3695
3696 /*!
3697     \overload
3698
3699     Sets the x (width) size increment to \a w and the y (height) size
3700     increment to \a h.
3701 */
3702 void QWidget::setSizeIncrement(int w, int h)
3703 {
3704     Q_D(QWidget);
3705     d->createTLExtra();
3706     QTLWExtra* x = d->topData();
3707     if (x->incw == w && x->inch == h)
3708         return;
3709     x->incw = w;
3710     x->inch = h;
3711     if (isWindow())
3712         d->setConstraints_sys();
3713 }
3714
3715 /*!
3716     \overload
3717
3718     This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3719     the widgets base size to width \a basew and height \a baseh.
3720 */
3721 void QWidget::setBaseSize(int basew, int baseh)
3722 {
3723     Q_D(QWidget);
3724     d->createTLExtra();
3725     QTLWExtra* x = d->topData();
3726     if (x->basew == basew && x->baseh == baseh)
3727         return;
3728     x->basew = basew;
3729     x->baseh = baseh;
3730     if (isWindow())
3731         d->setConstraints_sys();
3732 }
3733
3734 /*!
3735     Sets both the minimum and maximum sizes of the widget to \a s,
3736     thereby preventing it from ever growing or shrinking.
3737
3738     This will override the default size constraints set by QLayout.
3739
3740     To remove constraints, set the size to QWIDGETSIZE_MAX.
3741
3742     Alternatively, if you want the widget to have a
3743     fixed size based on its contents, you can call
3744     QLayout::setSizeConstraint(QLayout::SetFixedSize);
3745
3746     \sa maximumSize, minimumSize
3747 */
3748
3749 void QWidget::setFixedSize(const QSize & s)
3750 {
3751     setFixedSize(s.width(), s.height());
3752 }
3753
3754
3755 /*!
3756     \fn void QWidget::setFixedSize(int w, int h)
3757     \overload
3758
3759     Sets the width of the widget to \a w and the height to \a h.
3760 */
3761
3762 void QWidget::setFixedSize(int w, int h)
3763 {
3764     Q_D(QWidget);
3765     bool minSizeSet = d->setMinimumSize_helper(w, h);
3766     bool maxSizeSet = d->setMaximumSize_helper(w, h);
3767     if (!minSizeSet && !maxSizeSet)
3768         return;
3769
3770     if (isWindow())
3771         d->setConstraints_sys();
3772     else
3773         d->updateGeometry_helper(true);
3774
3775     if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3776         resize(w, h);
3777 }
3778
3779 void QWidget::setMinimumWidth(int w)
3780 {
3781     Q_D(QWidget);
3782     d->createExtra();
3783     uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3784     setMinimumSize(w, minimumSize().height());
3785     d->extra->explicitMinSize = expl;
3786 }
3787
3788 void QWidget::setMinimumHeight(int h)
3789 {
3790     Q_D(QWidget);
3791     d->createExtra();
3792     uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3793     setMinimumSize(minimumSize().width(), h);
3794     d->extra->explicitMinSize = expl;
3795 }
3796
3797 void QWidget::setMaximumWidth(int w)
3798 {
3799     Q_D(QWidget);
3800     d->createExtra();
3801     uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3802     setMaximumSize(w, maximumSize().height());
3803     d->extra->explicitMaxSize = expl;
3804 }
3805
3806 void QWidget::setMaximumHeight(int h)
3807 {
3808     Q_D(QWidget);
3809     d->createExtra();
3810     uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3811     setMaximumSize(maximumSize().width(), h);
3812     d->extra->explicitMaxSize = expl;
3813 }
3814
3815 /*!
3816     Sets both the minimum and maximum width of the widget to \a w
3817     without changing the heights. Provided for convenience.
3818
3819     \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3820 */
3821
3822 void QWidget::setFixedWidth(int w)
3823 {
3824     Q_D(QWidget);
3825     d->createExtra();
3826     uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3827     uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3828     setMinimumSize(w, minimumSize().height());
3829     setMaximumSize(w, maximumSize().height());
3830     d->extra->explicitMinSize = explMin;
3831     d->extra->explicitMaxSize = explMax;
3832 }
3833
3834
3835 /*!
3836     Sets both the minimum and maximum heights of the widget to \a h
3837     without changing the widths. Provided for convenience.
3838
3839     \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3840 */
3841
3842 void QWidget::setFixedHeight(int h)
3843 {
3844     Q_D(QWidget);
3845     d->createExtra();
3846     uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3847     uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3848     setMinimumSize(minimumSize().width(), h);
3849     setMaximumSize(maximumSize().width(), h);
3850     d->extra->explicitMinSize = explMin;
3851     d->extra->explicitMaxSize = explMax;
3852 }
3853
3854
3855 /*!
3856     Translates the widget coordinate \a pos to the coordinate system
3857     of \a parent. The \a parent must not be 0 and must be a parent
3858     of the calling widget.
3859
3860     \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3861 */
3862
3863 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3864 {
3865     QPoint p = pos;
3866     if (parent) {
3867         const QWidget * w = this;
3868         while (w != parent) {
3869             Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3870                        "parent must be in parent hierarchy");
3871             p = w->mapToParent(p);
3872             w = w->parentWidget();
3873         }
3874     }
3875     return p;
3876 }
3877
3878
3879 /*!
3880     Translates the widget coordinate \a pos from the coordinate system
3881     of \a parent to this widget's coordinate system. The \a parent
3882     must not be 0 and must be a parent of the calling widget.
3883
3884     \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3885 */
3886
3887 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3888 {
3889     QPoint p(pos);
3890     if (parent) {
3891         const QWidget * w = this;
3892         while (w != parent) {
3893             Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3894                        "parent must be in parent hierarchy");
3895
3896             p = w->mapFromParent(p);
3897             w = w->parentWidget();
3898         }
3899     }
3900     return p;
3901 }
3902
3903
3904 /*!
3905     Translates the widget coordinate \a pos to a coordinate in the
3906     parent widget.
3907
3908     Same as mapToGlobal() if the widget has no parent.
3909
3910     \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3911 */
3912
3913 QPoint QWidget::mapToParent(const QPoint &pos) const
3914 {
3915     return pos + data->crect.topLeft();
3916 }
3917
3918 /*!
3919     Translates the parent widget coordinate \a pos to widget
3920     coordinates.
3921
3922     Same as mapFromGlobal() if the widget has no parent.
3923
3924     \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3925 */
3926
3927 QPoint QWidget::mapFromParent(const QPoint &pos) const
3928 {
3929     return pos - data->crect.topLeft();
3930 }
3931
3932
3933 /*!
3934     Returns the window for this widget, i.e. the next ancestor widget
3935     that has (or could have) a window-system frame.
3936
3937     If the widget is a window, the widget itself is returned.
3938
3939     Typical usage is changing the window title:
3940
3941     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3942
3943     \sa isWindow()
3944 */
3945
3946 QWidget *QWidget::window() const
3947 {
3948     QWidget *w = (QWidget *)this;
3949     QWidget *p = w->parentWidget();
3950     while (!w->isWindow() && p) {
3951         w = p;
3952         p = p->parentWidget();
3953     }
3954     return w;
3955 }
3956
3957 /*!
3958     \since 4.4
3959
3960     Returns the native parent for this widget, i.e. the next ancestor widget
3961     that has a system identifier, or 0 if it does not have any native parent.
3962
3963     \sa effectiveWinId()
3964 */
3965 QWidget *QWidget::nativeParentWidget() const
3966 {
3967     QWidget *parent = parentWidget();
3968     while (parent && !parent->internalWinId())
3969         parent = parent->parentWidget();
3970     return parent;
3971 }
3972
3973 /*! \fn QWidget *QWidget::topLevelWidget() const
3974     \obsolete
3975
3976     Use window() instead.
3977 */
3978
3979
3980
3981 /*!
3982   Returns the background role of the widget.
3983
3984   The background role defines the brush from the widget's \l palette that
3985   is used to render the background.
3986
3987   If no explicit background role is set, the widget inherts its parent
3988   widget's background role.
3989
3990   \sa setBackgroundRole(), foregroundRole()
3991  */
3992 QPalette::ColorRole QWidget::backgroundRole() const
3993 {
3994
3995     const QWidget *w = this;
3996     do {
3997         QPalette::ColorRole role = w->d_func()->bg_role;
3998         if (role != QPalette::NoRole)
3999             return role;
4000         if (w->isWindow() || w->windowType() == Qt::SubWindow)
4001             break;
4002         w = w->parentWidget();
4003     } while (w);
4004     return QPalette::Window;
4005 }
4006
4007 /*!
4008   Sets the background role of the widget to \a role.
4009
4010   The background role defines the brush from the widget's \l palette that
4011   is used to render the background.
4012
4013   If \a role is QPalette::NoRole, then the widget inherits its
4014   parent's background role.
4015
4016   Note that styles are free to choose any color from the palette.
4017   You can modify the palette or set a style sheet if you don't
4018   achieve the result you want with setBackgroundRole().
4019
4020   \sa backgroundRole(), foregroundRole()
4021  */
4022
4023 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4024 {
4025     Q_D(QWidget);
4026     d->bg_role = role;
4027     d->updateSystemBackground();
4028     d->propagatePaletteChange();
4029     d->updateIsOpaque();
4030 }
4031
4032 /*!
4033   Returns the foreground role.
4034
4035   The foreground role defines the color from the widget's \l palette that
4036   is used to draw the foreground.
4037
4038   If no explicit foreground role is set, the function returns a role
4039   that contrasts with the background role.
4040
4041   \sa setForegroundRole(), backgroundRole()
4042  */
4043 QPalette::ColorRole QWidget::foregroundRole() const
4044 {
4045     Q_D(const QWidget);
4046     QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4047     if (rl != QPalette::NoRole)
4048         return rl;
4049     QPalette::ColorRole role = QPalette::WindowText;
4050     switch (backgroundRole()) {
4051     case QPalette::Button:
4052         role = QPalette::ButtonText;
4053         break;
4054     case QPalette::Base:
4055         role = QPalette::Text;
4056         break;
4057     case QPalette::Dark:
4058     case QPalette::Shadow:
4059         role = QPalette::Light;
4060         break;
4061     case QPalette::Highlight:
4062         role = QPalette::HighlightedText;
4063         break;
4064     case QPalette::ToolTipBase:
4065         role = QPalette::ToolTipText;
4066         break;
4067     default:
4068         ;
4069     }
4070     return role;
4071 }
4072
4073 /*!
4074   Sets the foreground role of the widget to \a role.
4075
4076   The foreground role defines the color from the widget's \l palette that
4077   is used to draw the foreground.
4078
4079   If \a role is QPalette::NoRole, the widget uses a foreground role
4080   that contrasts with the background role.
4081
4082   Note that styles are free to choose any color from the palette.
4083   You can modify the palette or set a style sheet if you don't
4084   achieve the result you want with setForegroundRole().
4085
4086   \sa foregroundRole(), backgroundRole()
4087  */
4088 void QWidget::setForegroundRole(QPalette::ColorRole role)
4089 {
4090     Q_D(QWidget);
4091     d->fg_role = role;
4092     d->updateSystemBackground();
4093     d->propagatePaletteChange();
4094 }
4095
4096 /*!
4097     \property QWidget::palette
4098     \brief the widget's palette
4099
4100     This property describes the widget's palette. The palette is used by the
4101     widget's style when rendering standard components, and is available as a
4102     means to ensure that custom widgets can maintain consistency with the
4103     native platform's look and feel. It's common that different platforms, or
4104     different styles, have different palettes.
4105
4106     When you assign a new palette to a widget, the color roles from this
4107     palette are combined with the widget's default palette to form the
4108     widget's final palette. The palette entry for the widget's background role
4109     is used to fill the widget's background (see QWidget::autoFillBackground),
4110     and the foreground role initializes QPainter's pen.
4111
4112     The default depends on the system environment. QApplication maintains a
4113     system/theme palette which serves as a default for all widgets.  There may
4114     also be special palette defaults for certain types of widgets (e.g., on
4115     Windows XP and Vista, all classes that derive from QMenuBar have a special
4116     default palette). You can also define default palettes for widgets
4117     yourself by passing a custom palette and the name of a widget to
4118     QApplication::setPalette(). Finally, the style always has the option of
4119     polishing the palette as it's assigned (see QStyle::polish()).
4120
4121     QWidget propagates explicit palette roles from parent to child. If you
4122     assign a brush or color to a specific role on a palette and assign that
4123     palette to a widget, that role will propagate to all the widget's
4124     children, overriding any system defaults for that role. Note that palettes
4125     by default don't propagate to windows (see isWindow()) unless the
4126     Qt::WA_WindowPropagation attribute is enabled.
4127
4128     QWidget's palette propagation is similar to its font propagation.
4129
4130     The current style, which is used to render the content of all standard Qt
4131     widgets, is free to choose colors and brushes from the widget palette, or
4132     in some cases, to ignore the palette (partially, or completely). In
4133     particular, certain styles like GTK style, Mac style, Windows XP, and
4134     Vista style, depend on third party APIs to render the content of widgets,
4135     and these styles typically do not follow the palette. Because of this,
4136     assigning roles to a widget's palette is not guaranteed to change the
4137     appearance of the widget. Instead, you may choose to apply a \l
4138     styleSheet. You can refer to our Knowledge Base article
4139     \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4140     information.
4141
4142     \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4143     When using style sheets, the palette of a widget can be customized using
4144     the "color", "background-color", "selection-color",
4145     "selection-background-color" and "alternate-background-color".
4146
4147     \sa QApplication::palette(), QWidget::font()
4148 */
4149 const QPalette &QWidget::palette() const
4150 {
4151     if (!isEnabled()) {
4152         data->pal.setCurrentColorGroup(QPalette::Disabled);
4153     } else if ((!isVisible() || isActiveWindow())
4154 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4155         && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4156 #endif
4157         ) {
4158         data->pal.setCurrentColorGroup(QPalette::Active);
4159     } else {
4160 #ifdef Q_WS_MAC
4161         extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4162         if (qt_mac_can_clickThrough(this))
4163             data->pal.setCurrentColorGroup(QPalette::Active);
4164         else
4165 #endif
4166             data->pal.setCurrentColorGroup(QPalette::Inactive);
4167     }
4168     return data->pal;
4169 }
4170
4171 void QWidget::setPalette(const QPalette &palette)
4172 {
4173     Q_D(QWidget);
4174     setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4175
4176     // Determine which palette is inherited from this widget's ancestors and
4177     // QApplication::palette, resolve this against \a palette (attributes from
4178     // the inherited palette are copied over this widget's palette). Then
4179     // propagate this palette to this widget's children.
4180     QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4181     QPalette resolvedPalette = palette.resolve(naturalPalette);
4182     d->setPalette_helper(resolvedPalette);
4183 }
4184
4185 /*!
4186     \internal
4187
4188     Returns the palette that the widget \a w inherits from its ancestors and
4189     QApplication::palette. \a inheritedMask is the combination of the widget's
4190     ancestors palette request masks (i.e., which attributes from the parent
4191     widget's palette are implicitly imposed on this widget by the user). Note
4192     that this font does not take into account the palette set on \a w itself.
4193 */
4194 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4195 {
4196     Q_Q(const QWidget);
4197     QPalette naturalPalette = QApplication::palette(q);
4198     if (!q->testAttribute(Qt::WA_StyleSheet)
4199         && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4200 #ifndef QT_NO_GRAPHICSVIEW
4201             || (extra && extra->proxyWidget)
4202 #endif //QT_NO_GRAPHICSVIEW
4203             )) {
4204         if (QWidget *p = q->parentWidget()) {
4205             if (!p->testAttribute(Qt::WA_StyleSheet)) {
4206                 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4207                     QPalette inheritedPalette = p->palette();
4208                     inheritedPalette.resolve(inheritedMask);
4209                     naturalPalette = inheritedPalette.resolve(naturalPalette);
4210                 } else {
4211                     naturalPalette = p->palette();
4212                 }
4213             }
4214         }
4215 #ifndef QT_NO_GRAPHICSVIEW
4216         else if (extra && extra->proxyWidget) {
4217             QPalette inheritedPalette = extra->proxyWidget->palette();
4218             inheritedPalette.resolve(inheritedMask);
4219             naturalPalette = inheritedPalette.resolve(naturalPalette);
4220         }
4221 #endif //QT_NO_GRAPHICSVIEW
4222     }
4223     naturalPalette.resolve(0);
4224     return naturalPalette;
4225 }
4226 /*!
4227     \internal
4228
4229     Determine which palette is inherited from this widget's ancestors and
4230     QApplication::palette, resolve this against this widget's palette
4231     (attributes from the inherited palette are copied over this widget's
4232     palette). Then propagate this palette to this widget's children.
4233 */
4234 void QWidgetPrivate::resolvePalette()
4235 {
4236     QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4237     QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4238     setPalette_helper(resolvedPalette);
4239 }
4240
4241 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4242 {
4243     Q_Q(QWidget);
4244     if (data.pal == palette && data.pal.resolve() == palette.resolve())
4245         return;
4246     data.pal = palette;
4247     updateSystemBackground();
4248     propagatePaletteChange();
4249     updateIsOpaque();
4250     q->update();
4251     updateIsOpaque();
4252 }
4253
4254 /*!
4255     \property QWidget::font
4256     \brief the font currently set for the widget
4257
4258     This property describes the widget's requested font. The font is used by
4259     the widget's style when rendering standard components, and is available as
4260     a means to ensure that custom widgets can maintain consistency with the
4261     native platform's look and feel. It's common that different platforms, or
4262     different styles, define different fonts for an application.
4263
4264     When you assign a new font to a widget, the properties from this font are
4265     combined with the widget's default font to form the widget's final
4266     font. You can call fontInfo() to get a copy of the widget's final
4267     font. The final font is also used to initialize QPainter's font.
4268
4269     The default depends on the system environment. QApplication maintains a
4270     system/theme font which serves as a default for all widgets.  There may
4271     also be special font defaults for certain types of widgets. You can also
4272     define default fonts for widgets yourself by passing a custom font and the
4273     name of a widget to QApplication::setFont(). Finally, the font is matched
4274     against Qt's font database to find the best match.
4275
4276     QWidget propagates explicit font properties from parent to child. If you
4277     change a specific property on a font and assign that font to a widget,
4278     that property will propagate to all the widget's children, overriding any
4279     system defaults for that property. Note that fonts by default don't
4280     propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4281     attribute is enabled.
4282
4283     QWidget's font propagation is similar to its palette propagation.
4284
4285     The current style, which is used to render the content of all standard Qt
4286     widgets, is free to choose to use the widget font, or in some cases, to
4287     ignore it (partially, or completely). In particular, certain styles like
4288     GTK style, Mac style, Windows XP, and Vista style, apply special
4289     modifications to the widget font to match the platform's native look and
4290     feel. Because of this, assigning properties to a widget's font is not
4291     guaranteed to change the appearance of the widget. Instead, you may choose
4292     to apply a \l styleSheet.
4293
4294     \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4295     style sheets will take precedence if the settings conflict.
4296
4297     \sa fontInfo(), fontMetrics()
4298 */
4299
4300 void QWidget::setFont(const QFont &font)
4301 {
4302     Q_D(QWidget);
4303
4304 #ifndef QT_NO_STYLE_STYLESHEET
4305     const QStyleSheetStyle* style;
4306     if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4307         style->saveWidgetFont(this, font);
4308     }
4309 #endif
4310
4311     setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4312
4313     // Determine which font is inherited from this widget's ancestors and
4314     // QApplication::font, resolve this against \a font (attributes from the
4315     // inherited font are copied over). Then propagate this font to this
4316     // widget's children.
4317     QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4318     QFont resolvedFont = font.resolve(naturalFont);
4319     d->setFont_helper(resolvedFont);
4320 }
4321
4322 /*
4323     \internal
4324
4325     Returns the font that the widget \a w inherits from its ancestors and
4326     QApplication::font. \a inheritedMask is the combination of the widget's
4327     ancestors font request masks (i.e., which attributes from the parent
4328     widget's font are implicitly imposed on this widget by the user). Note
4329     that this font does not take into account the font set on \a w itself.
4330
4331     ### Stylesheet has a different font propagation mechanism. When a stylesheet
4332         is applied, fonts are not propagated anymore
4333 */
4334 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4335 {
4336     Q_Q(const QWidget);
4337     QFont naturalFont = QApplication::font(q);
4338     if (!q->testAttribute(Qt::WA_StyleSheet)
4339         && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4340 #ifndef QT_NO_GRAPHICSVIEW
4341             || (extra && extra->proxyWidget)
4342 #endif //QT_NO_GRAPHICSVIEW
4343             )) {
4344         if (QWidget *p = q->parentWidget()) {
4345             if (!p->testAttribute(Qt::WA_StyleSheet)) {
4346                 if (!naturalFont.isCopyOf(QApplication::font())) {
4347                     QFont inheritedFont = p->font();
4348                     inheritedFont.resolve(inheritedMask);
4349                     naturalFont = inheritedFont.resolve(naturalFont);
4350                 } else {
4351                     naturalFont = p->font();
4352                 }
4353             }
4354         }
4355 #ifndef QT_NO_GRAPHICSVIEW
4356         else if (extra && extra->proxyWidget) {
4357             QFont inheritedFont = extra->proxyWidget->font();
4358             inheritedFont.resolve(inheritedMask);
4359             naturalFont = inheritedFont.resolve(naturalFont);
4360         }
4361 #endif //QT_NO_GRAPHICSVIEW
4362     }
4363     naturalFont.resolve(0);
4364     return naturalFont;
4365 }
4366
4367 /*!
4368     \internal
4369
4370     Determine which font is implicitly imposed on this widget by its ancestors
4371     and QApplication::font, resolve this against its own font (attributes from
4372     the implicit font are copied over). Then propagate this font to this
4373     widget's children.
4374 */
4375 void QWidgetPrivate::resolveFont()
4376 {
4377     QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4378     QFont resolvedFont = data.fnt.resolve(naturalFont);
4379     setFont_helper(resolvedFont);
4380 }
4381
4382 /*!
4383     \internal
4384
4385     Assign \a font to this widget, and propagate it to all children, except
4386     style sheet widgets (handled differently) and windows that don't enable
4387     window propagation.  \a implicitMask is the union of all ancestor widgets'
4388     font request masks, and determines which attributes from this widget's
4389     font should propagate.
4390 */
4391 void QWidgetPrivate::updateFont(const QFont &font)
4392 {
4393     Q_Q(QWidget);
4394 #ifndef QT_NO_STYLE_STYLESHEET
4395     const QStyleSheetStyle* cssStyle;
4396     cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4397 #endif
4398
4399     data.fnt = QFont(font, q);
4400 #if defined(Q_WS_X11)
4401     // make sure the font set on this widget is associated with the correct screen
4402     data.fnt.x11SetScreen(xinfo.screen());
4403 #endif
4404     // Combine new mask with natural mask and propagate to children.
4405 #ifndef QT_NO_GRAPHICSVIEW
4406     if (!q->parentWidget() && extra && extra->proxyWidget) {
4407         QGraphicsProxyWidget *p = extra->proxyWidget;
4408         inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4409     } else
4410 #endif //QT_NO_GRAPHICSVIEW
4411     if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4412         inheritedFontResolveMask = 0;
4413     }
4414     uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4415
4416     for (int i = 0; i < children.size(); ++i) {
4417         QWidget *w = qobject_cast<QWidget*>(children.at(i));
4418         if (w) {
4419             if (0) {
4420 #ifndef QT_NO_STYLE_STYLESHEET
4421             } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4422                 // Style sheets follow a different font propagation scheme.
4423                 if (cssStyle)
4424                     cssStyle->updateStyleSheetFont(w);
4425 #endif
4426             } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4427                 // Propagate font changes.
4428                 QWidgetPrivate *wd = w->d_func();
4429                 wd->inheritedFontResolveMask = newMask;
4430                 wd->resolveFont();
4431             }
4432         }
4433     }
4434
4435 #ifndef QT_NO_STYLE_STYLESHEET
4436     if (cssStyle) {
4437         cssStyle->updateStyleSheetFont(q);
4438     }
4439 #endif
4440
4441     QEvent e(QEvent::FontChange);
4442     QApplication::sendEvent(q, &e);
4443 }
4444
4445 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4446 {
4447     Q_Q(QWidget);
4448
4449     if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4450         return;
4451     q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4452     if (!children.isEmpty()) {
4453         for (int i = 0; i < children.size(); ++i) {
4454             QWidget *w = qobject_cast<QWidget*>(children.at(i));
4455             if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4456                 w->d_func()->setLayoutDirection_helper(direction);
4457         }
4458     }
4459     QEvent e(QEvent::LayoutDirectionChange);
4460     QApplication::sendEvent(q, &e);
4461 }
4462
4463 void QWidgetPrivate::resolveLayoutDirection()
4464 {
4465     Q_Q(const QWidget);
4466     if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4467         setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4468 }
4469
4470 /*!
4471     \property QWidget::layoutDirection
4472
4473     \brief the layout direction for this widget
4474
4475     By default, this property is set to Qt::LeftToRight.
4476
4477     When the layout direction is set on a widget, it will propagate to
4478     the widget's children, but not to a child that is a window and not
4479     to a child for which setLayoutDirection() has been explicitly
4480     called. Also, child widgets added \e after setLayoutDirection()
4481     has been called for the parent do not inherit the parent's layout
4482     direction.
4483
4484     This method no longer affects text layout direction since Qt 4.7.
4485
4486     \sa QApplication::layoutDirection
4487 */
4488 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4489 {
4490     Q_D(QWidget);
4491
4492     if (direction == Qt::LayoutDirectionAuto) {
4493         unsetLayoutDirection();
4494         return;
4495     }
4496
4497     setAttribute(Qt::WA_SetLayoutDirection);
4498     d->setLayoutDirection_helper(direction);
4499 }
4500
4501 Qt::LayoutDirection QWidget::layoutDirection() const
4502 {
4503     return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4504 }
4505
4506 void QWidget::unsetLayoutDirection()
4507 {
4508     Q_D(QWidget);
4509     setAttribute(Qt::WA_SetLayoutDirection, false);
4510     d->resolveLayoutDirection();
4511 }
4512
4513 /*!
4514     \fn QFontMetrics QWidget::fontMetrics() const
4515
4516     Returns the font metrics for the widget's current font.
4517     Equivalent to QFontMetrics(widget->font()).
4518
4519     \sa font(), fontInfo(), setFont()
4520 */
4521
4522 /*!
4523     \fn QFontInfo QWidget::fontInfo() const
4524
4525     Returns the font info for the widget's current font.
4526     Equivalent to QFontInto(widget->font()).
4527
4528     \sa font(), fontMetrics(), setFont()
4529 */
4530
4531
4532 /*!
4533     \property QWidget::cursor
4534     \brief the cursor shape for this widget
4535
4536     The mouse cursor will assume this shape when it's over this
4537     widget. See the \link Qt::CursorShape list of predefined cursor
4538     objects\endlink for a range of useful shapes.
4539
4540     An editor widget might use an I-beam cursor:
4541     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4542
4543     If no cursor has been set, or after a call to unsetCursor(), the
4544     parent's cursor is used.
4545
4546     By default, this property contains a cursor with the Qt::ArrowCursor
4547     shape.
4548
4549     Some underlying window implementations will reset the cursor if it
4550     leaves a widget even if the mouse is grabbed. If you want to have
4551     a cursor set for all widgets, even when outside the window, consider
4552     QApplication::setOverrideCursor().
4553
4554     \sa QApplication::setOverrideCursor()
4555 */
4556
4557 #ifndef QT_NO_CURSOR
4558 QCursor QWidget::cursor() const
4559 {
4560     Q_D(const QWidget);
4561     if (testAttribute(Qt::WA_SetCursor))
4562         return (d->extra && d->extra->curs)
4563             ? *d->extra->curs
4564             : QCursor(Qt::ArrowCursor);
4565     if (isWindow() || !parentWidget())
4566         return QCursor(Qt::ArrowCursor);
4567     return parentWidget()->cursor();
4568 }
4569
4570 void QWidget::setCursor(const QCursor &cursor)
4571 {
4572     Q_D(QWidget);
4573 // On Mac we must set the cursor even if it is the ArrowCursor.
4574 #if !defined(Q_WS_MAC)
4575     if (cursor.shape() != Qt::ArrowCursor
4576         || (d->extra && d->extra->curs))
4577 #endif
4578     {
4579         d->createExtra();
4580         QCursor *newCursor = new QCursor(cursor);
4581         delete d->extra->curs;
4582         d->extra->curs = newCursor;
4583     }
4584     setAttribute(Qt::WA_SetCursor);
4585     d->setCursor_sys(cursor);
4586
4587     QEvent event(QEvent::CursorChange);
4588     QApplication::sendEvent(this, &event);
4589 }
4590
4591 void QWidget::unsetCursor()
4592 {
4593     Q_D(QWidget);
4594     if (d->extra) {
4595         delete d->extra->curs;
4596         d->extra->curs = 0;
4597     }
4598     if (!isWindow())
4599         setAttribute(Qt::WA_SetCursor, false);
4600     d->unsetCursor_sys();
4601
4602     QEvent event(QEvent::CursorChange);
4603     QApplication::sendEvent(this, &event);
4604 }
4605
4606 #endif
4607
4608 /*!
4609     \enum QWidget::RenderFlag
4610
4611     This enum describes how to render the widget when calling QWidget::render().
4612
4613     \value DrawWindowBackground If you enable this option, the widget's background
4614     is rendered into the target even if autoFillBackground is not set. By default,
4615     this option is enabled.
4616
4617     \value DrawChildren If you enable this option, the widget's children
4618     are rendered recursively into the target. By default, this option is enabled.
4619
4620     \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4621     is ignored when rendering into the target. By default, this option is disabled.
4622
4623     \since 4.3
4624 */
4625
4626 /*!
4627     \since 4.3
4628
4629     Renders the \a sourceRegion of this widget into the \a target
4630     using \a renderFlags to determine how to render. Rendering
4631     starts at \a targetOffset in the \a target. For example:
4632
4633     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4634
4635     If \a sourceRegion is a null region, this function will use QWidget::rect() as
4636     the region, i.e. the entire widget.
4637
4638     Ensure that you call QPainter::end() for the \a target device's
4639     active painter (if any) before rendering. For example:
4640
4641     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4642
4643     \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4644     or QGLWidget::renderPixmap() instead.
4645 */
4646 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4647                      const QRegion &sourceRegion, RenderFlags renderFlags)
4648 {
4649     d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4650 }
4651
4652 /*!
4653     \overload
4654
4655     Renders the widget into the \a painter's QPainter::device().
4656
4657     Transformations and settings applied to the \a painter will be used
4658     when rendering.
4659
4660     \note The \a painter must be active. On Mac OS X the widget will be
4661     rendered into a QPixmap and then drawn by the \a painter.
4662
4663     \sa QPainter::device()
4664 */
4665 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4666                      const QRegion &sourceRegion, RenderFlags renderFlags)
4667 {
4668     if (!painter) {
4669         qWarning("QWidget::render: Null pointer to painter");
4670         return;
4671     }
4672
4673     if (!painter->isActive()) {
4674         qWarning("QWidget::render: Cannot render with an inactive painter");
4675         return;
4676     }
4677
4678     const qreal opacity = painter->opacity();
4679     if (qFuzzyIsNull(opacity))
4680         return; // Fully transparent.
4681
4682     Q_D(QWidget);
4683     const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4684     const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4685                                                      : sourceRegion;
4686     if (toBePainted.isEmpty())
4687         return;
4688
4689     if (!d->extra)
4690         d->createExtra();
4691     d->extra->inRenderWithPainter = true;
4692
4693 #ifdef Q_WS_MAC
4694     d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4695 #else
4696     QPaintEngine *engine = painter->paintEngine();
4697     Q_ASSERT(engine);
4698     QPaintEnginePrivate *enginePriv = engine->d_func();
4699     Q_ASSERT(enginePriv);
4700     QPaintDevice *target = engine->paintDevice();
4701     Q_ASSERT(target);
4702
4703     // Render via a pixmap when dealing with non-opaque painters or printers.
4704     if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4705         d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4706         d->extra->inRenderWithPainter = false;
4707         return;
4708     }
4709
4710     // Set new shared painter.
4711     QPainter *oldPainter = d->sharedPainter();
4712     d->setSharedPainter(painter);
4713
4714     // Save current system clip, viewport and transform,
4715     const QTransform oldTransform = enginePriv->systemTransform;
4716     const QRegion oldSystemClip = enginePriv->systemClip;
4717     const QRegion oldSystemViewport = enginePriv->systemViewport;
4718
4719     // This ensures that all painting triggered by render() is clipped to the current engine clip.
4720     if (painter->hasClipping()) {
4721         const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4722         enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4723     } else {
4724         enginePriv->setSystemViewport(oldSystemClip);
4725     }
4726
4727     render(target, targetOffset, toBePainted, renderFlags);
4728
4729     // Restore system clip, viewport and transform.
4730     enginePriv->systemClip = oldSystemClip;
4731     enginePriv->setSystemViewport(oldSystemViewport);
4732     enginePriv->setSystemTransform(oldTransform);
4733
4734     // Restore shared painter.
4735     d->setSharedPainter(oldPainter);
4736 #endif
4737
4738     d->extra->inRenderWithPainter = false;
4739 }
4740
4741 static void sendResizeEvents(QWidget *target)
4742 {
4743     QResizeEvent e(target->size(), QSize());
4744     QApplication::sendEvent(target, &e);
4745
4746     const QObjectList children = target->children();
4747     for (int i = 0; i < children.size(); ++i) {
4748         QWidget *child = static_cast<QWidget*>(children.at(i));
4749         if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4750             sendResizeEvents(child);
4751     }
4752 }
4753
4754 /*!
4755     \since 5.0
4756
4757     Renders the widget into a pixmap restricted by the
4758     given \a rectangle. If the \a widget has any children, then
4759     they are also painted in the appropriate positions.
4760
4761     If no rectangle is specified (the default) the entire widget is
4762     painted.
4763
4764     Replacement for Qt 4's QPixmap::grabWidget().
4765
4766     \sa render(), QPixmap
4767 */
4768
4769 /* INVOKABLE since used by QPixmap::grabWidget(). */
4770 QPixmap QWidget::grab(const QRect &rectangle)
4771 {
4772     Q_D(const QWidget);
4773     if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4774         sendResizeEvents(this);
4775
4776     adjustSize();
4777
4778     QRect r(rectangle);
4779     if (r.width() < 0)
4780         r.setWidth(width() - rectangle.x());
4781     if (r.height() < 0)
4782         r.setHeight(height() - rectangle.y());
4783
4784     if (!r.intersects(rect()))
4785         return QPixmap();
4786
4787     QPixmap res(r.size());
4788     if (!d->isOpaque)
4789         res.fill(Qt::transparent);
4790     render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4791            | QWidget::DrawChildren | QWidget::IgnoreMask);
4792     return res;
4793 }
4794
4795 /*!
4796     \brief The graphicsEffect function returns a pointer to the
4797     widget's graphics effect.
4798
4799     If the widget has no graphics effect, 0 is returned.
4800
4801     \since 4.6
4802
4803     \sa setGraphicsEffect()
4804 */
4805 #ifndef QT_NO_GRAPHICSEFFECT
4806 QGraphicsEffect *QWidget::graphicsEffect() const
4807 {
4808     Q_D(const QWidget);
4809     return d->graphicsEffect;
4810 }
4811 #endif //QT_NO_GRAPHICSEFFECT
4812
4813 /*!
4814
4815   \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4816
4817     Sets \a effect as the widget's effect. If there already is an effect installed
4818     on this widget, QWidget will delete the existing effect before installing
4819     the new \a effect.
4820
4821     If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4822     the effect from the widget and install it on this widget.
4823
4824     QWidget takes ownership of \a effect.
4825
4826     \note This function will apply the effect on itself and all its children.
4827
4828     \since 4.6
4829
4830     \sa graphicsEffect()
4831 */
4832 #ifndef QT_NO_GRAPHICSEFFECT
4833 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4834 {
4835     Q_D(QWidget);
4836     if (d->graphicsEffect == effect)
4837         return;
4838
4839     if (d->graphicsEffect) {
4840         d->invalidateBuffer(rect());
4841         delete d->graphicsEffect;
4842         d->graphicsEffect = 0;
4843     }
4844
4845     if (effect) {
4846         // Set new effect.
4847         QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4848         QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4849         d->graphicsEffect = effect;
4850         effect->d_func()->setGraphicsEffectSource(source);
4851         update();
4852     }
4853
4854     d->updateIsOpaque();
4855 }
4856 #endif //QT_NO_GRAPHICSEFFECT
4857
4858 bool QWidgetPrivate::isAboutToShow() const
4859 {
4860     if (data.in_show)
4861         return true;
4862
4863     Q_Q(const QWidget);
4864     if (q->isHidden())
4865         return false;
4866
4867     // The widget will be shown if any of its ancestors are about to show.
4868     QWidget *parent = q->parentWidget();
4869     return parent ? parent->d_func()->isAboutToShow() : false;
4870 }
4871
4872 QRegion QWidgetPrivate::prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags)
4873 {
4874     Q_Q(QWidget);
4875     const bool isVisible = q->isVisible();
4876
4877     // Make sure the widget is laid out correctly.
4878     if (!isVisible && !isAboutToShow()) {
4879         QWidget *topLevel = q->window();
4880         (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4881         topLevel->ensurePolished();
4882
4883         // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4884         // they're not explicitly hidden.
4885         QWidget *widget = q;
4886         QWidgetList hiddenWidgets;
4887         while (widget) {
4888             if (widget->isHidden()) {
4889                 widget->setAttribute(Qt::WA_WState_Hidden, false);
4890                 hiddenWidgets.append(widget);
4891                 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4892                     widget->d_func()->updateGeometry_helper(true);
4893             }
4894             widget = widget->parentWidget();
4895         }
4896
4897         // Activate top-level layout.
4898         if (topLevel->d_func()->layout)
4899             topLevel->d_func()->layout->activate();
4900
4901         // Adjust size if necessary.
4902         QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4903         if (topLevelExtra && !topLevelExtra->sizeAdjusted
4904             && !topLevel->testAttribute(Qt::WA_Resized)) {
4905             topLevel->adjustSize();
4906             topLevel->setAttribute(Qt::WA_Resized, false);
4907         }
4908
4909         // Activate child layouts.
4910         topLevel->d_func()->activateChildLayoutsRecursively();
4911
4912         // We're not cheating with WA_WState_Hidden anymore.
4913         for (int i = 0; i < hiddenWidgets.size(); ++i) {
4914             QWidget *widget = hiddenWidgets.at(i);
4915             widget->setAttribute(Qt::WA_WState_Hidden);
4916             if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4917                 widget->parentWidget()->d_func()->layout->invalidate();
4918         }
4919     } else if (isVisible) {
4920         q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4921     }
4922
4923     // Calculate the region to be painted.
4924     QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4925     if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4926         toBePainted &= extra->mask;
4927     return toBePainted;
4928 }
4929
4930 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4931                                    QWidget::RenderFlags renderFlags)
4932 {
4933     Q_ASSERT(painter);
4934     Q_ASSERT(!toBePainted.isEmpty());
4935
4936     Q_Q(QWidget);
4937 #ifndef Q_WS_MAC
4938     const QTransform originalTransform = painter->worldTransform();
4939     const bool useDeviceCoordinates = originalTransform.isScaling();
4940     if (!useDeviceCoordinates) {
4941 #endif
4942         // Render via a pixmap.
4943         const QRect rect = toBePainted.boundingRect();
4944         const QSize size = rect.size();
4945         if (size.isNull())
4946             return;
4947
4948         QPixmap pixmap(size);
4949         if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4950             pixmap.fill(Qt::transparent);
4951         q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4952
4953         const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4954         painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4955
4956         painter->drawPixmap(targetOffset, pixmap);
4957
4958         if (restore)
4959             painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4960
4961 #ifndef Q_WS_MAC
4962     } else {
4963         // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4964         QTransform transform = originalTransform;
4965         transform.translate(targetOffset.x(), targetOffset.y());
4966
4967         QPaintDevice *device = painter->device();
4968         Q_ASSERT(device);
4969
4970         // Calculate device rect.
4971         const QRectF rect(toBePainted.boundingRect());
4972         QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4973         deviceRect &= QRect(0, 0, device->width(), device->height());
4974
4975         QPixmap pixmap(deviceRect.size());
4976         pixmap.fill(Qt::transparent);
4977
4978         // Create a pixmap device coordinate painter.
4979         QPainter pixmapPainter(&pixmap);
4980         pixmapPainter.setRenderHints(painter->renderHints());
4981         transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4982         pixmapPainter.setTransform(transform);
4983
4984         q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4985         pixmapPainter.end();
4986
4987         // And then draw the pixmap.
4988         painter->setTransform(QTransform());
4989         painter->drawPixmap(deviceRect.topLeft(), pixmap);
4990         painter->setTransform(originalTransform);
4991     }
4992 #endif
4993 }
4994
4995 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
4996                                 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
4997 {
4998     if (rgn.isEmpty())
4999         return;
5000
5001 #ifdef Q_WS_MAC
5002     if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5003         dirtyOnWidget = QRegion();
5004
5005     // We disable the rendering of QToolBar in the backingStore if
5006     // it's supposed to be in the unified toolbar on Mac OS X.
5007     if (backingStore && isInUnifiedToolbar)
5008         return;
5009 #endif // Q_WS_MAC
5010
5011
5012     Q_Q(QWidget);
5013 #ifndef QT_NO_GRAPHICSEFFECT
5014     if (graphicsEffect && graphicsEffect->isEnabled()) {
5015         QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5016         QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5017                                                          (source->d_func());
5018         if (!sourced->context) {
5019             QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5020             sourced->context = &context;
5021             if (!sharedPainter) {
5022                 QPaintEngine *paintEngine = pdev->paintEngine();
5023                 paintEngine->d_func()->systemClip = rgn.translated(offset);
5024                 QPainter p(pdev);
5025                 p.translate(offset);
5026                 context.painter = &p;
5027                 graphicsEffect->draw(&p);
5028                 paintEngine->d_func()->systemClip = QRegion();
5029             } else {
5030                 context.painter = sharedPainter;
5031                 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5032                     sourced->invalidateCache();
5033                     sourced->lastEffectTransform = sharedPainter->worldTransform();
5034                 }
5035                 sharedPainter->save();
5036                 sharedPainter->translate(offset);
5037                 graphicsEffect->draw(sharedPainter);
5038                 sharedPainter->restore();
5039             }
5040             sourced->context = 0;
5041             return;
5042         }
5043     }
5044 #endif //QT_NO_GRAFFICSEFFECT
5045
5046     const bool asRoot = flags & DrawAsRoot;
5047     const bool alsoOnScreen = flags & DrawPaintOnScreen;
5048     const bool recursive = flags & DrawRecursive;
5049     const bool alsoInvisible = flags & DrawInvisible;
5050
5051     Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5052
5053     QRegion toBePainted(rgn);
5054     if (asRoot && !alsoInvisible)
5055         toBePainted &= clipRect(); //(rgn & visibleRegion());
5056     if (!(flags & DontSubtractOpaqueChildren))
5057         subtractOpaqueChildren(toBePainted, q->rect());
5058
5059     if (!toBePainted.isEmpty()) {
5060         bool onScreen = paintOnScreen();
5061         if (!onScreen || alsoOnScreen) {
5062             //update the "in paint event" flag
5063             if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5064                 qWarning("QWidget::repaint: Recursive repaint detected");
5065             q->setAttribute(Qt::WA_WState_InPaintEvent);
5066
5067             //clip away the new area
5068 #ifndef QT_NO_PAINT_DEBUG
5069             bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5070 #endif
5071             QPaintEngine *paintEngine = pdev->paintEngine();
5072             if (paintEngine) {
5073                 setRedirected(pdev, -offset);
5074
5075 #ifdef Q_WS_MAC
5076                 // (Alien support) Special case for Mac when redirecting: If the paint device
5077                 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5078                 // outside the paint event is not supported on QWidgets. The attributeis
5079                 // restored further down.
5080                 if (pdev->devType() == QInternal::Widget)
5081                     static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5082
5083 #endif
5084                 if (sharedPainter)
5085                     paintEngine->d_func()->systemClip = toBePainted;
5086                 else
5087                     paintEngine->d_func()->systemRect = q->data->crect;
5088
5089                 //paint the background
5090                 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5091                     && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5092                     QPainter p(q);
5093                     paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5094                 }
5095
5096                 if (!sharedPainter)
5097                     paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5098
5099                 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5100                     QPainter p(q);
5101                     QColor tint = q->palette().window().color();
5102                     tint.setAlphaF(qreal(.6));
5103                     p.fillRect(toBePainted.boundingRect(), tint);
5104                 }
5105             }
5106
5107 #if 0
5108             qDebug() << "painting" << q << "opaque ==" << isOpaque();
5109             qDebug() << "clipping to" << toBePainted << "location == " << offset
5110                      << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5111 #endif
5112
5113             //actually send the paint event
5114             QPaintEvent e(toBePainted);
5115             QCoreApplication::sendSpontaneousEvent(q, &e);
5116
5117             //restore
5118             if (paintEngine) {
5119 #ifdef Q_WS_MAC
5120                 if (pdev->devType() == QInternal::Widget)
5121                     static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5122 #endif
5123                 restoreRedirected();
5124                 if (!sharedPainter)
5125                     paintEngine->d_func()->systemRect = QRect();
5126                 else
5127                     paintEngine->d_func()->currentClipDevice = 0;
5128                 paintEngine->d_func()->systemClip = QRegion();
5129             }
5130             q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5131             if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5132                 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5133
5134             if (paintEngine && paintEngine->autoDestruct()) {
5135                 delete paintEngine;
5136             }
5137
5138 #ifndef QT_NO_PAINT_DEBUG
5139             if (flushed)
5140                 QWidgetBackingStore::unflushPaint(q, toBePainted);
5141 #endif
5142         } else if (q->isWindow()) {
5143             QPaintEngine *engine = pdev->paintEngine();
5144             if (engine) {
5145                 QPainter p(pdev);
5146                 p.setClipRegion(toBePainted);
5147                 const QBrush bg = q->palette().brush(QPalette::Window);
5148                 if (bg.style() == Qt::TexturePattern)
5149                     p.drawTiledPixmap(q->rect(), bg.texture());
5150                 else
5151                     p.fillRect(q->rect(), bg);
5152
5153                 if (engine->autoDestruct())
5154                     delete engine;
5155             }
5156         }
5157     }
5158
5159     if (recursive && !children.isEmpty()) {
5160         paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5161                                 , sharedPainter, backingStore);
5162     }
5163 }
5164
5165 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5166                             const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5167                             bool readyToRender)
5168 {
5169     if (!target) {
5170         qWarning("QWidget::render: null pointer to paint device");
5171         return;
5172     }
5173
5174     const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5175     QRegion paintRegion = !inRenderWithPainter && !readyToRender
5176                           ? prepareToRender(sourceRegion, renderFlags)
5177                           : sourceRegion;
5178     if (paintRegion.isEmpty())
5179         return;
5180
5181 #ifndef Q_WS_MAC
5182     QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5183
5184     // Use the target's shared painter if set (typically set when doing
5185     // "other->render(widget);" in the widget's paintEvent.
5186     if (target->devType() == QInternal::Widget) {
5187         QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5188         if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5189             QPainter *targetPainter = targetPrivate->sharedPainter();
5190             if (targetPainter && targetPainter->isActive())
5191                 setSharedPainter(targetPainter);
5192         }
5193     }
5194 #endif
5195
5196     // Use the target's redirected device if set and adjust offset and paint
5197     // region accordingly. This is typically the case when people call render
5198     // from the paintEvent.
5199     QPoint offset = targetOffset;
5200     offset -= paintRegion.boundingRect().topLeft();
5201     QPoint redirectionOffset;
5202     QPaintDevice *redirected = 0;
5203
5204     if (target->devType() == QInternal::Widget)
5205         redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5206     if (!redirected)
5207         redirected = QPainter::redirected(target, &redirectionOffset);
5208
5209     if (redirected) {
5210         target = redirected;
5211         offset -= redirectionOffset;
5212     }
5213
5214     if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5215         if (QPaintEngine *targetEngine = target->paintEngine()) {
5216             const QRegion targetSystemClip = targetEngine->systemClip();
5217             if (!targetSystemClip.isEmpty())
5218                 paintRegion &= targetSystemClip.translated(-offset);
5219         }
5220     }
5221
5222     // Set backingstore flags.
5223     int flags = DrawPaintOnScreen | DrawInvisible;
5224     if (renderFlags & QWidget::DrawWindowBackground)
5225         flags |= DrawAsRoot;
5226
5227     if (renderFlags & QWidget::DrawChildren)
5228         flags |= DrawRecursive;
5229     else
5230         flags |= DontSubtractOpaqueChildren;
5231
5232     if (target->devType() == QInternal::Printer) {
5233         QPainter p(target);
5234         render_helper(&p, targetOffset, paintRegion, renderFlags);
5235         return;
5236     }
5237
5238 #ifndef Q_WS_MAC
5239     // Render via backingstore.
5240     drawWidget(target, paintRegion, offset, flags, sharedPainter());
5241
5242     // Restore shared painter.
5243     if (oldSharedPainter)
5244         setSharedPainter(oldSharedPainter);
5245 #else
5246     // Render via backingstore (no shared painter).
5247     drawWidget(target, paintRegion, offset, flags, 0);
5248 #endif
5249 }
5250
5251 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5252                                             const QPoint &offset, int flags
5253                                             , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5254 {
5255     QWidget *w = 0;
5256     QRect boundingRect;
5257     bool dirtyBoundingRect = true;
5258     const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5259     const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5260
5261     do {
5262         QWidget *x =  qobject_cast<QWidget*>(siblings.at(index));
5263         if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5264             && !(excludeNativeChildren && x->internalWinId())) {
5265             if (dirtyBoundingRect) {
5266                 boundingRect = rgn.boundingRect();
5267                 dirtyBoundingRect = false;
5268             }
5269
5270             if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5271                 w = x;
5272                 break;
5273             }
5274         }
5275         --index;
5276     } while (index >= 0);
5277
5278     if (!w)
5279         return;
5280
5281     QWidgetPrivate *wd = w->d_func();
5282     const QPoint widgetPos(w->data->crect.topLeft());
5283     const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5284     if (index > 0) {
5285         QRegion wr(rgn);
5286         if (wd->isOpaque)
5287             wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5288         paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5289                                , sharedPainter, backingStore);
5290     }
5291
5292     if (w->updatesEnabled()
5293 #ifndef QT_NO_GRAPHICSVIEW
5294             && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5295 #endif //QT_NO_GRAPHICSVIEW
5296        ) {
5297         QRegion wRegion(rgn);
5298         wRegion &= wd->effectiveRectFor(w->data->crect);
5299         wRegion.translate(-widgetPos);
5300         if (hasMask)
5301             wRegion &= wd->extra->mask;
5302         wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5303     }
5304 }
5305
5306 #ifndef QT_NO_GRAPHICSEFFECT
5307 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5308 {
5309     if (system != Qt::DeviceCoordinates)
5310         return m_widget->rect();
5311
5312     if (!context) {
5313         // Device coordinates without context not yet supported.
5314         qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5315         return QRectF();
5316     }
5317
5318     return context->painter->worldTransform().mapRect(m_widget->rect());
5319 }
5320
5321 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5322 {
5323     if (!context || context->painter != painter) {
5324         m_widget->render(painter);
5325         return;
5326     }
5327
5328     // The region saved in the context is neither clipped to the rect
5329     // nor the mask, so we have to clip it here before calling drawWidget.
5330     QRegion toBePainted = context->rgn;
5331     toBePainted &= m_widget->rect();
5332     QWidgetPrivate *wd = qt_widget_private(m_widget);
5333     if (wd->extra && wd->extra->hasMask)
5334         toBePainted &= wd->extra->mask;
5335
5336     wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5337                    context->sharedPainter, context->backingStore);
5338 }
5339
5340 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5341                                            QGraphicsEffect::PixmapPadMode mode) const
5342 {
5343     const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5344     if (!context && deviceCoordinates) {
5345         // Device coordinates without context not yet supported.
5346         qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5347         return QPixmap();
5348     }
5349
5350     QPoint pixmapOffset;
5351     QRectF sourceRect = m_widget->rect();
5352
5353     if (deviceCoordinates) {
5354         const QTransform &painterTransform = context->painter->worldTransform();
5355         sourceRect = painterTransform.mapRect(sourceRect);
5356         pixmapOffset = painterTransform.map(pixmapOffset);
5357     }
5358
5359     QRect effectRect;
5360
5361     if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5362         effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5363     else if (mode == QGraphicsEffect::PadToTransparentBorder)
5364         effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5365     else
5366         effectRect = sourceRect.toAlignedRect();
5367
5368     if (offset)
5369         *offset = effectRect.topLeft();
5370
5371     pixmapOffset -= effectRect.topLeft();
5372
5373     QPixmap pixmap(effectRect.size());
5374     pixmap.fill(Qt::transparent);
5375     m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5376     return pixmap;
5377 }
5378 #endif //QT_NO_GRAPHICSEFFECT
5379
5380 #ifndef QT_NO_GRAPHICSVIEW
5381 /*!
5382     \internal
5383
5384     Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5385     widget and its ancestors. The search starts at \a origin (inclusive).
5386     If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5387     widget was found.
5388 */
5389 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5390 {
5391     if (origin) {
5392         QWExtra *extra = origin->d_func()->extra;
5393         if (extra && extra->proxyWidget)
5394             return extra->proxyWidget;
5395         return nearestGraphicsProxyWidget(origin->parentWidget());
5396     }
5397     return 0;
5398 }
5399 #endif
5400
5401 /*!
5402     \property QWidget::locale
5403     \brief the widget's locale
5404     \since 4.3
5405
5406     As long as no special locale has been set, this is either
5407     the parent's locale or (if this widget is a top level widget),
5408     the default locale.
5409
5410     If the widget displays dates or numbers, these should be formatted
5411     using the widget's locale.
5412
5413     \sa QLocale QLocale::setDefault()
5414 */
5415
5416 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5417 {
5418     Q_Q(QWidget);
5419     if (locale == loc && !forceUpdate)
5420         return;
5421
5422     locale = loc;
5423
5424     if (!children.isEmpty()) {
5425         for (int i = 0; i < children.size(); ++i) {
5426             QWidget *w = qobject_cast<QWidget*>(children.at(i));
5427             if (!w)
5428                 continue;
5429             if (w->testAttribute(Qt::WA_SetLocale))
5430                 continue;
5431             if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5432                 continue;
5433             w->d_func()->setLocale_helper(loc, forceUpdate);
5434         }
5435     }
5436     QEvent e(QEvent::LocaleChange);
5437     QApplication::sendEvent(q, &e);
5438 }
5439
5440 void QWidget::setLocale(const QLocale &locale)
5441 {
5442     Q_D(QWidget);
5443
5444     setAttribute(Qt::WA_SetLocale);
5445     d->setLocale_helper(locale);
5446 }
5447
5448 QLocale QWidget::locale() const
5449 {
5450     Q_D(const QWidget);
5451
5452     return d->locale;
5453 }
5454
5455 void QWidgetPrivate::resolveLocale()
5456 {
5457     Q_Q(const QWidget);
5458
5459     if (!q->testAttribute(Qt::WA_SetLocale)) {
5460         setLocale_helper(q->isWindow()
5461                             ? QLocale()
5462                             : q->parentWidget()->locale());
5463     }
5464 }
5465
5466 void QWidget::unsetLocale()
5467 {
5468     Q_D(QWidget);
5469     setAttribute(Qt::WA_SetLocale, false);
5470     d->resolveLocale();
5471 }
5472
5473 static QString constructWindowTitleFromFilePath(const QString &filePath)
5474 {
5475     QFileInfo fi(filePath);
5476     QString windowTitle = fi.fileName() + QLatin1String("[*]");
5477 #ifndef Q_WS_MAC
5478     QString appName = QApplication::applicationName();
5479     if (!appName.isEmpty())
5480         windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5481 #endif
5482     return windowTitle;
5483 }
5484
5485 /*!
5486     \property QWidget::windowTitle
5487     \brief the window title (caption)
5488
5489     This property only makes sense for top-level widgets, such as
5490     windows and dialogs. If no caption has been set, the title is based of the
5491     \l windowFilePath. If neither of these is set, then the title is
5492     an empty string.
5493
5494     If you use the \l windowModified mechanism, the window title must
5495     contain a "[*]" placeholder, which indicates where the '*' should
5496     appear. Normally, it should appear right after the file name
5497     (e.g., "document1.txt[*] - Text Editor"). If the \l
5498     windowModified property is false (the default), the placeholder
5499     is simply removed.
5500
5501     \sa windowIcon, windowIconText, windowModified, windowFilePath
5502 */
5503 QString QWidget::windowTitle() const
5504 {
5505     Q_D(const QWidget);
5506     if (d->extra && d->extra->topextra) {
5507         if (!d->extra->topextra->caption.isEmpty())
5508             return d->extra->topextra->caption;
5509         if (!d->extra->topextra->filePath.isEmpty())
5510             return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5511     }
5512     return QString();
5513 }
5514
5515 /*!
5516     Returns a modified window title with the [*] place holder
5517     replaced according to the rules described in QWidget::setWindowTitle
5518
5519     This function assumes that "[*]" can be quoted by another
5520     "[*]", so it will replace two place holders by one and
5521     a single last one by either "*" or nothing depending on
5522     the modified flag.
5523
5524     \internal
5525 */
5526 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5527 {
5528     Q_ASSERT(widget);
5529
5530 #ifdef QT_EVAL
5531     extern QString qt_eval_adapt_window_title(const QString &title);
5532     QString cap = qt_eval_adapt_window_title(title);
5533 #else
5534     QString cap = title;
5535 #endif
5536
5537     if (cap.isEmpty())
5538         return cap;
5539
5540     QLatin1String placeHolder("[*]");
5541     int placeHolderLength = 3; // QLatin1String doesn't have length()
5542
5543     int index = cap.indexOf(placeHolder);
5544
5545     // here the magic begins
5546     while (index != -1) {
5547         index += placeHolderLength;
5548         int count = 1;
5549         while (cap.indexOf(placeHolder, index) == index) {
5550             ++count;
5551             index += placeHolderLength;
5552         }
5553
5554         if (count%2) { // odd number of [*] -> replace last one
5555             int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5556             if (widget->isWindowModified()
5557              && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5558                 cap.replace(lastIndex, 3, QWidget::tr("*"));
5559             else
5560                 cap.remove(lastIndex, 3);
5561         }
5562
5563         index = cap.indexOf(placeHolder, index);
5564     }
5565
5566     cap.replace(QLatin1String("[*][*]"), placeHolder);
5567
5568     return cap;
5569 }
5570
5571 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5572 {
5573     Q_Q(QWidget);
5574     if (q->testAttribute(Qt::WA_WState_Created))
5575         setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5576 }
5577
5578 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5579 {
5580     Q_Q(QWidget);
5581     if (q->testAttribute(Qt::WA_WState_Created))
5582         setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5583 }
5584
5585 void QWidget::setWindowIconText(const QString &iconText)
5586 {
5587     if (QWidget::windowIconText() == iconText)
5588         return;
5589
5590     Q_D(QWidget);
5591     d->topData()->iconText = iconText;
5592     d->setWindowIconText_helper(iconText);
5593
5594     QEvent e(QEvent::IconTextChange);
5595     QApplication::sendEvent(this, &e);
5596 }
5597
5598 void QWidget::setWindowTitle(const QString &title)
5599 {
5600     if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5601         return;
5602
5603     Q_D(QWidget);
5604     d->topData()->caption = title;
5605     d->setWindowTitle_helper(title);
5606
5607     QEvent e(QEvent::WindowTitleChange);
5608     QApplication::sendEvent(this, &e);
5609 }
5610
5611
5612 /*!
5613     \property QWidget::windowIcon
5614     \brief the widget's icon
5615
5616     This property only makes sense for windows. If no icon
5617     has been set, windowIcon() returns the application icon
5618     (QApplication::windowIcon()).
5619
5620     \sa windowIconText, windowTitle
5621 */
5622 QIcon QWidget::windowIcon() const
5623 {
5624     const QWidget *w = this;
5625     while (w) {
5626         const QWidgetPrivate *d = w->d_func();
5627         if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5628             return *d->extra->topextra->icon;
5629         w = w->parentWidget();
5630     }
5631     return QApplication::windowIcon();
5632 }
5633
5634 void QWidgetPrivate::setWindowIcon_helper()
5635 {
5636     QEvent e(QEvent::WindowIconChange);
5637     QApplication::sendEvent(q_func(), &e);
5638     for (int i = 0; i < children.size(); ++i) {
5639         QWidget *w = qobject_cast<QWidget *>(children.at(i));
5640         if (w && !w->isWindow())
5641             QApplication::sendEvent(w, &e);
5642     }
5643 }
5644
5645 void QWidget::setWindowIcon(const QIcon &icon)
5646 {
5647     Q_D(QWidget);
5648
5649     setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5650     d->createTLExtra();
5651
5652     if (!d->extra->topextra->icon)
5653         d->extra->topextra->icon = new QIcon();
5654     *d->extra->topextra->icon = icon;
5655
5656     delete d->extra->topextra->iconPixmap;
5657     d->extra->topextra->iconPixmap = 0;
5658
5659     d->setWindowIcon_sys();
5660     d->setWindowIcon_helper();
5661 }
5662
5663
5664 /*!
5665     \property QWidget::windowIconText
5666     \brief the widget's icon text
5667
5668     This property only makes sense for windows. If no icon
5669     text has been set, this functions returns an empty string.
5670
5671     \sa windowIcon, windowTitle
5672 */
5673
5674 QString QWidget::windowIconText() const
5675 {
5676     Q_D(const QWidget);
5677     return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5678 }
5679
5680 /*!
5681     \property QWidget::windowFilePath
5682     \since 4.4
5683     \brief the file path associated with a widget
5684
5685     This property only makes sense for windows. It associates a file path with
5686     a window. If you set the file path, but have not set the window title, Qt
5687     sets the window title to contain a string created using the following
5688     components.
5689
5690     On Mac OS X:
5691
5692     \list
5693     \li The file name of the specified path, obtained using QFileInfo::fileName().
5694     \endlist
5695
5696     On Windows and X11:
5697
5698     \list
5699     \li The file name of the specified path, obtained using QFileInfo::fileName().
5700     \li An optional \c{*} character, if the \l windowModified property is set.
5701     \li The \c{0x2014} unicode character, padded either side by spaces.
5702     \li The application name, obtained from the application's
5703     \l{QCoreApplication::}{applicationName} property.
5704     \endlist
5705
5706     If the window title is set at any point, then the window title takes precedence and
5707     will be shown instead of the file path string.
5708
5709     Additionally, on Mac OS X, this has an added benefit that it sets the
5710     \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5711     for the window, assuming that the file path exists.
5712
5713     If no file path is set, this property contains an empty string.
5714
5715     By default, this property contains an empty string.
5716
5717     \sa windowTitle, windowIcon
5718 */
5719
5720 QString QWidget::windowFilePath() const
5721 {
5722     Q_D(const QWidget);
5723     return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5724 }
5725
5726 void QWidget::setWindowFilePath(const QString &filePath)
5727 {
5728     if (filePath == windowFilePath())
5729         return;
5730
5731     Q_D(QWidget);
5732
5733     d->createTLExtra();
5734     d->extra->topextra->filePath = filePath;
5735     d->setWindowFilePath_helper(filePath);
5736 }
5737
5738 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5739 {
5740     if (extra->topextra && extra->topextra->caption.isEmpty()) {
5741 #ifdef Q_WS_MAC
5742         setWindowTitle_helper(QFileInfo(filePath).fileName());
5743 #else
5744         Q_Q(QWidget);
5745         Q_UNUSED(filePath);
5746         setWindowTitle_helper(q->windowTitle());
5747 #endif
5748     }
5749 #ifdef Q_WS_MAC
5750     setWindowFilePath_sys(filePath);
5751 #endif
5752 }
5753
5754 /*!
5755     Returns the window's role, or an empty string.
5756
5757     \sa windowIcon, windowTitle
5758 */
5759
5760 QString QWidget::windowRole() const
5761 {
5762     Q_D(const QWidget);
5763     return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5764 }
5765
5766 /*!
5767     Sets the window's role to \a role. This only makes sense for
5768     windows on X11.
5769 */
5770 void QWidget::setWindowRole(const QString &role)
5771 {
5772 #if defined(Q_WS_X11)
5773     Q_D(QWidget);
5774     d->topData()->role = role;
5775     d->setWindowRole();
5776 #else
5777     Q_UNUSED(role)
5778 #endif
5779 }
5780
5781 /*!
5782     \property QWidget::mouseTracking
5783     \brief whether mouse tracking is enabled for the widget
5784
5785     If mouse tracking is disabled (the default), the widget only
5786     receives mouse move events when at least one mouse button is
5787     pressed while the mouse is being moved.
5788
5789     If mouse tracking is enabled, the widget receives mouse move
5790     events even if no buttons are pressed.
5791
5792     \sa mouseMoveEvent()
5793 */
5794
5795
5796 /*!
5797     Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5798     function resets this widget to have no focus proxy.
5799
5800     Some widgets can "have focus", but create a child widget, such as
5801     QLineEdit, to actually handle the focus. In this case, the widget
5802     can set the line edit to be its focus proxy.
5803
5804     setFocusProxy() sets the widget which will actually get focus when
5805     "this widget" gets it. If there is a focus proxy, setFocus() and
5806     hasFocus() operate on the focus proxy.
5807
5808     \sa focusProxy()
5809 */
5810
5811 void QWidget::setFocusProxy(QWidget * w)
5812 {
5813     Q_D(QWidget);
5814     if (!w && !d->extra)
5815         return;
5816
5817     for (QWidget* fp  = w; fp; fp = fp->focusProxy()) {
5818         if (fp == this) {
5819             qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5820             return;
5821         }
5822     }
5823
5824     d->createExtra();
5825     d->extra->focus_proxy = w;
5826 }
5827
5828
5829 /*!
5830     Returns the focus proxy, or 0 if there is no focus proxy.
5831
5832     \sa setFocusProxy()
5833 */
5834
5835 QWidget * QWidget::focusProxy() const
5836 {
5837     Q_D(const QWidget);
5838     return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5839 }
5840
5841
5842 /*!
5843     \property QWidget::focus
5844     \brief whether this widget (or its focus proxy) has the keyboard
5845     input focus
5846
5847     By default, this property is false.
5848
5849     \note Obtaining the value of this property for a widget is effectively equivalent
5850     to checking whether QApplication::focusWidget() refers to the widget.
5851
5852     \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5853 */
5854 bool QWidget::hasFocus() const
5855 {
5856     const QWidget* w = this;
5857     while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5858         w = w->d_func()->extra->focus_proxy;
5859     if (QWidget *window = w->window()) {
5860 #ifndef QT_NO_GRAPHICSVIEW
5861         QWExtra *e = window->d_func()->extra;
5862         if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5863             return true;
5864 #endif
5865     }
5866     return (QApplication::focusWidget() == w);
5867 }
5868
5869 /*!
5870     Gives the keyboard input focus to this widget (or its focus
5871     proxy) if this widget or one of its parents is the \link
5872     isActiveWindow() active window\endlink. The \a reason argument will
5873     be passed into any focus event sent from this function, it is used
5874     to give an explanation of what caused the widget to get focus.
5875     If the window is not active, the widget will be given the focus when
5876     the window becomes active.
5877
5878     First, a focus out event is sent to the focus widget (if any) to
5879     tell it that it is about to lose the focus. Then a focus in event
5880     is sent to this widget to tell it that it just received the focus.
5881     (Nothing happens if the focus in and focus out widgets are the
5882     same.)
5883
5884     \note On embedded platforms, setFocus() will not cause an input panel
5885     to be opened by the input method. If you want this to happen, you
5886     have to send a QEvent::RequestSoftwareInputPanel event to the
5887     widget yourself.
5888
5889     setFocus() gives focus to a widget regardless of its focus policy,
5890     but does not clear any keyboard grab (see grabKeyboard()).
5891
5892     Be aware that if the widget is hidden, it will not accept focus
5893     until it is shown.
5894
5895     \warning If you call setFocus() in a function which may itself be
5896     called from focusOutEvent() or focusInEvent(), you may get an
5897     infinite recursion.
5898
5899     \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5900     setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5901     grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5902 */
5903
5904 void QWidget::setFocus(Qt::FocusReason reason)
5905 {
5906     if (!isEnabled())
5907         return;
5908
5909     QWidget *f = this;
5910     while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5911         f = f->d_func()->extra->focus_proxy;
5912
5913     if (QApplication::focusWidget() == f
5914 #if defined(Q_WS_WIN)
5915         && GetFocus() == f->internalWinId()
5916 #endif
5917        )
5918         return;
5919
5920 #ifndef QT_NO_GRAPHICSVIEW
5921     QWidget *previousProxyFocus = 0;
5922     if (QWExtra *topData = window()->d_func()->extra) {
5923         if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5924             previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5925             if (previousProxyFocus && previousProxyFocus->focusProxy())
5926                 previousProxyFocus = previousProxyFocus->focusProxy();
5927             if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5928                 return;
5929         }
5930     }
5931 #endif
5932
5933     QWidget *w = f;
5934     if (isHidden()) {
5935         while (w && w->isHidden()) {
5936             w->d_func()->focus_child = f;
5937             w = w->isWindow() ? 0 : w->parentWidget();
5938         }
5939     } else {
5940         while (w) {
5941             w->d_func()->focus_child = f;
5942             w = w->isWindow() ? 0 : w->parentWidget();
5943         }
5944     }
5945
5946 #ifndef QT_NO_GRAPHICSVIEW
5947     // Update proxy state
5948     if (QWExtra *topData = window()->d_func()->extra) {
5949         if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5950             topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5951             topData->proxyWidget->setFocus(reason);
5952             topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5953         }
5954     }
5955 #endif
5956
5957     if (f->isActiveWindow()) {
5958         QApplicationPrivate::setFocusWidget(f, reason);
5959 #ifndef QT_NO_ACCESSIBILITY
5960 # ifdef Q_OS_WIN
5961         // The negation of the condition in setFocus_sys
5962         if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5963             //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5964 # endif
5965 # ifdef  Q_OS_UNIX
5966         // menus update the focus manually and this would create bogus events
5967         if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5968 # endif
5969         {
5970             QAccessibleEvent event(QAccessible::Focus, f);
5971             QAccessible::updateAccessibility(&event);
5972         }
5973 #endif
5974 #ifndef QT_NO_GRAPHICSVIEW
5975         if (QWExtra *topData = window()->d_func()->extra) {
5976             if (topData->proxyWidget) {
5977                 if (previousProxyFocus && previousProxyFocus != f) {
5978                     // Send event to self
5979                     QFocusEvent event(QEvent::FocusOut, reason);
5980                     QPointer<QWidget> that = previousProxyFocus;
5981                     QApplication::sendEvent(previousProxyFocus, &event);
5982                     if (that)
5983                         QApplication::sendEvent(that->style(), &event);
5984                 }
5985                 if (!isHidden()) {
5986 #ifndef QT_NO_GRAPHICSVIEW
5987                     // Update proxy state
5988                     if (QWExtra *topData = window()->d_func()->extra)
5989                         if (topData->proxyWidget && topData->proxyWidget->hasFocus())
5990                             topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
5991 #endif
5992                     // Send event to self
5993                     QFocusEvent event(QEvent::FocusIn, reason);
5994                     QPointer<QWidget> that = f;
5995                     QApplication::sendEvent(f, &event);
5996                     if (that)
5997                         QApplication::sendEvent(that->style(), &event);
5998                 }
5999             }
6000         }
6001 #endif
6002     }
6003 }
6004
6005 /*!
6006     \fn void QWidget::setFocus()
6007     \overload
6008
6009     Gives the keyboard input focus to this widget (or its focus
6010     proxy) if this widget or one of its parents is the
6011     \l{isActiveWindow()}{active window}.
6012 */
6013
6014 /*!
6015     Takes keyboard input focus from the widget.
6016
6017     If the widget has active focus, a \link focusOutEvent() focus out
6018     event\endlink is sent to this widget to tell it that it is about
6019     to lose the focus.
6020
6021     This widget must enable focus setting in order to get the keyboard
6022     input focus, i.e. it must call setFocusPolicy().
6023
6024     \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6025     setFocusPolicy(), QApplication::focusWidget()
6026 */
6027
6028 void QWidget::clearFocus()
6029 {
6030     QWidget *w = this;
6031     while (w) {
6032         if (w->d_func()->focus_child == this)
6033             w->d_func()->focus_child = 0;
6034         w = w->parentWidget();
6035     }
6036 #ifndef QT_NO_GRAPHICSVIEW
6037     QWExtra *topData = d_func()->extra;
6038     if (topData && topData->proxyWidget)
6039         topData->proxyWidget->clearFocus();
6040 #endif
6041
6042     if (hasFocus()) {
6043         // Update proxy state
6044         QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6045 #if defined(Q_WS_WIN)
6046         if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6047             SetFocus(0);
6048         else
6049 #endif
6050         {
6051 #ifndef QT_NO_ACCESSIBILITY
6052             QAccessibleEvent event(QAccessible::Focus, this);
6053             QAccessible::updateAccessibility(&event);
6054 #endif
6055         }
6056     }
6057 }
6058
6059
6060 /*!
6061     \fn bool QWidget::focusNextChild()
6062
6063     Finds a new widget to give the keyboard focus to, as appropriate
6064     for \key Tab, and returns true if it can find a new widget, or
6065     false if it can't.
6066
6067     \sa focusPreviousChild()
6068 */
6069
6070 /*!
6071     \fn bool QWidget::focusPreviousChild()
6072
6073     Finds a new widget to give the keyboard focus to, as appropriate
6074     for \key Shift+Tab, and returns true if it can find a new widget,
6075     or false if it can't.
6076
6077     \sa focusNextChild()
6078 */
6079
6080 /*!
6081     Finds a new widget to give the keyboard focus to, as appropriate
6082     for Tab and Shift+Tab, and returns true if it can find a new
6083     widget, or false if it can't.
6084
6085     If \a next is true, this function searches forward, if \a next
6086     is false, it searches backward.
6087
6088     Sometimes, you will want to reimplement this function. For
6089     example, a web browser might reimplement it to move its "current
6090     active link" forward or backward, and call
6091     focusNextPrevChild() only when it reaches the last or
6092     first link on the "page".
6093
6094     Child widgets call focusNextPrevChild() on their parent widgets,
6095     but only the window that contains the child widgets decides where
6096     to redirect focus. By reimplementing this function for an object,
6097     you thus gain control of focus traversal for all child widgets.
6098
6099     \sa focusNextChild(), focusPreviousChild()
6100 */
6101
6102 bool QWidget::focusNextPrevChild(bool next)
6103 {
6104     Q_D(QWidget);
6105     QWidget* p = parentWidget();
6106     bool isSubWindow = (windowType() == Qt::SubWindow);
6107     if (!isWindow() && !isSubWindow && p)
6108         return p->focusNextPrevChild(next);
6109 #ifndef QT_NO_GRAPHICSVIEW
6110     if (d->extra && d->extra->proxyWidget)
6111         return d->extra->proxyWidget->focusNextPrevChild(next);
6112 #endif
6113     QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6114     if (!w) return false;
6115
6116     w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6117     return true;
6118 }
6119
6120 /*!
6121     Returns the last child of this widget that setFocus had been
6122     called on.  For top level widgets this is the widget that will get
6123     focus in case this window gets activated
6124
6125     This is not the same as QApplication::focusWidget(), which returns
6126     the focus widget in the currently active window.
6127 */
6128
6129 QWidget *QWidget::focusWidget() const
6130 {
6131     return const_cast<QWidget *>(d_func()->focus_child);
6132 }
6133
6134 /*!
6135     Returns the next widget in this widget's focus chain.
6136
6137     \sa previousInFocusChain()
6138 */
6139 QWidget *QWidget::nextInFocusChain() const
6140 {
6141     return const_cast<QWidget *>(d_func()->focus_next);
6142 }
6143
6144 /*!
6145     \brief The previousInFocusChain function returns the previous
6146     widget in this widget's focus chain.
6147
6148     \sa nextInFocusChain()
6149
6150     \since 4.6
6151 */
6152 QWidget *QWidget::previousInFocusChain() const
6153 {
6154     return const_cast<QWidget *>(d_func()->focus_prev);
6155 }
6156
6157 /*!
6158     \property QWidget::isActiveWindow
6159     \brief whether this widget's window is the active window
6160
6161     The active window is the window that contains the widget that has
6162     keyboard focus (The window may still have focus if it has no
6163     widgets or none of its widgets accepts keyboard focus).
6164
6165     When popup windows are visible, this property is true for both the
6166     active window \e and for the popup.
6167
6168     By default, this property is false.
6169
6170     \sa activateWindow(), QApplication::activeWindow()
6171 */
6172 bool QWidget::isActiveWindow() const
6173 {
6174     QWidget *tlw = window();
6175     if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6176         return true;
6177
6178 #ifndef QT_NO_GRAPHICSVIEW
6179     if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6180         if (isVisible() && tlwExtra->proxyWidget)
6181             return tlwExtra->proxyWidget->isActiveWindow();
6182     }
6183 #endif
6184
6185 #ifdef Q_WS_MAC
6186     extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6187     if(qt_mac_is_macdrawer(tlw) &&
6188        tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6189         return true;
6190
6191     extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6192     if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6193         return true;
6194 #endif
6195     if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6196         if(tlw->windowType() == Qt::Tool &&
6197            !tlw->isModal() &&
6198            (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6199            return true;
6200         QWidget *w = QApplication::activeWindow();
6201         while(w && tlw->windowType() == Qt::Tool &&
6202               !w->isModal() && w->parentWidget()) {
6203             w = w->parentWidget()->window();
6204             if(w == tlw)
6205                 return true;
6206         }
6207     }
6208 #if defined(Q_WS_WIN32)
6209     HWND active = GetActiveWindow();
6210     if (!tlw->testAttribute(Qt::WA_WState_Created))
6211         return false;
6212     return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6213 #else
6214     return false;
6215 #endif
6216 }
6217
6218 /*!
6219     Puts the \a second widget after the \a first widget in the focus order.
6220
6221     Note that since the tab order of the \a second widget is changed, you
6222     should order a chain like this:
6223
6224     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6225
6226     \e not like this:
6227
6228     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6229
6230     If \a first or \a second has a focus proxy, setTabOrder()
6231     correctly substitutes the proxy.
6232
6233     \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6234 */
6235 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6236 {
6237     if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6238         return;
6239
6240     if (first->window() != second->window()) {
6241         qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6242         return;
6243     }
6244
6245     QWidget *fp = first->focusProxy();
6246     if (fp) {
6247         // If first is redirected, set first to the last child of first
6248         // that can take keyboard focus so that second is inserted after
6249         // that last child, and the focus order within first is (more
6250         // likely to be) preserved.
6251         QList<QWidget *> l = first->findChildren<QWidget *>();
6252         for (int i = l.size()-1; i >= 0; --i) {
6253             QWidget * next = l.at(i);
6254             if (next->window() == fp->window()) {
6255                 fp = next;
6256                 if (fp->focusPolicy() != Qt::NoFocus)
6257                     break;
6258             }
6259         }
6260         first = fp;
6261     }
6262
6263     if (fp == second)
6264         return;
6265
6266     if (QWidget *sp = second->focusProxy())
6267         second = sp;
6268
6269 //    QWidget *fp = first->d_func()->focus_prev;
6270     QWidget *fn = first->d_func()->focus_next;
6271
6272     if (fn == second || first == second)
6273         return;
6274
6275     QWidget *sp = second->d_func()->focus_prev;
6276     QWidget *sn = second->d_func()->focus_next;
6277
6278     fn->d_func()->focus_prev = second;
6279     first->d_func()->focus_next = second;
6280
6281     second->d_func()->focus_next = fn;
6282     second->d_func()->focus_prev = first;
6283
6284     sp->d_func()->focus_next = sn;
6285     sn->d_func()->focus_prev = sp;
6286
6287
6288     Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6289     Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6290
6291     Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6292     Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6293 }
6294
6295 /*!\internal
6296
6297   Moves the relevant subwidgets of this widget from the \a oldtlw's
6298   tab chain to that of the new parent, if there's anything to move and
6299   we're really moving
6300
6301   This function is called from QWidget::reparent() *after* the widget
6302   has been reparented.
6303
6304   \sa reparent()
6305 */
6306
6307 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6308 {
6309     Q_Q(QWidget);
6310     if (oldtlw == q->window())
6311         return; // nothing to do
6312
6313     if(focus_child)
6314         focus_child->clearFocus();
6315
6316     // separate the focus chain into new (children of myself) and old (the rest)
6317     QWidget *firstOld = 0;
6318     //QWidget *firstNew = q; //invariant
6319     QWidget *o = 0; // last in the old list
6320     QWidget *n = q; // last in the new list
6321
6322     bool prevWasNew = true;
6323     QWidget *w = focus_next;
6324
6325     //Note: for efficiency, we do not maintain the list invariant inside the loop
6326     //we append items to the relevant list, and we optimize by not changing pointers
6327     //when subsequent items are going into the same list.
6328     while (w  != q) {
6329         bool currentIsNew =  q->isAncestorOf(w);
6330         if (currentIsNew) {
6331             if (!prevWasNew) {
6332                 //prev was old -- append to new list
6333                 n->d_func()->focus_next = w;
6334                 w->d_func()->focus_prev = n;
6335             }
6336             n = w;
6337         } else {
6338             if (prevWasNew) {
6339                 //prev was new -- append to old list, if there is one
6340                 if (o) {
6341                     o->d_func()->focus_next = w;
6342                     w->d_func()->focus_prev = o;
6343                 } else {
6344                     // "create" the old list
6345                     firstOld = w;
6346                 }
6347             }
6348             o = w;
6349         }
6350         w = w->d_func()->focus_next;
6351         prevWasNew = currentIsNew;
6352     }
6353
6354     //repair the old list:
6355     if (firstOld) {
6356         o->d_func()->focus_next = firstOld;
6357         firstOld->d_func()->focus_prev = o;
6358     }
6359
6360     if (!q->isWindow()) {
6361         QWidget *topLevel = q->window();
6362         //insert new chain into toplevel's chain
6363
6364         QWidget *prev = topLevel->d_func()->focus_prev;
6365
6366         topLevel->d_func()->focus_prev = n;
6367         prev->d_func()->focus_next = q;
6368
6369         focus_prev = prev;
6370         n->d_func()->focus_next = topLevel;
6371     } else {
6372         //repair the new list
6373             n->d_func()->focus_next = q;
6374             focus_prev = n;
6375     }
6376
6377 }
6378
6379 /*!\internal
6380
6381   Measures the shortest distance from a point to a rect.
6382
6383   This function is called from QDesktopwidget::screen(QPoint) to find the
6384   closest screen for a point.
6385   In directional KeypadNavigation, it is called to find the closest
6386   widget to the current focus widget center.
6387 */
6388 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6389 {
6390     int dx = 0;
6391     int dy = 0;
6392     if (p.x() < r.left())
6393         dx = r.left() - p.x();
6394     else if (p.x() > r.right())
6395         dx = p.x() - r.right();
6396     if (p.y() < r.top())
6397         dy = r.top() - p.y();
6398     else if (p.y() > r.bottom())
6399         dy = p.y() - r.bottom();
6400     return dx + dy;
6401 }
6402
6403 /*!
6404     \property QWidget::frameSize
6405     \brief the size of the widget including any window frame
6406
6407     By default, this property contains a value that depends on the user's
6408     platform and screen geometry.
6409 */
6410 QSize QWidget::frameSize() const
6411 {
6412     Q_D(const QWidget);
6413     if (isWindow() && !(windowType() == Qt::Popup)) {
6414         QRect fs = d->frameStrut();
6415         return QSize(data->crect.width() + fs.left() + fs.right(),
6416                       data->crect.height() + fs.top() + fs.bottom());
6417     }
6418     return data->crect.size();
6419 }
6420
6421 /*! \fn void QWidget::move(int x, int y)
6422
6423     \overload
6424
6425     This corresponds to move(QPoint(\a x, \a y)).
6426 */
6427
6428 void QWidget::move(const QPoint &p)
6429 {
6430     Q_D(QWidget);
6431     setAttribute(Qt::WA_Moved);
6432     if (isWindow())
6433         d->topData()->posFromMove = true;
6434     if (testAttribute(Qt::WA_WState_Created)) {
6435         d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6436                        p.y() + geometry().y() - QWidget::y(),
6437                        width(), height(), true);
6438         d->setDirtyOpaqueRegion();
6439     } else {
6440         data->crect.moveTopLeft(p); // no frame yet
6441         setAttribute(Qt::WA_PendingMoveEvent);
6442     }
6443 }
6444
6445 /*! \fn void QWidget::resize(int w, int h)
6446     \overload
6447
6448     This corresponds to resize(QSize(\a w, \a h)).
6449 */
6450
6451 void QWidget::resize(const QSize &s)
6452 {
6453     Q_D(QWidget);
6454     setAttribute(Qt::WA_Resized);
6455     if (testAttribute(Qt::WA_WState_Created)) {
6456         d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6457         d->setDirtyOpaqueRegion();
6458     } else {
6459         data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6460         setAttribute(Qt::WA_PendingResizeEvent);
6461     }
6462 }
6463
6464 void QWidget::setGeometry(const QRect &r)
6465 {
6466     Q_D(QWidget);
6467     setAttribute(Qt::WA_Resized);
6468     setAttribute(Qt::WA_Moved);
6469     if (isWindow())
6470         d->topData()->posFromMove = false;
6471     if (testAttribute(Qt::WA_WState_Created)) {
6472         d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6473         d->setDirtyOpaqueRegion();
6474     } else {
6475         data->crect.setTopLeft(r.topLeft());
6476         data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6477         setAttribute(Qt::WA_PendingMoveEvent);
6478         setAttribute(Qt::WA_PendingResizeEvent);
6479     }
6480 }
6481
6482 /*!
6483     \since 4.2
6484     Saves the current geometry and state for top-level widgets.
6485
6486     To save the geometry when the window closes, you can
6487     implement a close event like this:
6488
6489     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6490
6491     See the \l{Window Geometry} documentation for an overview of geometry
6492     issues with windows.
6493
6494     Use QMainWindow::saveState() to save the geometry and the state of
6495     toolbars and dock widgets.
6496
6497     \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6498 */
6499 QByteArray QWidget::saveGeometry() const
6500 {
6501 #ifdef Q_WS_MAC
6502     // We check if the window was maximized during this invocation. If so, we need to record the
6503     // starting position as 0,0.
6504     Q_D(const QWidget);
6505     QRect newFramePosition = frameGeometry();
6506     QRect newNormalPosition = normalGeometry();
6507     if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6508         // Change the starting position
6509         newFramePosition.moveTo(0, 0);
6510         newNormalPosition.moveTo(0, 0);
6511     }
6512 #endif // Q_WS_MAC
6513     QByteArray array;
6514     QDataStream stream(&array, QIODevice::WriteOnly);
6515     stream.setVersion(QDataStream::Qt_4_0);
6516     const quint32 magicNumber = 0x1D9D0CB;
6517     quint16 majorVersion = 1;
6518     quint16 minorVersion = 0;
6519     stream << magicNumber
6520            << majorVersion
6521            << minorVersion
6522 #ifdef Q_WS_MAC
6523            << newFramePosition
6524            << newNormalPosition
6525 #else
6526            << frameGeometry()
6527            << normalGeometry()
6528 #endif // Q_WS_MAC
6529            << qint32(QApplication::desktop()->screenNumber(this))
6530            << quint8(windowState() & Qt::WindowMaximized)
6531            << quint8(windowState() & Qt::WindowFullScreen);
6532     return array;
6533 }
6534
6535 /*!
6536     \since 4.2
6537
6538     Restores the geometry and state top-level widgets stored in the
6539     byte array \a geometry. Returns true on success; otherwise
6540     returns false.
6541
6542     If the restored geometry is off-screen, it will be modified to be
6543     inside the available screen geometry.
6544
6545     To restore geometry saved using QSettings, you can use code like
6546     this:
6547
6548     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6549
6550     See the \l{Window Geometry} documentation for an overview of geometry
6551     issues with windows.
6552
6553     Use QMainWindow::restoreState() to restore the geometry and the
6554     state of toolbars and dock widgets.
6555
6556     \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6557 */
6558 bool QWidget::restoreGeometry(const QByteArray &geometry)
6559 {
6560     if (geometry.size() < 4)
6561         return false;
6562     QDataStream stream(geometry);
6563     stream.setVersion(QDataStream::Qt_4_0);
6564
6565     const quint32 magicNumber = 0x1D9D0CB;
6566     quint32 storedMagicNumber;
6567     stream >> storedMagicNumber;
6568     if (storedMagicNumber != magicNumber)
6569         return false;
6570
6571     const quint16 currentMajorVersion = 1;
6572     quint16 majorVersion = 0;
6573     quint16 minorVersion = 0;
6574
6575     stream >> majorVersion >> minorVersion;
6576
6577     if (majorVersion != currentMajorVersion)
6578         return false;
6579     // (Allow all minor versions.)
6580
6581     QRect restoredFrameGeometry;
6582      QRect restoredNormalGeometry;
6583     qint32 restoredScreenNumber;
6584     quint8 maximized;
6585     quint8 fullScreen;
6586
6587     stream >> restoredFrameGeometry
6588            >> restoredNormalGeometry
6589            >> restoredScreenNumber
6590            >> maximized
6591            >> fullScreen;
6592
6593     const int frameHeight = 20;
6594     if (!restoredFrameGeometry.isValid())
6595         restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6596
6597     if (!restoredNormalGeometry.isValid())
6598         restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6599     if (!restoredNormalGeometry.isValid()) {
6600         // use the widget's adjustedSize if the sizeHint() doesn't help
6601         restoredNormalGeometry.setSize(restoredNormalGeometry
6602                                        .size()
6603                                        .expandedTo(d_func()->adjustedSize()));
6604     }
6605
6606     const QDesktopWidget * const desktop = QApplication::desktop();
6607     if (restoredScreenNumber >= desktop->numScreens())
6608         restoredScreenNumber = desktop->primaryScreen();
6609
6610     const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6611
6612     // Modify the restored geometry if we are about to restore to coordinates
6613     // that would make the window "lost". This happens if:
6614     // - The restored geometry is completely oustside the available geometry
6615     // - The title bar is outside the available geometry.
6616     // - (Mac only) The window is higher than the available geometry. It must
6617     //   be possible to bring the size grip on screen by moving the window.
6618 #ifdef Q_WS_MAC
6619     restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6620     restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6621 #endif
6622
6623     if (!restoredFrameGeometry.intersects(availableGeometry)) {
6624         restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6625         restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6626         restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6627     }
6628     restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6629
6630     if (!restoredNormalGeometry.intersects(availableGeometry)) {
6631         restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6632         restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6633         restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6634     }
6635     restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6636
6637     if (maximized || fullScreen) {
6638         // set geomerty before setting the window state to make
6639         // sure the window is maximized to the right screen.
6640         // Skip on windows: the window is restored into a broken
6641         // half-maximized state.
6642 #ifndef Q_WS_WIN
6643         setGeometry(restoredNormalGeometry);
6644 #endif
6645         Qt::WindowStates ws = windowState();
6646         if (maximized)
6647             ws |= Qt::WindowMaximized;
6648         if (fullScreen)
6649             ws |= Qt::WindowFullScreen;
6650        setWindowState(ws);
6651        d_func()->topData()->normalGeometry = restoredNormalGeometry;
6652     } else {
6653         QPoint offset;
6654 #ifdef Q_WS_X11
6655         if (isFullScreen())
6656             offset = d_func()->topData()->fullScreenOffset;
6657 #endif
6658         setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6659         move(restoredFrameGeometry.topLeft() + offset);
6660         resize(restoredNormalGeometry.size());
6661     }
6662     return true;
6663 }
6664
6665 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6666     \overload
6667
6668     This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6669 */
6670
6671 /*!
6672   Sets the margins around the contents of the widget to have the sizes
6673   \a left, \a top, \a right, and \a bottom. The margins are used by
6674   the layout system, and may be used by subclasses to specify the area
6675   to draw in (e.g. excluding the frame).
6676
6677   Changing the margins will trigger a resizeEvent().
6678
6679   \sa contentsRect(), getContentsMargins()
6680 */
6681 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6682 {
6683     Q_D(QWidget);
6684     if (left == d->leftmargin && top == d->topmargin
6685          && right == d->rightmargin && bottom == d->bottommargin)
6686         return;
6687     d->leftmargin = left;
6688     d->topmargin = top;
6689     d->rightmargin = right;
6690     d->bottommargin = bottom;
6691
6692     if (QLayout *l=d->layout)
6693         l->update(); //force activate; will do updateGeometry
6694     else
6695         updateGeometry();
6696
6697     // ### Qt 5: compat, remove
6698     if (isVisible()) {
6699         update();
6700         QResizeEvent e(data->crect.size(), data->crect.size());
6701         QApplication::sendEvent(this, &e);
6702     } else {
6703         setAttribute(Qt::WA_PendingResizeEvent, true);
6704     }
6705
6706     QEvent e(QEvent::ContentsRectChange);
6707     QApplication::sendEvent(this, &e);
6708 }
6709
6710 /*!
6711   \overload
6712   \since 4.6
6713
6714   \brief The setContentsMargins function sets the margins around the
6715   widget's contents.
6716
6717   Sets the margins around the contents of the widget to have the
6718   sizes determined by \a margins. The margins are
6719   used by the layout system, and may be used by subclasses to
6720   specify the area to draw in (e.g. excluding the frame).
6721
6722   Changing the margins will trigger a resizeEvent().
6723
6724   \sa contentsRect(), getContentsMargins()
6725 */
6726 void QWidget::setContentsMargins(const QMargins &margins)
6727 {
6728     setContentsMargins(margins.left(), margins.top(),
6729                        margins.right(), margins.bottom());
6730 }
6731
6732 /*!
6733   Returns the widget's contents margins for \a left, \a top, \a
6734   right, and \a bottom.
6735
6736   \sa setContentsMargins(), contentsRect()
6737  */
6738 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6739 {
6740     Q_D(const QWidget);
6741     if (left)
6742         *left = d->leftmargin;
6743     if (top)
6744         *top = d->topmargin;
6745     if (right)
6746         *right = d->rightmargin;
6747     if (bottom)
6748         *bottom = d->bottommargin;
6749 }
6750
6751 /*!
6752   \since 4.6
6753
6754   \brief The contentsMargins function returns the widget's contents margins.
6755
6756   \sa getContentsMargins(), setContentsMargins(), contentsRect()
6757  */
6758 QMargins QWidget::contentsMargins() const
6759 {
6760     Q_D(const QWidget);
6761     return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6762 }
6763
6764
6765 /*!
6766     Returns the area inside the widget's margins.
6767
6768     \sa setContentsMargins(), getContentsMargins()
6769 */
6770 QRect QWidget::contentsRect() const
6771 {
6772     Q_D(const QWidget);
6773     return QRect(QPoint(d->leftmargin, d->topmargin),
6774                  QPoint(data->crect.width() - 1 - d->rightmargin,
6775                         data->crect.height() - 1 - d->bottommargin));
6776
6777 }
6778
6779
6780
6781 /*!
6782   \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6783
6784   This signal is emitted when the widget's \l contextMenuPolicy is
6785   Qt::CustomContextMenu, and the user has requested a context menu on
6786   the widget. The position \a pos is the position of the context menu
6787   event that the widget receives. Normally this is in widget
6788   coordinates. The exception to this rule is QAbstractScrollArea and
6789   its subclasses that map the context menu event to coordinates of the
6790   \link QAbstractScrollArea::viewport() viewport() \endlink .
6791
6792
6793   \sa mapToGlobal() QMenu contextMenuPolicy
6794 */
6795
6796
6797 /*!
6798     \property QWidget::contextMenuPolicy
6799     \brief how the widget shows a context menu
6800
6801     The default value of this property is Qt::DefaultContextMenu,
6802     which means the contextMenuEvent() handler is called. Other values
6803     are Qt::NoContextMenu, Qt::PreventContextMenu,
6804     Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6805     Qt::CustomContextMenu, the signal customContextMenuRequested() is
6806     emitted.
6807
6808     \sa contextMenuEvent(), customContextMenuRequested(), actions()
6809 */
6810
6811 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6812 {
6813     return (Qt::ContextMenuPolicy)data->context_menu_policy;
6814 }
6815
6816 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6817 {
6818     data->context_menu_policy = (uint) policy;
6819 }
6820
6821 /*!
6822     \property QWidget::focusPolicy
6823     \brief the way the widget accepts keyboard focus
6824
6825     The policy is Qt::TabFocus if the widget accepts keyboard
6826     focus by tabbing, Qt::ClickFocus if the widget accepts
6827     focus by clicking, Qt::StrongFocus if it accepts both, and
6828     Qt::NoFocus (the default) if it does not accept focus at
6829     all.
6830
6831     You must enable keyboard focus for a widget if it processes
6832     keyboard events. This is normally done from the widget's
6833     constructor. For instance, the QLineEdit constructor calls
6834     setFocusPolicy(Qt::StrongFocus).
6835
6836     If the widget has a focus proxy, then the focus policy will
6837     be propagated to it.
6838
6839     \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6840 */
6841
6842
6843 Qt::FocusPolicy QWidget::focusPolicy() const
6844 {
6845     return (Qt::FocusPolicy)data->focus_policy;
6846 }
6847
6848 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6849 {
6850     data->focus_policy = (uint) policy;
6851     Q_D(QWidget);
6852     if (d->extra && d->extra->focus_proxy)
6853         d->extra->focus_proxy->setFocusPolicy(policy);
6854 }
6855
6856 /*!
6857     \property QWidget::updatesEnabled
6858     \brief whether updates are enabled
6859
6860     An updates enabled widget receives paint events and has a system
6861     background; a disabled widget does not. This also implies that
6862     calling update() and repaint() has no effect if updates are
6863     disabled.
6864
6865     By default, this property is true.
6866
6867     setUpdatesEnabled() is normally used to disable updates for a
6868     short period of time, for instance to avoid screen flicker during
6869     large changes. In Qt, widgets normally do not generate screen
6870     flicker, but on X11 the server might erase regions on the screen
6871     when widgets get hidden before they can be replaced by other
6872     widgets. Disabling updates solves this.
6873
6874     Example:
6875     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6876
6877     Disabling a widget implicitly disables all its children. Enabling a widget
6878     enables all child widgets \e except top-level widgets or those that
6879     have been explicitly disabled. Re-enabling updates implicitly calls
6880     update() on the widget.
6881
6882     \sa paintEvent()
6883 */
6884 void QWidget::setUpdatesEnabled(bool enable)
6885 {
6886     Q_D(QWidget);
6887     setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6888     d->setUpdatesEnabled_helper(enable);
6889 }
6890
6891 /*!  \fn void QWidget::show()
6892
6893     Shows the widget and its child widgets. This function is
6894     equivalent to setVisible(true).
6895
6896     \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6897     showNormal(), isVisible()
6898 */
6899
6900
6901 /*! \internal
6902
6903    Makes the widget visible in the isVisible() meaning of the word.
6904    It is only called for toplevels or widgets with visible parents.
6905  */
6906 void QWidgetPrivate::show_recursive()
6907 {
6908     Q_Q(QWidget);
6909     // polish if necessary
6910
6911     if (!q->testAttribute(Qt::WA_WState_Created))
6912         createRecursively();
6913     q->ensurePolished();
6914
6915     if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6916         q->parentWidget()->d_func()->layout->activate();
6917     // activate our layout before we and our children become visible
6918     if (layout)
6919         layout->activate();
6920
6921     show_helper();
6922 }
6923
6924 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6925 {
6926     Q_Q(QWidget);
6927
6928     disableUpdates = disableUpdates && q->updatesEnabled();
6929     if (disableUpdates)
6930         q->setAttribute(Qt::WA_UpdatesDisabled);
6931
6932     if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6933         QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6934         QApplication::sendEvent(q, &e);
6935         q->setAttribute(Qt::WA_PendingMoveEvent, false);
6936     }
6937
6938     if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6939         QResizeEvent e(data.crect.size(), QSize());
6940         QApplication::sendEvent(q, &e);
6941         q->setAttribute(Qt::WA_PendingResizeEvent, false);
6942     }
6943
6944     if (disableUpdates)
6945         q->setAttribute(Qt::WA_UpdatesDisabled, false);
6946
6947     if (!recursive)
6948         return;
6949
6950     for (int i = 0; i < children.size(); ++i) {
6951         if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6952             child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6953     }
6954 }
6955
6956 void QWidgetPrivate::activateChildLayoutsRecursively()
6957 {
6958     sendPendingMoveAndResizeEvents(false, true);
6959
6960     for (int i = 0; i < children.size(); ++i) {
6961         QWidget *child = qobject_cast<QWidget *>(children.at(i));
6962         if (!child || child->isHidden() || child->isWindow())
6963             continue;
6964
6965         child->ensurePolished();
6966
6967         // Activate child's layout
6968         QWidgetPrivate *childPrivate = child->d_func();
6969         if (childPrivate->layout)
6970             childPrivate->layout->activate();
6971
6972         // Pretend we're visible.
6973         const bool wasVisible = child->isVisible();
6974         if (!wasVisible)
6975             child->setAttribute(Qt::WA_WState_Visible);
6976
6977         // Do the same for all my children.
6978         childPrivate->activateChildLayoutsRecursively();
6979
6980         // We're not cheating anymore.
6981         if (!wasVisible)
6982             child->setAttribute(Qt::WA_WState_Visible, false);
6983     }
6984 }
6985
6986 void QWidgetPrivate::show_helper()
6987 {
6988     Q_Q(QWidget);
6989     data.in_show = true; // qws optimization
6990     // make sure we receive pending move and resize events
6991     sendPendingMoveAndResizeEvents();
6992
6993     // become visible before showing all children
6994     q->setAttribute(Qt::WA_WState_Visible);
6995
6996     // finally show all children recursively
6997     showChildren(false);
6998
6999
7000
7001     // popup handling: new popups and tools need to be raised, and
7002     // existing popups must be closed. Also propagate the current
7003     // windows's KeyboardFocusChange status.
7004     if (q->isWindow()) {
7005         if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7006             q->raise();
7007             if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7008                 q->setAttribute(Qt::WA_KeyboardFocusChange);
7009         } else {
7010             while (QApplication::activePopupWidget()) {
7011                 if (!QApplication::activePopupWidget()->close())
7012                     break;
7013             }
7014         }
7015     }
7016
7017     // Automatic embedding of child windows of widgets already embedded into
7018     // QGraphicsProxyWidget when they are shown the first time.
7019     bool isEmbedded = false;
7020 #ifndef QT_NO_GRAPHICSVIEW
7021     if (q->isWindow()) {
7022         isEmbedded = q->graphicsProxyWidget() ? true : false;
7023         if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7024             QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7025             if (ancestorProxy) {
7026                 isEmbedded = true;
7027                 ancestorProxy->d_func()->embedSubWindow(q);
7028             }
7029         }
7030     }
7031 #else
7032     Q_UNUSED(isEmbedded);
7033 #endif
7034
7035     // On Windows, show the popup now so that our own focus handling
7036     // stores the correct old focus widget even if it's stolen in the
7037     // showevent
7038 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7039     if (!isEmbedded && q->windowType() == Qt::Popup)
7040         qApp->d_func()->openPopup(q);
7041 #endif
7042
7043     // send the show event before showing the window
7044     QShowEvent showEvent;
7045     QApplication::sendEvent(q, &showEvent);
7046
7047     if (!isEmbedded && q->isModal() && q->isWindow())
7048         // QApplicationPrivate::enterModal *before* show, otherwise the initial
7049         // stacking might be wrong
7050         QApplicationPrivate::enterModal(q);
7051
7052
7053     show_sys();
7054
7055     if (!isEmbedded && q->windowType() == Qt::Popup)
7056         qApp->d_func()->openPopup(q);
7057
7058 #ifndef QT_NO_ACCESSIBILITY
7059     if (q->windowType() != Qt::ToolTip) {    // Tooltips are read aloud twice in MS narrator.
7060         QAccessibleEvent event(QAccessible::ObjectShow, q);
7061         QAccessible::updateAccessibility(&event);
7062     }
7063 #endif
7064
7065     if (QApplicationPrivate::hidden_focus_widget == q) {
7066         QApplicationPrivate::hidden_focus_widget = 0;
7067         q->setFocus(Qt::OtherFocusReason);
7068     }
7069
7070     // Process events when showing a Qt::SplashScreen widget before the event loop
7071     // is spinnning; otherwise it might not show up on particular platforms.
7072     // This makes QSplashScreen behave the same on all platforms.
7073     if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7074         QApplication::processEvents();
7075
7076     data.in_show = false;  // reset qws optimization
7077 }
7078
7079 /*! \fn void QWidget::hide()
7080
7081     Hides the widget. This function is equivalent to
7082     setVisible(false).
7083
7084
7085     \note If you are working with QDialog or its subclasses and you invoke
7086     the show() function after this function, the dialog will be displayed in
7087     its original position.
7088
7089     \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7090 */
7091
7092 /*!\internal
7093  */
7094 void QWidgetPrivate::hide_helper()
7095 {
7096     Q_Q(QWidget);
7097
7098     bool isEmbedded = false;
7099 #if !defined QT_NO_GRAPHICSVIEW
7100     isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7101 #else
7102     Q_UNUSED(isEmbedded);
7103 #endif
7104
7105     if (!isEmbedded && (q->windowType() == Qt::Popup))
7106         qApp->d_func()->closePopup(q);
7107
7108     // Move test modal here.  Otherwise, a modal dialog could get
7109     // destroyed and we lose all access to its parent because we haven't
7110     // left modality.  (Eg. modal Progress Dialog)
7111     if (!isEmbedded && q->isModal() && q->isWindow())
7112         QApplicationPrivate::leaveModal(q);
7113
7114 #if defined(Q_WS_WIN)
7115     if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7116         && !q->parentWidget()->isHidden() && q->isActiveWindow())
7117         q->parentWidget()->activateWindow();        // Activate parent
7118 #endif
7119
7120     q->setAttribute(Qt::WA_Mapped, false);
7121     hide_sys();
7122
7123     bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7124
7125     if (wasVisible) {
7126         q->setAttribute(Qt::WA_WState_Visible, false);
7127
7128     }
7129
7130     QHideEvent hideEvent;
7131     QApplication::sendEvent(q, &hideEvent);
7132     hideChildren(false);
7133
7134     // next bit tries to move the focus if the focus widget is now
7135     // hidden.
7136     if (wasVisible) {
7137         qApp->d_func()->sendSyntheticEnterLeave(q);
7138         QWidget *fw = QApplication::focusWidget();
7139         while (fw &&  !fw->isWindow()) {
7140             if (fw == q) {
7141                 q->focusNextPrevChild(true);
7142                 break;
7143             }
7144             fw = fw->parentWidget();
7145         }
7146     }
7147
7148     if (QWidgetBackingStore *bs = maybeBackingStore())
7149         bs->removeDirtyWidget(q);
7150
7151 #ifndef QT_NO_ACCESSIBILITY
7152     if (wasVisible) {
7153         QAccessibleEvent event(QAccessible::ObjectHide, q);
7154         QAccessible::updateAccessibility(&event);
7155     }
7156 #endif
7157 }
7158
7159 /*!
7160     \fn bool QWidget::isHidden() const
7161
7162     Returns true if the widget is hidden, otherwise returns false.
7163
7164     A hidden widget will only become visible when show() is called on
7165     it. It will not be automatically shown when the parent is shown.
7166
7167     To check visibility, use !isVisible() instead (notice the exclamation mark).
7168
7169     isHidden() implies !isVisible(), but a widget can be not visible
7170     and not hidden at the same time. This is the case for widgets that are children of
7171     widgets that are not visible.
7172
7173
7174     Widgets are hidden if:
7175     \list
7176         \li they were created as independent windows,
7177         \li they were created as children of visible widgets,
7178         \li hide() or setVisible(false) was called.
7179     \endlist
7180 */
7181
7182
7183 void QWidget::setVisible(bool visible)
7184 {
7185     if (visible) { // show
7186         if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7187             return;
7188
7189         Q_D(QWidget);
7190
7191         // Designer uses a trick to make grabWidget work without showing
7192         if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7193             && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7194             parentWidget()->window()->d_func()->createRecursively();
7195
7196         //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7197         //but not children of non-visible parents
7198         QWidget *pw = parentWidget();
7199         if (!testAttribute(Qt::WA_WState_Created)
7200             && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7201             create();
7202         }
7203
7204 #if defined(Q_WS_X11)
7205         if (windowType() == Qt::Window)
7206             QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7207 #endif
7208
7209         bool wasResized = testAttribute(Qt::WA_Resized);
7210         Qt::WindowStates initialWindowState = windowState();
7211
7212         // polish if necessary
7213         ensurePolished();
7214
7215         // remember that show was called explicitly
7216         setAttribute(Qt::WA_WState_ExplicitShowHide);
7217         // whether we need to inform the parent widget immediately
7218         bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7219         // we are no longer hidden
7220         setAttribute(Qt::WA_WState_Hidden, false);
7221
7222         if (needUpdateGeometry)
7223             d->updateGeometry_helper(true);
7224
7225         // activate our layout before we and our children become visible
7226         if (d->layout)
7227             d->layout->activate();
7228
7229         if (!isWindow()) {
7230             QWidget *parent = parentWidget();
7231             while (parent && parent->isVisible() && parent->d_func()->layout  && !parent->data->in_show) {
7232                 parent->d_func()->layout->activate();
7233                 if (parent->isWindow())
7234                     break;
7235                 parent = parent->parentWidget();
7236             }
7237             if (parent)
7238                 parent->d_func()->setDirtyOpaqueRegion();
7239         }
7240
7241         // adjust size if necessary
7242         if (!wasResized
7243             && (isWindow() || !parentWidget()->d_func()->layout))  {
7244             if (isWindow()) {
7245                 adjustSize();
7246                 if (windowState() != initialWindowState)
7247                     setWindowState(initialWindowState);
7248             } else {
7249                 adjustSize();
7250             }
7251             setAttribute(Qt::WA_Resized, false);
7252         }
7253
7254         setAttribute(Qt::WA_KeyboardFocusChange, false);
7255
7256         if (isWindow() || parentWidget()->isVisible()) {
7257             d->show_helper();
7258
7259             qApp->d_func()->sendSyntheticEnterLeave(this);
7260         }
7261
7262         QEvent showToParentEvent(QEvent::ShowToParent);
7263         QApplication::sendEvent(this, &showToParentEvent);
7264     } else { // hide
7265         if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7266             return;
7267 #if defined(Q_WS_WIN)
7268         // reset WS_DISABLED style in a Blocked window
7269         if(isWindow() && testAttribute(Qt::WA_WState_Created)
7270            && QApplicationPrivate::isBlockedByModal(this))
7271         {
7272             LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7273             dwStyle &= ~WS_DISABLED;
7274             SetWindowLong(winId(), GWL_STYLE, dwStyle);
7275         }
7276 #endif
7277         if (QApplicationPrivate::hidden_focus_widget == this)
7278             QApplicationPrivate::hidden_focus_widget = 0;
7279
7280         Q_D(QWidget);
7281
7282         // hw: The test on getOpaqueRegion() needs to be more intelligent
7283         // currently it doesn't work if the widget is hidden (the region will
7284         // be clipped). The real check should be testing the cached region
7285         // (and dirty flag) directly.
7286         if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7287             parentWidget()->d_func()->setDirtyOpaqueRegion();
7288
7289         setAttribute(Qt::WA_WState_Hidden);
7290         setAttribute(Qt::WA_WState_ExplicitShowHide);
7291         if (testAttribute(Qt::WA_WState_Created))
7292             d->hide_helper();
7293
7294         // invalidate layout similar to updateGeometry()
7295         if (!isWindow() && parentWidget()) {
7296             if (parentWidget()->d_func()->layout)
7297                 parentWidget()->d_func()->layout->invalidate();
7298             else if (parentWidget()->isVisible())
7299                 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7300         }
7301
7302         QEvent hideToParentEvent(QEvent::HideToParent);
7303         QApplication::sendEvent(this, &hideToParentEvent);
7304     }
7305 }
7306
7307 /*!\fn void QWidget::setHidden(bool hidden)
7308
7309     Convenience function, equivalent to setVisible(!\a hidden).
7310 */
7311
7312
7313 void QWidgetPrivate::_q_showIfNotHidden()
7314 {
7315     Q_Q(QWidget);
7316     if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7317         q->setVisible(true);
7318 }
7319
7320 void QWidgetPrivate::showChildren(bool spontaneous)
7321 {
7322     QList<QObject*> childList = children;
7323     for (int i = 0; i < childList.size(); ++i) {
7324         QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7325         if (!widget
7326             || widget->isWindow()
7327             || widget->testAttribute(Qt::WA_WState_Hidden))
7328             continue;
7329         if (spontaneous) {
7330             widget->setAttribute(Qt::WA_Mapped);
7331             widget->d_func()->showChildren(true);
7332             QShowEvent e;
7333             QApplication::sendSpontaneousEvent(widget, &e);
7334         } else {
7335             if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7336                 widget->d_func()->show_recursive();
7337             else
7338                 widget->show();
7339         }
7340     }
7341 }
7342
7343 void QWidgetPrivate::hideChildren(bool spontaneous)
7344 {
7345     QList<QObject*> childList = children;
7346     for (int i = 0; i < childList.size(); ++i) {
7347         QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7348         if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7349             continue;
7350 #ifdef Q_WS_MAC
7351         // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7352         // When hiding a widget we need to make sure that no mouse_down events are active, because
7353         // the mouse_up event will never be received by a hidden widget or one of its descendants.
7354         // The solution is simple, before going through with this we check if there are any mouse_down events in
7355         // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7356         // then we continue.
7357         // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7358         // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7359         // mouse release event. There are two ways to interpret this:
7360         // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7361         // might be waiting for a release event that will never arrive.
7362         // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7363         // supposed to trigger because it is not visible.
7364         if(widget == qt_button_down)
7365             qt_button_down = 0;
7366 #endif // Q_WS_MAC
7367         if (spontaneous)
7368             widget->setAttribute(Qt::WA_Mapped, false);
7369         else
7370             widget->setAttribute(Qt::WA_WState_Visible, false);
7371         widget->d_func()->hideChildren(spontaneous);
7372         QHideEvent e;
7373         if (spontaneous) {
7374             QApplication::sendSpontaneousEvent(widget, &e);
7375         } else {
7376             QApplication::sendEvent(widget, &e);
7377             if (widget->internalWinId()
7378                 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7379                 // hide_sys() on an ancestor won't have any affect on this
7380                 // widget, so it needs an explicit hide_sys() of its own
7381                 widget->d_func()->hide_sys();
7382             }
7383         }
7384         qApp->d_func()->sendSyntheticEnterLeave(widget);
7385 #ifndef QT_NO_ACCESSIBILITY
7386         if (!spontaneous) {
7387             QAccessibleEvent event(QAccessible::ObjectHide, widget);
7388             QAccessible::updateAccessibility(&event);
7389         }
7390 #endif
7391     }
7392 }
7393
7394 bool QWidgetPrivate::close_helper(CloseMode mode)
7395 {
7396     if (data.is_closing)
7397         return true;
7398
7399     Q_Q(QWidget);
7400     data.is_closing = 1;
7401
7402     QPointer<QWidget> that = q;
7403     QPointer<QWidget> parentWidget = q->parentWidget();
7404
7405     bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7406     if (mode != CloseNoEvent) {
7407         QCloseEvent e;
7408         if (mode == CloseWithSpontaneousEvent)
7409             QApplication::sendSpontaneousEvent(q, &e);
7410         else
7411             QApplication::sendEvent(q, &e);
7412         if (!that.isNull() && !e.isAccepted()) {
7413             data.is_closing = 0;
7414             return false;
7415         }
7416     }
7417
7418     if (!that.isNull() && !q->isHidden())
7419         q->hide();
7420
7421     // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7422     quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7423
7424     if (quitOnClose) {
7425         /* if there is no non-withdrawn primary window left (except
7426            the ones without QuitOnClose), we emit the lastWindowClosed
7427            signal */
7428         QWidgetList list = QApplication::topLevelWidgets();
7429         bool lastWindowClosed = true;
7430         for (int i = 0; i < list.size(); ++i) {
7431             QWidget *w = list.at(i);
7432             if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7433                 continue;
7434             lastWindowClosed = false;
7435             break;
7436         }
7437         if (lastWindowClosed) {
7438             QGuiApplicationPrivate::emitLastWindowClosed();
7439             QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7440             applicationPrivate->maybeQuit();
7441         }
7442     }
7443
7444
7445     if (!that.isNull()) {
7446         data.is_closing = 0;
7447         if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7448             q->setAttribute(Qt::WA_DeleteOnClose, false);
7449             q->deleteLater();
7450         }
7451     }
7452     return true;
7453 }
7454
7455
7456 /*!
7457     Closes this widget. Returns true if the widget was closed;
7458     otherwise returns false.
7459
7460     First it sends the widget a QCloseEvent. The widget is \link
7461     hide() hidden\endlink if it \link QCloseEvent::accept()
7462     accepts\endlink the close event. If it \link QCloseEvent::ignore()
7463     ignores\endlink the event, nothing happens. The default
7464     implementation of QWidget::closeEvent() accepts the close event.
7465
7466     If the widget has the Qt::WA_DeleteOnClose flag, the widget
7467     is also deleted. A close events is delivered to the widget no
7468     matter if the widget is visible or not.
7469
7470     The \l QApplication::lastWindowClosed() signal is emitted when the
7471     last visible primary window (i.e. window with no parent) with the
7472     Qt::WA_QuitOnClose attribute set is closed. By default this
7473     attribute is set for all widgets except transient windows such as
7474     splash screens, tool windows, and popup menus.
7475
7476 */
7477
7478 bool QWidget::close()
7479 {
7480     return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7481 }
7482
7483 /*!
7484     \property QWidget::visible
7485     \brief whether the widget is visible
7486
7487     Calling setVisible(true) or show() sets the widget to visible
7488     status if all its parent widgets up to the window are visible. If
7489     an ancestor is not visible, the widget won't become visible until
7490     all its ancestors are shown. If its size or position has changed,
7491     Qt guarantees that a widget gets move and resize events just
7492     before it is shown. If the widget has not been resized yet, Qt
7493     will adjust the widget's size to a useful default using
7494     adjustSize().
7495
7496     Calling setVisible(false) or hide() hides a widget explicitly. An
7497     explicitly hidden widget will never become visible, even if all
7498     its ancestors become visible, unless you show it.
7499
7500     A widget receives show and hide events when its visibility status
7501     changes. Between a hide and a show event, there is no need to
7502     waste CPU cycles preparing or displaying information to the user.
7503     A video application, for example, might simply stop generating new
7504     frames.
7505
7506     A widget that happens to be obscured by other windows on the
7507     screen is considered to be visible. The same applies to iconified
7508     windows and windows that exist on another virtual
7509     desktop (on platforms that support this concept). A widget
7510     receives spontaneous show and hide events when its mapping status
7511     is changed by the window system, e.g. a spontaneous hide event
7512     when the user minimizes the window, and a spontaneous show event
7513     when the window is restored again.
7514
7515     You almost never have to reimplement the setVisible() function. If
7516     you need to change some settings before a widget is shown, use
7517     showEvent() instead. If you need to do some delayed initialization
7518     use the Polish event delivered to the event() function.
7519
7520     \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7521     showEvent(), hideEvent()
7522 */
7523
7524
7525 /*!
7526     Returns true if this widget would become visible if \a ancestor is
7527     shown; otherwise returns false.
7528
7529     The true case occurs if neither the widget itself nor any parent
7530     up to but excluding \a ancestor has been explicitly hidden.
7531
7532     This function will still return true if the widget is obscured by
7533     other windows on the screen, but could be physically visible if it
7534     or they were to be moved.
7535
7536     isVisibleTo(0) is identical to isVisible().
7537
7538     \sa show() hide() isVisible()
7539 */
7540
7541 bool QWidget::isVisibleTo(QWidget* ancestor) const
7542 {
7543     if (!ancestor)
7544         return isVisible();
7545     const QWidget * w = this;
7546     while (!w->isHidden()
7547             && !w->isWindow()
7548             && w->parentWidget()
7549             && w->parentWidget() != ancestor)
7550         w = w->parentWidget();
7551     return !w->isHidden();
7552 }
7553
7554
7555 /*!
7556     Returns the unobscured region where paint events can occur.
7557
7558     For visible widgets, this is an approximation of the area not
7559     covered by other widgets; otherwise, this is an empty region.
7560
7561     The repaint() function calls this function if necessary, so in
7562     general you do not need to call it.
7563
7564 */
7565 QRegion QWidget::visibleRegion() const
7566 {
7567     Q_D(const QWidget);
7568
7569     QRect clipRect = d->clipRect();
7570     if (clipRect.isEmpty())
7571         return QRegion();
7572     QRegion r(clipRect);
7573     d->subtractOpaqueChildren(r, clipRect);
7574     d->subtractOpaqueSiblings(r);
7575     return r;
7576 }
7577
7578
7579 QSize QWidgetPrivate::adjustedSize() const
7580 {
7581     Q_Q(const QWidget);
7582
7583     QSize s = q->sizeHint();
7584
7585     if (q->isWindow()) {
7586         Qt::Orientations exp;
7587         if (layout) {
7588             if (layout->hasHeightForWidth())
7589                 s.setHeight(layout->totalHeightForWidth(s.width()));
7590             exp = layout->expandingDirections();
7591         } else
7592         {
7593             if (q->sizePolicy().hasHeightForWidth())
7594                 s.setHeight(q->heightForWidth(s.width()));
7595             exp = q->sizePolicy().expandingDirections();
7596         }
7597         if (exp & Qt::Horizontal)
7598             s.setWidth(qMax(s.width(), 200));
7599         if (exp & Qt::Vertical)
7600             s.setHeight(qMax(s.height(), 100));
7601 #if defined(Q_WS_X11)
7602         QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7603 #else // all others
7604         QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7605 #endif
7606 #if defined (Q_OS_WINCE)
7607         s.setWidth(qMin(s.width(), screen.width()));
7608         s.setHeight(qMin(s.height(), screen.height()));
7609 #else
7610         s.setWidth(qMin(s.width(), screen.width()*2/3));
7611         s.setHeight(qMin(s.height(), screen.height()*2/3));
7612 #endif
7613         if (QTLWExtra *extra = maybeTopData())
7614             extra->sizeAdjusted = true;
7615     }
7616
7617     if (!s.isValid()) {
7618         QRect r = q->childrenRect(); // get children rectangle
7619         if (r.isNull())
7620             return s;
7621         s = r.size() + QSize(2 * r.x(), 2 * r.y());
7622     }
7623
7624     return s;
7625 }
7626
7627 /*!
7628     Adjusts the size of the widget to fit its contents.
7629
7630     This function uses sizeHint() if it is valid, i.e., the size hint's width
7631     and height are \>= 0. Otherwise, it sets the size to the children
7632     rectangle that covers all child widgets (the union of all child widget
7633     rectangles).
7634
7635     For windows, the screen size is also taken into account. If the sizeHint()
7636     is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7637     {expanding}, the window will be at least (200, 100). The maximum size of
7638     a window is 2/3 of the screen's width and height.
7639
7640     \sa sizeHint(), childrenRect()
7641 */
7642
7643 void QWidget::adjustSize()
7644 {
7645     Q_D(QWidget);
7646     ensurePolished();
7647     QSize s = d->adjustedSize();
7648
7649     if (d->layout)
7650         d->layout->activate();
7651
7652     if (s.isValid())
7653         resize(s);
7654 }
7655
7656
7657 /*!
7658     \property QWidget::sizeHint
7659     \brief the recommended size for the widget
7660
7661     If the value of this property is an invalid size, no size is
7662     recommended.
7663
7664     The default implementation of sizeHint() returns an invalid size
7665     if there is no layout for this widget, and returns the layout's
7666     preferred size otherwise.
7667
7668     \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7669     setMinimumSize(), updateGeometry()
7670 */
7671
7672 QSize QWidget::sizeHint() const
7673 {
7674     Q_D(const QWidget);
7675     if (d->layout)
7676         return d->layout->totalSizeHint();
7677     return QSize(-1, -1);
7678 }
7679
7680 /*!
7681     \property QWidget::minimumSizeHint
7682     \brief the recommended minimum size for the widget
7683
7684     If the value of this property is an invalid size, no minimum size
7685     is recommended.
7686
7687     The default implementation of minimumSizeHint() returns an invalid
7688     size if there is no layout for this widget, and returns the
7689     layout's minimum size otherwise. Most built-in widgets reimplement
7690     minimumSizeHint().
7691
7692     \l QLayout will never resize a widget to a size smaller than the
7693     minimum size hint unless minimumSize() is set or the size policy is
7694     set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7695     size hint will be ignored.
7696
7697     \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7698 */
7699 QSize QWidget::minimumSizeHint() const
7700 {
7701     Q_D(const QWidget);
7702     if (d->layout)
7703         return d->layout->totalMinimumSize();
7704     return QSize(-1, -1);
7705 }
7706
7707
7708 /*!
7709     \fn QWidget *QWidget::parentWidget() const
7710
7711     Returns the parent of this widget, or 0 if it does not have any
7712     parent widget.
7713 */
7714
7715
7716 /*!
7717     Returns true if this widget is a parent, (or grandparent and so on
7718     to any level), of the given \a child, and both widgets are within
7719     the same window; otherwise returns false.
7720 */
7721
7722 bool QWidget::isAncestorOf(const QWidget *child) const
7723 {
7724     while (child) {
7725         if (child == this)
7726             return true;
7727         if (child->isWindow())
7728             return false;
7729         child = child->parentWidget();
7730     }
7731     return false;
7732 }
7733
7734 #if defined(Q_WS_WIN)
7735 inline void setDisabledStyle(QWidget *w, bool setStyle)
7736 {
7737     // set/reset WS_DISABLED style.
7738     if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7739         LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7740         LONG newStyle = dwStyle;
7741         if (setStyle)
7742             newStyle |= WS_DISABLED;
7743         else
7744             newStyle &= ~WS_DISABLED;
7745         if (newStyle != dwStyle) {
7746             SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7747             // we might need to repaint in some situations (eg. menu)
7748             w->repaint();
7749         }
7750     }
7751 }
7752 #endif
7753
7754 /*****************************************************************************
7755   QWidget event handling
7756  *****************************************************************************/
7757
7758 /*!
7759     This is the main event handler; it handles event \a event. You can
7760     reimplement this function in a subclass, but we recommend using
7761     one of the specialized event handlers instead.
7762
7763     Key press and release events are treated differently from other
7764     events. event() checks for Tab and Shift+Tab and tries to move the
7765     focus appropriately. If there is no widget to move the focus to
7766     (or the key press is not Tab or Shift+Tab), event() calls
7767     keyPressEvent().
7768
7769     Mouse and tablet event handling is also slightly special: only
7770     when the widget is \l enabled, event() will call the specialized
7771     handlers such as mousePressEvent(); otherwise it will discard the
7772     event.
7773
7774     This function returns true if the event was recognized, otherwise
7775     it returns false.  If the recognized event was accepted (see \l
7776     QEvent::accepted), any further processing such as event
7777     propagation to the parent widget stops.
7778
7779     \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7780     keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7781     mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7782     mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7783     QObject::event(), QObject::timerEvent()
7784 */
7785
7786 bool QWidget::event(QEvent *event)
7787 {
7788     Q_D(QWidget);
7789
7790     // ignore mouse events when disabled
7791     if (!isEnabled()) {
7792         switch(event->type()) {
7793         case QEvent::TabletPress:
7794         case QEvent::TabletRelease:
7795         case QEvent::TabletMove:
7796         case QEvent::MouseButtonPress:
7797         case QEvent::MouseButtonRelease:
7798         case QEvent::MouseButtonDblClick:
7799         case QEvent::MouseMove:
7800         case QEvent::TouchBegin:
7801         case QEvent::TouchUpdate:
7802         case QEvent::TouchEnd:
7803         case QEvent::TouchCancel:
7804         case QEvent::ContextMenu:
7805 #ifndef QT_NO_WHEELEVENT
7806         case QEvent::Wheel:
7807 #endif
7808             return false;
7809         default:
7810             break;
7811         }
7812     }
7813     switch (event->type()) {
7814     case QEvent::MouseMove:
7815         mouseMoveEvent((QMouseEvent*)event);
7816         break;
7817
7818     case QEvent::MouseButtonPress:
7819         mousePressEvent((QMouseEvent*)event);
7820         break;
7821
7822     case QEvent::MouseButtonRelease:
7823         mouseReleaseEvent((QMouseEvent*)event);
7824         break;
7825
7826     case QEvent::MouseButtonDblClick:
7827         mouseDoubleClickEvent((QMouseEvent*)event);
7828         break;
7829 #ifndef QT_NO_WHEELEVENT
7830     case QEvent::Wheel:
7831         wheelEvent((QWheelEvent*)event);
7832         break;
7833 #endif
7834 #ifndef QT_NO_TABLETEVENT
7835     case QEvent::TabletMove:
7836     case QEvent::TabletPress:
7837     case QEvent::TabletRelease:
7838         tabletEvent((QTabletEvent*)event);
7839         break;
7840 #endif
7841     case QEvent::KeyPress: {
7842         QKeyEvent *k = (QKeyEvent *)event;
7843         bool res = false;
7844         if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) {  //### Add MetaModifier?
7845             if (k->key() == Qt::Key_Backtab
7846                 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7847                 res = focusNextPrevChild(false);
7848             else if (k->key() == Qt::Key_Tab)
7849                 res = focusNextPrevChild(true);
7850             if (res)
7851                 break;
7852         }
7853         keyPressEvent(k);
7854 #ifdef QT_KEYPAD_NAVIGATION
7855         if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7856             && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7857             if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7858                 if (k->key() == Qt::Key_Up)
7859                     res = focusNextPrevChild(false);
7860                 else if (k->key() == Qt::Key_Down)
7861                     res = focusNextPrevChild(true);
7862             } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7863                 if (k->key() == Qt::Key_Up)
7864                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7865                 else if (k->key() == Qt::Key_Right)
7866                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7867                 else if (k->key() == Qt::Key_Down)
7868                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7869                 else if (k->key() == Qt::Key_Left)
7870                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7871             }
7872             if (res) {
7873                 k->accept();
7874                 break;
7875             }
7876         }
7877 #endif
7878 #ifndef QT_NO_WHATSTHIS
7879         if (!k->isAccepted()
7880             && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7881             && d->whatsThis.size()) {
7882             QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7883             k->accept();
7884         }
7885 #endif
7886     }
7887         break;
7888
7889     case QEvent::KeyRelease:
7890         keyReleaseEvent((QKeyEvent*)event);
7891         // fall through
7892     case QEvent::ShortcutOverride:
7893         break;
7894
7895     case QEvent::InputMethod:
7896         inputMethodEvent((QInputMethodEvent *) event);
7897         break;
7898
7899     case QEvent::InputMethodQuery:
7900         if (testAttribute(Qt::WA_InputMethodEnabled)) {
7901             QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7902             Qt::InputMethodQueries queries = query->queries();
7903             for (uint i = 0; i < 32; ++i) {
7904                 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7905                 if (q) {
7906                     QVariant v = inputMethodQuery(q);
7907                     if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7908                         v = QVariant(true); // special case for Qt4 compatibility
7909                     query->setValue(q, v);
7910                 }
7911             }
7912             query->accept();
7913             break;
7914         }
7915
7916     case QEvent::PolishRequest:
7917         ensurePolished();
7918         break;
7919
7920     case QEvent::Polish: {
7921         style()->polish(this);
7922         setAttribute(Qt::WA_WState_Polished);
7923         if (!QApplication::font(this).isCopyOf(QApplication::font()))
7924             d->resolveFont();
7925         if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7926             d->resolvePalette();
7927     }
7928         break;
7929
7930     case QEvent::ApplicationWindowIconChange:
7931         if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7932             d->setWindowIcon_sys();
7933             d->setWindowIcon_helper();
7934         }
7935         break;
7936     case QEvent::FocusIn:
7937 #ifdef QT_SOFTKEYS_ENABLED
7938         QSoftKeyManager::updateSoftKeys();
7939 #endif
7940         focusInEvent((QFocusEvent*)event);
7941         d->updateWidgetTransform();
7942         break;
7943
7944     case QEvent::FocusOut:
7945         focusOutEvent((QFocusEvent*)event);
7946         break;
7947
7948     case QEvent::Enter:
7949 #ifndef QT_NO_STATUSTIP
7950         if (d->statusTip.size()) {
7951             QStatusTipEvent tip(d->statusTip);
7952             QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7953         }
7954 #endif
7955         enterEvent(event);
7956         break;
7957
7958     case QEvent::Leave:
7959 #ifndef QT_NO_STATUSTIP
7960         if (d->statusTip.size()) {
7961             QString empty;
7962             QStatusTipEvent tip(empty);
7963             QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7964         }
7965 #endif
7966         leaveEvent(event);
7967         break;
7968
7969     case QEvent::HoverEnter:
7970     case QEvent::HoverLeave:
7971         update();
7972         break;
7973
7974     case QEvent::Paint:
7975         // At this point the event has to be delivered, regardless
7976         // whether the widget isVisible() or not because it
7977         // already went through the filters
7978         paintEvent((QPaintEvent*)event);
7979         break;
7980
7981     case QEvent::Move:
7982         moveEvent((QMoveEvent*)event);
7983         d->updateWidgetTransform();
7984         break;
7985
7986     case QEvent::Resize:
7987         resizeEvent((QResizeEvent*)event);
7988         d->updateWidgetTransform();
7989         break;
7990
7991     case QEvent::Close:
7992         closeEvent((QCloseEvent *)event);
7993         break;
7994
7995 #ifndef QT_NO_CONTEXTMENU
7996     case QEvent::ContextMenu:
7997         switch (data->context_menu_policy) {
7998         case Qt::PreventContextMenu:
7999             break;
8000         case Qt::DefaultContextMenu:
8001             contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8002             break;
8003         case Qt::CustomContextMenu:
8004             emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8005             break;
8006 #ifndef QT_NO_MENU
8007         case Qt::ActionsContextMenu:
8008             if (d->actions.count()) {
8009                 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8010                             0, this);
8011                 break;
8012             }
8013             // fall through
8014 #endif
8015         default:
8016             event->ignore();
8017             break;
8018         }
8019         break;
8020 #endif // QT_NO_CONTEXTMENU
8021
8022 #ifndef QT_NO_DRAGANDDROP
8023     case QEvent::Drop:
8024         dropEvent((QDropEvent*) event);
8025         break;
8026
8027     case QEvent::DragEnter:
8028         dragEnterEvent((QDragEnterEvent*) event);
8029         break;
8030
8031     case QEvent::DragMove:
8032         dragMoveEvent((QDragMoveEvent*) event);
8033         break;
8034
8035     case QEvent::DragLeave:
8036         dragLeaveEvent((QDragLeaveEvent*) event);
8037         break;
8038 #endif
8039
8040     case QEvent::Show:
8041         showEvent((QShowEvent*) event);
8042         break;
8043
8044     case QEvent::Hide:
8045         hideEvent((QHideEvent*) event);
8046         break;
8047
8048     case QEvent::ShowWindowRequest:
8049         if (!isHidden())
8050             d->show_sys();
8051         break;
8052
8053     case QEvent::ApplicationFontChange:
8054         d->resolveFont();
8055         break;
8056     case QEvent::ApplicationPaletteChange:
8057         if (!(windowType() == Qt::Desktop))
8058             d->resolvePalette();
8059         break;
8060
8061     case QEvent::ToolBarChange:
8062     case QEvent::ActivationChange:
8063     case QEvent::EnabledChange:
8064     case QEvent::FontChange:
8065     case QEvent::StyleChange:
8066     case QEvent::PaletteChange:
8067     case QEvent::WindowTitleChange:
8068     case QEvent::IconTextChange:
8069     case QEvent::ModifiedChange:
8070     case QEvent::MouseTrackingChange:
8071     case QEvent::ParentChange:
8072     case QEvent::WindowStateChange:
8073     case QEvent::LocaleChange:
8074     case QEvent::MacSizeChange:
8075     case QEvent::ContentsRectChange:
8076     case QEvent::ThemeChange:
8077         changeEvent(event);
8078         break;
8079
8080     case QEvent::WindowActivate:
8081     case QEvent::WindowDeactivate: {
8082         if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8083             update();
8084         QList<QObject*> childList = d->children;
8085         for (int i = 0; i < childList.size(); ++i) {
8086             QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8087             if (w && w->isVisible() && !w->isWindow())
8088                 QApplication::sendEvent(w, event);
8089         }
8090
8091 #ifdef QT_SOFTKEYS_ENABLED
8092         if (isWindow())
8093             QSoftKeyManager::updateSoftKeys();
8094 #endif
8095
8096         break; }
8097
8098     case QEvent::LanguageChange:
8099         changeEvent(event);
8100         {
8101             QList<QObject*> childList = d->children;
8102             for (int i = 0; i < childList.size(); ++i) {
8103                 QObject *o = childList.at(i);
8104                 if (o)
8105                     QApplication::sendEvent(o, event);
8106             }
8107         }
8108         update();
8109         break;
8110
8111     case QEvent::ApplicationLayoutDirectionChange:
8112         d->resolveLayoutDirection();
8113         break;
8114
8115     case QEvent::LayoutDirectionChange:
8116         if (d->layout)
8117             d->layout->invalidate();
8118         update();
8119         changeEvent(event);
8120         break;
8121     case QEvent::UpdateRequest:
8122         d->syncBackingStore();
8123         break;
8124     case QEvent::UpdateLater:
8125         update(static_cast<QUpdateLaterEvent*>(event)->region());
8126         break;
8127
8128     case QEvent::WindowBlocked:
8129     case QEvent::WindowUnblocked:
8130         {
8131             QList<QObject*> childList = d->children;
8132             for (int i = 0; i < childList.size(); ++i) {
8133                 QObject *o = childList.at(i);
8134                 if (o && o != QApplication::activeModalWidget()) {
8135                     if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8136                         // do not forward the event to child windows,
8137                         // QApplication does this for us
8138                         continue;
8139                     }
8140                     QApplication::sendEvent(o, event);
8141                 }
8142             }
8143 #if defined(Q_WS_WIN)
8144             setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8145 #endif
8146         }
8147         break;
8148 #ifndef QT_NO_TOOLTIP
8149     case QEvent::ToolTip:
8150         if (!d->toolTip.isEmpty())
8151             QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8152         else
8153             event->ignore();
8154         break;
8155 #endif
8156 #ifndef QT_NO_WHATSTHIS
8157     case QEvent::WhatsThis:
8158         if (d->whatsThis.size())
8159             QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8160         else
8161             event->ignore();
8162         break;
8163     case QEvent::QueryWhatsThis:
8164         if (d->whatsThis.isEmpty())
8165             event->ignore();
8166         break;
8167 #endif
8168     case QEvent::EmbeddingControl:
8169         d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8170         data->fstrut_dirty = false;
8171 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8172         d->topData()->embedded = 1;
8173 #endif
8174         break;
8175 #ifndef QT_NO_ACTION
8176     case QEvent::ActionAdded:
8177     case QEvent::ActionRemoved:
8178     case QEvent::ActionChanged:
8179 #ifdef QT_SOFTKEYS_ENABLED
8180         QSoftKeyManager::updateSoftKeys();
8181 #endif
8182         actionEvent((QActionEvent*)event);
8183         break;
8184 #endif
8185
8186     case QEvent::KeyboardLayoutChange:
8187         {
8188             changeEvent(event);
8189
8190             // inform children of the change
8191             QList<QObject*> childList = d->children;
8192             for (int i = 0; i < childList.size(); ++i) {
8193                 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8194                 if (w && w->isVisible() && !w->isWindow())
8195                     QApplication::sendEvent(w, event);
8196             }
8197             break;
8198         }
8199 #ifdef Q_WS_MAC
8200     case QEvent::MacGLWindowChange:
8201         d->needWindowChange = false;
8202         break;
8203 #endif
8204     case QEvent::TouchBegin:
8205     case QEvent::TouchUpdate:
8206     case QEvent::TouchEnd:
8207     case QEvent::TouchCancel:
8208     {
8209         event->ignore();
8210         break;
8211     }
8212 #ifndef QT_NO_GESTURES
8213     case QEvent::Gesture:
8214         event->ignore();
8215         break;
8216 #endif
8217 #ifndef QT_NO_PROPERTIES
8218     case QEvent::DynamicPropertyChange: {
8219         const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8220         if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8221             uint value = property(propName.constData()).toUInt();
8222             if (!d->extra)
8223                 d->createExtra();
8224             const char axis = propName.at(12);
8225             if (axis == 'X')
8226                 d->extra->customDpiX = value;
8227             else if (axis == 'Y')
8228                 d->extra->customDpiY = value;
8229             d->updateFont(d->data.fnt);
8230         }
8231         // fall through
8232     }
8233 #endif
8234     default:
8235         return QObject::event(event);
8236     }
8237     return true;
8238 }
8239
8240 /*!
8241   This event handler can be reimplemented to handle state changes.
8242
8243   The state being changed in this event can be retrieved through the \a event
8244   supplied.
8245
8246   Change events include: QEvent::ToolBarChange,
8247   QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8248   QEvent::StyleChange, QEvent::PaletteChange,
8249   QEvent::WindowTitleChange, QEvent::IconTextChange,
8250   QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8251   QEvent::ParentChange, QEvent::WindowStateChange,
8252   QEvent::LanguageChange, QEvent::LocaleChange,
8253   QEvent::LayoutDirectionChange.
8254
8255 */
8256 void QWidget::changeEvent(QEvent * event)
8257 {
8258     switch(event->type()) {
8259     case QEvent::EnabledChange: {
8260         update();
8261 #ifndef QT_NO_ACCESSIBILITY
8262         QAccessible::State s;
8263         s.disabled = true;
8264         QAccessibleStateChangeEvent event(s, this);
8265         QAccessible::updateAccessibility(&event);
8266 #endif
8267         break;
8268     }
8269
8270     case QEvent::FontChange:
8271     case QEvent::StyleChange: {
8272         Q_D(QWidget);
8273         update();
8274         updateGeometry();
8275         if (d->layout)
8276             d->layout->invalidate();
8277         break;
8278     }
8279
8280     case QEvent::PaletteChange:
8281         update();
8282         break;
8283
8284     case QEvent::ThemeChange:
8285         if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8286             && qApp && !QApplication::closingDown()) {
8287             if (testAttribute(Qt::WA_WState_Polished))
8288                 QApplication::style()->unpolish(this);
8289             if (testAttribute(Qt::WA_WState_Polished))
8290                 QApplication::style()->polish(this);
8291             QEvent styleChangedEvent(QEvent::StyleChange);
8292             QCoreApplication::sendEvent(this, &styleChangedEvent);
8293             if (isVisible())
8294                 update();
8295         }
8296         break;
8297
8298 #ifdef Q_WS_MAC
8299     case QEvent::MacSizeChange:
8300         updateGeometry();
8301         break;
8302     case QEvent::ToolTipChange:
8303     case QEvent::MouseTrackingChange:
8304         qt_mac_update_mouseTracking(this);
8305         break;
8306 #endif
8307
8308     default:
8309         break;
8310     }
8311 }
8312
8313 /*!
8314     This event handler, for event \a event, can be reimplemented in a
8315     subclass to receive mouse move events for the widget.
8316
8317     If mouse tracking is switched off, mouse move events only occur if
8318     a mouse button is pressed while the mouse is being moved. If mouse
8319     tracking is switched on, mouse move events occur even if no mouse
8320     button is pressed.
8321
8322     QMouseEvent::pos() reports the position of the mouse cursor,
8323     relative to this widget. For press and release events, the
8324     position is usually the same as the position of the last mouse
8325     move event, but it might be different if the user's hand shakes.
8326     This is a feature of the underlying window system, not Qt.
8327
8328     If you want to show a tooltip immediately, while the mouse is
8329     moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8330     and show them as a tooltip), you must first enable mouse tracking
8331     as described above. Then, to ensure that the tooltip is updated
8332     immediately, you must call QToolTip::showText() instead of
8333     setToolTip() in your implementation of mouseMoveEvent().
8334
8335     \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8336     mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8337 */
8338
8339 void QWidget::mouseMoveEvent(QMouseEvent *event)
8340 {
8341     event->ignore();
8342 }
8343
8344 /*!
8345     This event handler, for event \a event, can be reimplemented in a
8346     subclass to receive mouse press events for the widget.
8347
8348     If you create new widgets in the mousePressEvent() the
8349     mouseReleaseEvent() may not end up where you expect, depending on
8350     the underlying window system (or X11 window manager), the widgets'
8351     location and maybe more.
8352
8353     The default implementation implements the closing of popup widgets
8354     when you click outside the window. For other widget types it does
8355     nothing.
8356
8357     \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8358     mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8359 */
8360
8361 void QWidget::mousePressEvent(QMouseEvent *event)
8362 {
8363     event->ignore();
8364     if ((windowType() == Qt::Popup)) {
8365         event->accept();
8366         QWidget* w;
8367         while ((w = QApplication::activePopupWidget()) && w != this){
8368             w->close();
8369             if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8370                 w->hide(); // hide at least
8371         }
8372         if (!rect().contains(event->pos())){
8373             close();
8374         }
8375     }
8376 }
8377
8378 /*!
8379     This event handler, for event \a event, can be reimplemented in a
8380     subclass to receive mouse release events for the widget.
8381
8382     \sa mousePressEvent(), mouseDoubleClickEvent(),
8383     mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8384 */
8385
8386 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8387 {
8388     event->ignore();
8389 }
8390
8391 /*!
8392     This event handler, for event \a event, can be reimplemented in a
8393     subclass to receive mouse double click events for the widget.
8394
8395     The default implementation generates a normal mouse press event.
8396
8397     \note The widget will also receive mouse press and mouse release
8398     events in addition to the double click event. It is up to the
8399     developer to ensure that the application interprets these events
8400     correctly.
8401
8402     \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8403     event(), QMouseEvent
8404 */
8405
8406 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8407 {
8408 }
8409
8410 #ifndef QT_NO_WHEELEVENT
8411 /*!
8412     This event handler, for event \a event, can be reimplemented in a
8413     subclass to receive wheel events for the widget.
8414
8415     If you reimplement this handler, it is very important that you
8416     \link QWheelEvent ignore()\endlink the event if you do not handle
8417     it, so that the widget's parent can interpret it.
8418
8419     The default implementation ignores the event.
8420
8421     \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8422     QWheelEvent
8423 */
8424
8425 void QWidget::wheelEvent(QWheelEvent *event)
8426 {
8427     event->ignore();
8428 }
8429 #endif // QT_NO_WHEELEVENT
8430
8431 #ifndef QT_NO_TABLETEVENT
8432 /*!
8433     This event handler, for event \a event, can be reimplemented in a
8434     subclass to receive tablet events for the widget.
8435
8436     If you reimplement this handler, it is very important that you
8437     \link QTabletEvent ignore()\endlink the event if you do not handle
8438     it, so that the widget's parent can interpret it.
8439
8440     The default implementation ignores the event.
8441
8442     \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8443     QTabletEvent
8444 */
8445
8446 void QWidget::tabletEvent(QTabletEvent *event)
8447 {
8448     event->ignore();
8449 }
8450 #endif // QT_NO_TABLETEVENT
8451
8452 /*!
8453     This event handler, for event \a event, can be reimplemented in a
8454     subclass to receive key press events for the widget.
8455
8456     A widget must call setFocusPolicy() to accept focus initially and
8457     have focus in order to receive a key press event.
8458
8459     If you reimplement this handler, it is very important that you
8460     call the base class implementation if you do not act upon the key.
8461
8462     The default implementation closes popup widgets if the user
8463     presses Esc. Otherwise the event is ignored, so that the widget's
8464     parent can interpret it.
8465
8466     Note that QKeyEvent starts with isAccepted() == true, so you do not
8467     need to call QKeyEvent::accept() - just do not call the base class
8468     implementation if you act upon the key.
8469
8470     \sa keyReleaseEvent(), setFocusPolicy(),
8471     focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8472 */
8473
8474 void QWidget::keyPressEvent(QKeyEvent *event)
8475 {
8476     if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8477         event->accept();
8478         close();
8479     } else {
8480         event->ignore();
8481     }
8482 }
8483
8484 /*!
8485     This event handler, for event \a event, can be reimplemented in a
8486     subclass to receive key release events for the widget.
8487
8488     A widget must \link setFocusPolicy() accept focus\endlink
8489     initially and \link hasFocus() have focus\endlink in order to
8490     receive a key release event.
8491
8492     If you reimplement this handler, it is very important that you
8493     call the base class implementation if you do not act upon the key.
8494
8495     The default implementation ignores the event, so that the widget's
8496     parent can interpret it.
8497
8498     Note that QKeyEvent starts with isAccepted() == true, so you do not
8499     need to call QKeyEvent::accept() - just do not call the base class
8500     implementation if you act upon the key.
8501
8502     \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8503     focusInEvent(), focusOutEvent(), event(), QKeyEvent
8504 */
8505
8506 void QWidget::keyReleaseEvent(QKeyEvent *event)
8507 {
8508     event->ignore();
8509 }
8510
8511 /*!
8512     \fn void QWidget::focusInEvent(QFocusEvent *event)
8513
8514     This event handler can be reimplemented in a subclass to receive
8515     keyboard focus events (focus received) for the widget. The event
8516     is passed in the \a event parameter
8517
8518     A widget normally must setFocusPolicy() to something other than
8519     Qt::NoFocus in order to receive focus events. (Note that the
8520     application programmer can call setFocus() on any widget, even
8521     those that do not normally accept focus.)
8522
8523     The default implementation updates the widget (except for windows
8524     that do not specify a focusPolicy()).
8525
8526     \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8527     keyReleaseEvent(), event(), QFocusEvent
8528 */
8529
8530 void QWidget::focusInEvent(QFocusEvent *)
8531 {
8532     if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8533         update();
8534     }
8535 }
8536
8537 /*!
8538     \fn void QWidget::focusOutEvent(QFocusEvent *event)
8539
8540     This event handler can be reimplemented in a subclass to receive
8541     keyboard focus events (focus lost) for the widget. The events is
8542     passed in the \a event parameter.
8543
8544     A widget normally must setFocusPolicy() to something other than
8545     Qt::NoFocus in order to receive focus events. (Note that the
8546     application programmer can call setFocus() on any widget, even
8547     those that do not normally accept focus.)
8548
8549     The default implementation updates the widget (except for windows
8550     that do not specify a focusPolicy()).
8551
8552     \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8553     keyReleaseEvent(), event(), QFocusEvent
8554 */
8555
8556 void QWidget::focusOutEvent(QFocusEvent *)
8557 {
8558     if (focusPolicy() != Qt::NoFocus || !isWindow())
8559         update();
8560 }
8561
8562 /*!
8563     \fn void QWidget::enterEvent(QEvent *event)
8564
8565     This event handler can be reimplemented in a subclass to receive
8566     widget enter events which are passed in the \a event parameter.
8567
8568     An event is sent to the widget when the mouse cursor enters the
8569     widget.
8570
8571     \sa leaveEvent(), mouseMoveEvent(), event()
8572 */
8573
8574 void QWidget::enterEvent(QEvent *)
8575 {
8576 }
8577
8578 /*!
8579     \fn void QWidget::leaveEvent(QEvent *event)
8580
8581     This event handler can be reimplemented in a subclass to receive
8582     widget leave events which are passed in the \a event parameter.
8583
8584     A leave event is sent to the widget when the mouse cursor leaves
8585     the widget.
8586
8587     \sa enterEvent(), mouseMoveEvent(), event()
8588 */
8589
8590 void QWidget::leaveEvent(QEvent *)
8591 {
8592 }
8593
8594 /*!
8595     \fn void QWidget::paintEvent(QPaintEvent *event)
8596
8597     This event handler can be reimplemented in a subclass to receive paint
8598     events passed in \a event.
8599
8600     A paint event is a request to repaint all or part of a widget. It can
8601     happen for one of the following reasons:
8602
8603     \list
8604         \li repaint() or update() was invoked,
8605         \li the widget was obscured and has now been uncovered, or
8606         \li many other reasons.
8607     \endlist
8608
8609     Many widgets can simply repaint their entire surface when asked to, but
8610     some slow widgets need to optimize by painting only the requested region:
8611     QPaintEvent::region(). This speed optimization does not change the result,
8612     as painting is clipped to that region during event processing. QListView
8613     and QTableView do this, for example.
8614
8615     Qt also tries to speed up painting by merging multiple paint events into
8616     one. When update() is called several times or the window system sends
8617     several paint events, Qt merges these events into one event with a larger
8618     region (see QRegion::united()). The repaint() function does not permit this
8619     optimization, so we suggest using update() whenever possible.
8620
8621     When the paint event occurs, the update region has normally been erased, so
8622     you are painting on the widget's background.
8623
8624     The background can be set using setBackgroundRole() and setPalette().
8625
8626     Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8627     is no need to write double-buffering code in paintEvent() to avoid flicker.
8628
8629     \b{Note for the X11 platform}: It is possible to toggle global double
8630     buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8631
8632     \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8633
8634     \note Generally, you should refrain from calling update() or repaint()
8635     \b{inside} a paintEvent(). For example, calling update() or repaint() on
8636     children inside a paintevent() results in undefined behavior; the child may
8637     or may not get a paint event.
8638
8639     \warning If you are using a custom paint engine without Qt's backingstore,
8640     Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8641     never be called; the backingstore will be used instead.
8642
8643     \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8644     {Analog Clock Example}
8645 */
8646
8647 void QWidget::paintEvent(QPaintEvent *)
8648 {
8649 }
8650
8651
8652 /*!
8653     \fn void QWidget::moveEvent(QMoveEvent *event)
8654
8655     This event handler can be reimplemented in a subclass to receive
8656     widget move events which are passed in the \a event parameter.
8657     When the widget receives this event, it is already at the new
8658     position.
8659
8660     The old position is accessible through QMoveEvent::oldPos().
8661
8662     \sa resizeEvent(), event(), move(), QMoveEvent
8663 */
8664
8665 void QWidget::moveEvent(QMoveEvent *)
8666 {
8667 }
8668
8669
8670 /*!
8671     This event handler can be reimplemented in a subclass to receive
8672     widget resize events which are passed in the \a event parameter.
8673     When resizeEvent() is called, the widget already has its new
8674     geometry. The old size is accessible through
8675     QResizeEvent::oldSize().
8676
8677     The widget will be erased and receive a paint event immediately
8678     after processing the resize event. No drawing need be (or should
8679     be) done inside this handler.
8680
8681
8682     \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8683         {Scribble Example}
8684 */
8685
8686 void QWidget::resizeEvent(QResizeEvent * /* event */)
8687 {
8688 }
8689
8690 #ifndef QT_NO_ACTION
8691 /*!
8692     \fn void QWidget::actionEvent(QActionEvent *event)
8693
8694     This event handler is called with the given \a event whenever the
8695     widget's actions are changed.
8696
8697     \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8698 */
8699 void QWidget::actionEvent(QActionEvent *)
8700 {
8701
8702 }
8703 #endif
8704
8705 /*!
8706     This event handler is called with the given \a event when Qt receives a window
8707     close request for a top-level widget from the window system.
8708
8709     By default, the event is accepted and the widget is closed. You can reimplement
8710     this function to change the way the widget responds to window close requests.
8711     For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8712     on all events.
8713
8714     Main window applications typically use reimplementations of this function to check
8715     whether the user's work has been saved and ask for permission before closing.
8716     For example, the \l{Application Example} uses a helper function to determine whether
8717     or not to close the window:
8718
8719     \snippet mainwindows/application/mainwindow.cpp 3
8720     \snippet mainwindows/application/mainwindow.cpp 4
8721
8722     \sa event(), hide(), close(), QCloseEvent, {Application Example}
8723 */
8724
8725 void QWidget::closeEvent(QCloseEvent *event)
8726 {
8727     event->accept();
8728 }
8729
8730 #ifndef QT_NO_CONTEXTMENU
8731 /*!
8732     This event handler, for event \a event, can be reimplemented in a
8733     subclass to receive widget context menu events.
8734
8735     The handler is called when the widget's \l contextMenuPolicy is
8736     Qt::DefaultContextMenu.
8737
8738     The default implementation ignores the context event.
8739     See the \l QContextMenuEvent documentation for more details.
8740
8741     \sa event(), QContextMenuEvent customContextMenuRequested()
8742 */
8743
8744 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8745 {
8746     event->ignore();
8747 }
8748 #endif // QT_NO_CONTEXTMENU
8749
8750
8751 /*!
8752     This event handler, for event \a event, can be reimplemented in a
8753     subclass to receive Input Method composition events. This handler
8754     is called when the state of the input method changes.
8755
8756     Note that when creating custom text editing widgets, the
8757     Qt::WA_InputMethodEnabled window attribute must be set explicitly
8758     (using the setAttribute() function) in order to receive input
8759     method events.
8760
8761     The default implementation calls event->ignore(), which rejects the
8762     Input Method event. See the \l QInputMethodEvent documentation for more
8763     details.
8764
8765     \sa event(), QInputMethodEvent
8766 */
8767 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8768 {
8769     event->ignore();
8770 }
8771
8772 /*!
8773     This method is only relevant for input widgets. It is used by the
8774     input method to query a set of properties of the widget to be
8775     able to support complex input method operations as support for
8776     surrounding text and reconversions.
8777
8778     \a query specifies which property is queried.
8779
8780     \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8781 */
8782 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8783 {
8784     switch(query) {
8785     case Qt::ImCursorRectangle:
8786         return QRect(width()/2, 0, 1, height());
8787     case Qt::ImFont:
8788         return font();
8789     case Qt::ImAnchorPosition:
8790         // Fallback.
8791         return inputMethodQuery(Qt::ImCursorPosition);
8792     case Qt::ImHints:
8793         return (int)inputMethodHints();
8794     default:
8795         return QVariant();
8796     }
8797 }
8798
8799 /*!
8800     \property QWidget::inputMethodHints
8801     \brief What input method specific hints the widget has.
8802
8803     This is only relevant for input widgets. It is used by
8804     the input method to retrieve hints as to how the input method
8805     should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8806     is set, the input method may change its visual components to reflect
8807     that only numbers can be entered.
8808
8809     \note The flags are only hints, so the particular input method
8810           implementation is free to ignore them. If you want to be
8811           sure that a certain type of characters are entered,
8812           you should also set a QValidator on the widget.
8813
8814     The default value is Qt::ImhNone.
8815
8816     \since 4.6
8817
8818     \sa inputMethodQuery()
8819 */
8820 Qt::InputMethodHints QWidget::inputMethodHints() const
8821 {
8822 #ifndef QT_NO_IM
8823     const QWidgetPrivate *priv = d_func();
8824     while (priv->inheritsInputMethodHints) {
8825         priv = priv->q_func()->parentWidget()->d_func();
8826         Q_ASSERT(priv);
8827     }
8828     return priv->imHints;
8829 #else //QT_NO_IM
8830     return 0;
8831 #endif //QT_NO_IM
8832 }
8833
8834 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8835 {
8836 #ifndef QT_NO_IM
8837     Q_D(QWidget);
8838     d->imHints = hints;
8839     qApp->inputMethod()->update(Qt::ImHints);
8840 #endif //QT_NO_IM
8841 }
8842
8843
8844 #ifndef QT_NO_DRAGANDDROP
8845
8846 /*!
8847     \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8848
8849     This event handler is called when a drag is in progress and the
8850     mouse enters this widget. The event is passed in the \a event parameter.
8851
8852     If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8853     move events}.
8854
8855     See the \link dnd.html Drag-and-drop documentation\endlink for an
8856     overview of how to provide drag-and-drop in your application.
8857
8858     \sa QDrag, QDragEnterEvent
8859 */
8860 void QWidget::dragEnterEvent(QDragEnterEvent *)
8861 {
8862 }
8863
8864 /*!
8865     \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8866
8867     This event handler is called if a drag is in progress, and when
8868     any of the following conditions occur: the cursor enters this widget,
8869     the cursor moves within this widget, or a modifier key is pressed on
8870     the keyboard while this widget has the focus. The event is passed
8871     in the \a event parameter.
8872
8873     See the \link dnd.html Drag-and-drop documentation\endlink for an
8874     overview of how to provide drag-and-drop in your application.
8875
8876     \sa QDrag, QDragMoveEvent
8877 */
8878 void QWidget::dragMoveEvent(QDragMoveEvent *)
8879 {
8880 }
8881
8882 /*!
8883     \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8884
8885     This event handler is called when a drag is in progress and the
8886     mouse leaves this widget. The event is passed in the \a event
8887     parameter.
8888
8889     See the \link dnd.html Drag-and-drop documentation\endlink for an
8890     overview of how to provide drag-and-drop in your application.
8891
8892     \sa QDrag, QDragLeaveEvent
8893 */
8894 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8895 {
8896 }
8897
8898 /*!
8899     \fn void QWidget::dropEvent(QDropEvent *event)
8900
8901     This event handler is called when the drag is dropped on this
8902     widget. The event is passed in the \a event parameter.
8903
8904     See the \link dnd.html Drag-and-drop documentation\endlink for an
8905     overview of how to provide drag-and-drop in your application.
8906
8907     \sa QDrag, QDropEvent
8908 */
8909 void QWidget::dropEvent(QDropEvent *)
8910 {
8911 }
8912
8913 #endif // QT_NO_DRAGANDDROP
8914
8915 /*!
8916     \fn void QWidget::showEvent(QShowEvent *event)
8917
8918     This event handler can be reimplemented in a subclass to receive
8919     widget show events which are passed in the \a event parameter.
8920
8921     Non-spontaneous show events are sent to widgets immediately
8922     before they are shown. The spontaneous show events of windows are
8923     delivered afterwards.
8924
8925     Note: A widget receives spontaneous show and hide events when its
8926     mapping status is changed by the window system, e.g. a spontaneous
8927     hide event when the user minimizes the window, and a spontaneous
8928     show event when the window is restored again. After receiving a
8929     spontaneous hide event, a widget is still considered visible in
8930     the sense of isVisible().
8931
8932     \sa visible, event(), QShowEvent
8933 */
8934 void QWidget::showEvent(QShowEvent *)
8935 {
8936 }
8937
8938 /*!
8939     \fn void QWidget::hideEvent(QHideEvent *event)
8940
8941     This event handler can be reimplemented in a subclass to receive
8942     widget hide events. The event is passed in the \a event parameter.
8943
8944     Hide events are sent to widgets immediately after they have been
8945     hidden.
8946
8947     Note: A widget receives spontaneous show and hide events when its
8948     mapping status is changed by the window system, e.g. a spontaneous
8949     hide event when the user minimizes the window, and a spontaneous
8950     show event when the window is restored again. After receiving a
8951     spontaneous hide event, a widget is still considered visible in
8952     the sense of isVisible().
8953
8954     \sa visible, event(), QHideEvent
8955 */
8956 void QWidget::hideEvent(QHideEvent *)
8957 {
8958 }
8959
8960 /*!
8961     This special event handler can be reimplemented in a subclass to
8962     receive native platform events identified by \a eventType
8963     which are passed in the \a message parameter.
8964
8965     In your reimplementation of this function, if you want to stop the
8966     event being handled by Qt, return true and set \a result.
8967     If you return false, this native event is passed back to Qt,
8968     which translates the event into a Qt event and sends it to the widget.
8969
8970     \note Events are only delivered to this event handler if the widget is
8971     has a native Window handle.
8972
8973     \note This function superseedes the event filter functions
8974     x11Event(), winEvent() and macEvent() of Qt 4.
8975
8976     \table
8977     \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
8978     \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
8979     \endtable
8980 */
8981
8982 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
8983 {
8984     Q_UNUSED(eventType);
8985     Q_UNUSED(message);
8986     Q_UNUSED(result);
8987     return false;
8988 }
8989
8990 /*!
8991     Ensures that the widget has been polished by QStyle (i.e., has a
8992     proper font and palette).
8993
8994     QWidget calls this function after it has been fully constructed
8995     but before it is shown the very first time. You can call this
8996     function if you want to ensure that the widget is polished before
8997     doing an operation, e.g., the correct font size might be needed in
8998     the widget's sizeHint() reimplementation. Note that this function
8999     \e is called from the default implementation of sizeHint().
9000
9001     Polishing is useful for final initialization that must happen after
9002     all constructors (from base classes as well as from subclasses)
9003     have been called.
9004
9005     If you need to change some settings when a widget is polished,
9006     reimplement event() and handle the QEvent::Polish event type.
9007
9008     \b{Note:} The function is declared const so that it can be called from
9009     other const functions (e.g., sizeHint()).
9010
9011     \sa event()
9012 */
9013 void QWidget::ensurePolished() const
9014 {
9015     Q_D(const QWidget);
9016
9017     const QMetaObject *m = metaObject();
9018     if (m == d->polished)
9019         return;
9020     d->polished = m;
9021
9022     QEvent e(QEvent::Polish);
9023     QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9024
9025     // polish children after 'this'
9026     QList<QObject*> children = d->children;
9027     for (int i = 0; i < children.size(); ++i) {
9028         QObject *o = children.at(i);
9029         if(!o->isWidgetType())
9030             continue;
9031         if (QWidget *w = qobject_cast<QWidget *>(o))
9032             w->ensurePolished();
9033     }
9034
9035     if (d->parent && d->sendChildEvents) {
9036         QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9037         QCoreApplication::sendEvent(d->parent, &e);
9038     }
9039     if (d->extra && d->extra->topextra && d->extra->topextra->window
9040         && d->extra->topextra->window->objectName().isEmpty()) {
9041         QString on = objectName();
9042         if (on.isEmpty()) {
9043             on = QString::fromUtf8(metaObject()->className());
9044             on += QStringLiteral("Class");
9045         }
9046         on += QStringLiteral("Window");
9047         d->extra->topextra->window->setObjectName(on);
9048     }
9049 }
9050
9051 /*!
9052     Returns the mask currently set on a widget. If no mask is set the
9053     return value will be an empty region.
9054
9055     \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9056 */
9057 QRegion QWidget::mask() const
9058 {
9059     Q_D(const QWidget);
9060     return d->extra ? d->extra->mask : QRegion();
9061 }
9062
9063 /*!
9064     Returns the layout manager that is installed on this widget, or 0
9065     if no layout manager is installed.
9066
9067     The layout manager sets the geometry of the widget's children
9068     that have been added to the layout.
9069
9070     \sa setLayout(), sizePolicy(), {Layout Management}
9071 */
9072 QLayout *QWidget::layout() const
9073 {
9074     return d_func()->layout;
9075 }
9076
9077
9078 /*!
9079     \fn void QWidget::setLayout(QLayout *layout)
9080
9081     Sets the layout manager for this widget to \a layout.
9082
9083     If there already is a layout manager installed on this widget,
9084     QWidget won't let you install another. You must first delete the
9085     existing layout manager (returned by layout()) before you can
9086     call setLayout() with the new layout.
9087
9088     If \a layout is the layout manger on a different widget, setLayout()
9089     will reparent the layout and make it the layout manager for this widget.
9090
9091     Example:
9092
9093     \snippet examples/uitools/textfinder/textfinder.cpp 3b
9094
9095     An alternative to calling this function is to pass this widget to
9096     the layout's constructor.
9097
9098     The QWidget will take ownership of \a layout.
9099
9100     \sa layout(), {Layout Management}
9101 */
9102
9103 void QWidget::setLayout(QLayout *l)
9104 {
9105     if (!l) {
9106         qWarning("QWidget::setLayout: Cannot set layout to 0");
9107         return;
9108     }
9109     if (layout()) {
9110         if (layout() != l)
9111             qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9112                      " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9113                      objectName().toLocal8Bit().data());
9114         return;
9115     }
9116
9117     QObject *oldParent = l->parent();
9118     if (oldParent && oldParent != this) {
9119         if (oldParent->isWidgetType()) {
9120             // Steal the layout off a widget parent. Takes effect when
9121             // morphing laid-out container widgets in Designer.
9122             QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9123             oldParentWidget->takeLayout();
9124         } else {
9125             qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9126                      l->objectName().toLocal8Bit().data(), metaObject()->className(),
9127                      objectName().toLocal8Bit().data());
9128             return;
9129         }
9130     }
9131
9132     Q_D(QWidget);
9133     l->d_func()->topLevel = true;
9134     d->layout = l;
9135     if (oldParent != this) {
9136         l->setParent(this);
9137         l->d_func()->reparentChildWidgets(this);
9138         l->invalidate();
9139     }
9140
9141     if (isWindow() && d->maybeTopData())
9142         d->topData()->sizeAdjusted = false;
9143 }
9144
9145 /*!
9146     \fn QLayout *QWidget::takeLayout()
9147
9148     Remove the layout from the widget.
9149     \since 4.5
9150 */
9151
9152 QLayout *QWidget::takeLayout()
9153 {
9154     Q_D(QWidget);
9155     QLayout *l =  layout();
9156     if (!l)
9157         return 0;
9158     d->layout = 0;
9159     l->setParent(0);
9160     return l;
9161 }
9162
9163 /*!
9164     \property QWidget::sizePolicy
9165     \brief the default layout behavior of the widget
9166
9167     If there is a QLayout that manages this widget's children, the
9168     size policy specified by that layout is used. If there is no such
9169     QLayout, the result of this function is used.
9170
9171     The default policy is Preferred/Preferred, which means that the
9172     widget can be freely resized, but prefers to be the size
9173     sizeHint() returns. Button-like widgets set the size policy to
9174     specify that they may stretch horizontally, but are fixed
9175     vertically. The same applies to lineedit controls (such as
9176     QLineEdit, QSpinBox or an editable QComboBox) and other
9177     horizontally orientated widgets (such as QProgressBar).
9178     QToolButton's are normally square, so they allow growth in both
9179     directions. Widgets that support different directions (such as
9180     QSlider, QScrollBar or QHeader) specify stretching in the
9181     respective direction only. Widgets that can provide scroll bars
9182     (usually subclasses of QScrollArea) tend to specify that they can
9183     use additional space, and that they can make do with less than
9184     sizeHint().
9185
9186     \sa sizeHint() QLayout QSizePolicy updateGeometry()
9187 */
9188 QSizePolicy QWidget::sizePolicy() const
9189 {
9190     Q_D(const QWidget);
9191     return d->size_policy;
9192 }
9193
9194 void QWidget::setSizePolicy(QSizePolicy policy)
9195 {
9196     Q_D(QWidget);
9197     setAttribute(Qt::WA_WState_OwnSizePolicy);
9198     if (policy == d->size_policy)
9199         return;
9200     d->size_policy = policy;
9201
9202 #ifndef QT_NO_GRAPHICSVIEW
9203     if (QWExtra *extra = d->extra) {
9204         if (extra->proxyWidget)
9205             extra->proxyWidget->setSizePolicy(policy);
9206     }
9207 #endif
9208
9209     updateGeometry();
9210
9211     if (isWindow() && d->maybeTopData())
9212         d->topData()->sizeAdjusted = false;
9213 }
9214
9215 /*!
9216     \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9217     \overload
9218
9219     Sets the size policy of the widget to \a horizontal and \a
9220     vertical, with standard stretch and no height-for-width.
9221
9222     \sa QSizePolicy::QSizePolicy()
9223 */
9224
9225 /*!
9226     Returns the preferred height for this widget, given the width \a w.
9227
9228     If this widget has a layout, the default implementation returns
9229     the layout's preferred height.  if there is no layout, the default
9230     implementation returns -1 indicating that the preferred height
9231     does not depend on the width.
9232 */
9233
9234 int QWidget::heightForWidth(int w) const
9235 {
9236     if (layout() && layout()->hasHeightForWidth())
9237         return layout()->totalHeightForWidth(w);
9238     return -1;
9239 }
9240
9241
9242 /*!
9243     \Since 5.0
9244
9245     Returns true if the widget's preferred height depends on its width; otherwise returns false.
9246 */ 
9247 bool QWidget::hasHeightForWidth() const
9248 {
9249     Q_D(const QWidget);
9250     return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9251 }
9252
9253 /*!
9254     \fn QWidget *QWidget::childAt(int x, int y) const
9255
9256     Returns the visible child widget at the position (\a{x}, \a{y})
9257     in the widget's coordinate system. If there is no visible child
9258     widget at the specified position, the function returns 0.
9259 */
9260
9261 /*!
9262     \overload
9263
9264     Returns the visible child widget at point \a p in the widget's own
9265     coordinate system.
9266 */
9267
9268 QWidget *QWidget::childAt(const QPoint &p) const
9269 {
9270     return d_func()->childAt_helper(p, false);
9271 }
9272
9273 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9274 {
9275     if (children.isEmpty())
9276         return 0;
9277
9278 #ifdef Q_WS_MAC
9279     Q_Q(const QWidget);
9280     // Unified tool bars on the Mac require special handling since they live outside
9281     // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9282     bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9283                         && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9284     if (includeFrame)
9285         return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9286 #endif
9287
9288     if (!pointInsideRectAndMask(p))
9289         return 0;
9290     return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9291 }
9292
9293 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9294 {
9295 #ifndef Q_WS_MAC
9296     Q_UNUSED(includeFrame);
9297 #endif
9298     for (int i = children.size() - 1; i >= 0; --i) {
9299         QWidget *child = qobject_cast<QWidget *>(children.at(i));
9300         if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9301             || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9302             continue;
9303         }
9304
9305         // Map the point 'p' from parent coordinates to child coordinates.
9306         QPoint childPoint = p;
9307 #ifdef Q_WS_MAC
9308         // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9309         // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9310         // QWidget::mapFromParent won't do the trick.
9311         if (includeFrame && qobject_cast<QToolBar *>(child))
9312             childPoint = qt_mac_nativeMapFromParent(child, p);
9313         else
9314 #endif
9315         childPoint -= child->data->crect.topLeft();
9316
9317         // Check if the point hits the child.
9318         if (!child->d_func()->pointInsideRectAndMask(childPoint))
9319             continue;
9320
9321         // Do the same for the child's descendants.
9322         if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9323             return w;
9324
9325         // We have found our target; namely the child at position 'p'.
9326         return child;
9327     }
9328     return 0;
9329 }
9330
9331 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9332 {
9333     Q_Q(QWidget);
9334     if (widgetItem)
9335         widgetItem->invalidateSizeCache();
9336     QWidget *parent;
9337     if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9338         if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9339             if (parent->d_func()->layout)
9340                 parent->d_func()->layout->invalidate();
9341             else if (parent->isVisible())
9342                 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9343         }
9344     }
9345 }
9346
9347 /*!
9348     Notifies the layout system that this widget has changed and may
9349     need to change geometry.
9350
9351     Call this function if the sizeHint() or sizePolicy() have changed.
9352
9353     For explicitly hidden widgets, updateGeometry() is a no-op. The
9354     layout system will be notified as soon as the widget is shown.
9355 */
9356
9357 void QWidget::updateGeometry()
9358 {
9359     Q_D(QWidget);
9360     d->updateGeometry_helper(false);
9361 }
9362
9363 /*! \property QWidget::windowFlags
9364
9365     Window flags are a combination of a type (e.g. Qt::Dialog) and
9366     zero or more hints to the window system (e.g.
9367     Qt::FramelessWindowHint).
9368
9369     If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9370     window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9371     0) on the desktop. If the widget is a window and becomes a
9372     Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9373     relative to its parent widget.
9374
9375     \note This function calls setParent() when changing the flags for
9376     a window, causing the widget to be hidden. You must call show() to make
9377     the widget visible again..
9378
9379     \sa windowType(), {Window Flags Example}
9380 */
9381 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9382 {
9383     if (data->window_flags == flags)
9384         return;
9385
9386     Q_D(QWidget);
9387
9388     if ((data->window_flags | flags) & Qt::Window) {
9389         // the old type was a window and/or the new type is a window
9390         QPoint oldPos = pos();
9391         bool visible = isVisible();
9392         setParent(parentWidget(), flags);
9393
9394         // if both types are windows or neither of them are, we restore
9395         // the old position
9396         if (!((data->window_flags ^ flags) & Qt::Window)
9397             && (visible || testAttribute(Qt::WA_Moved))) {
9398             move(oldPos);
9399         }
9400         // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9401         d->adjustQuitOnCloseAttribute();
9402     } else {
9403         data->window_flags = flags;
9404     }
9405 }
9406
9407 /*!
9408     Sets the window flags for the widget to \a flags,
9409     \e without telling the window system.
9410
9411     \warning Do not call this function unless you really know what
9412     you're doing.
9413
9414     \sa setWindowFlags()
9415 */
9416 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9417 {
9418     data->window_flags = flags;
9419 }
9420
9421 /*!
9422     \fn Qt::WindowType QWidget::windowType() const
9423
9424     Returns the window type of this widget. This is identical to
9425     windowFlags() & Qt::WindowType_Mask.
9426
9427     \sa windowFlags
9428 */
9429
9430 /*!
9431     Sets the parent of the widget to \a parent, and resets the window
9432     flags. The widget is moved to position (0, 0) in its new parent.
9433
9434     If the new parent widget is in a different window, the
9435     reparented widget and its children are appended to the end of the
9436     \l{setFocusPolicy()}{tab chain} of the new parent
9437     widget, in the same internal order as before. If one of the moved
9438     widgets had keyboard focus, setParent() calls clearFocus() for that
9439     widget.
9440
9441     If the new parent widget is in the same window as the
9442     old parent, setting the parent doesn't change the tab order or
9443     keyboard focus.
9444
9445     If the "new" parent widget is the old parent widget, this function
9446     does nothing.
9447
9448     \note The widget becomes invisible as part of changing its parent,
9449     even if it was previously visible. You must call show() to make the
9450     widget visible again.
9451
9452     \warning It is very unlikely that you will ever need this
9453     function. If you have a widget that changes its content
9454     dynamically, it is far easier to use \l QStackedWidget.
9455
9456     \sa setWindowFlags()
9457 */
9458 void QWidget::setParent(QWidget *parent)
9459 {
9460     if (parent == parentWidget())
9461         return;
9462     setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9463 }
9464
9465 /*!
9466     \overload
9467
9468     This function also takes widget flags, \a f as an argument.
9469 */
9470
9471 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9472 {
9473     Q_D(QWidget);
9474     d->inSetParent = true;
9475     bool resized = testAttribute(Qt::WA_Resized);
9476     bool wasCreated = testAttribute(Qt::WA_WState_Created);
9477     QWidget *oldtlw = window();
9478
9479     QWidget *desktopWidget = 0;
9480     if (parent && parent->windowType() == Qt::Desktop)
9481         desktopWidget = parent;
9482     bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9483
9484 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC)
9485     if (newParent && parent && !desktopWidget) {
9486         if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9487 #ifdef Q_WS_MAC
9488             // On Mac, toolbars inside the unified title bar will never overlap with
9489             // siblings in the content view. So we skip enforce native siblings in that case
9490             && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9491 #endif // Q_WS_MAC
9492         )
9493             parent->d_func()->enforceNativeChildren();
9494         else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9495             setAttribute(Qt::WA_NativeWindow);
9496     }
9497 #endif
9498
9499     if (wasCreated) {
9500         if (!testAttribute(Qt::WA_WState_Hidden)) {
9501             hide();
9502             setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9503         }
9504         if (newParent) {
9505             QEvent e(QEvent::ParentAboutToChange);
9506             QApplication::sendEvent(this, &e);
9507         }
9508     }
9509     if (newParent && isAncestorOf(focusWidget()))
9510         focusWidget()->clearFocus();
9511
9512     QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9513     QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9514
9515     d->setParent_sys(parent, f);
9516
9517     QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9518     QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9519     if (oldBsTracker && oldBsTracker != bsTracker)
9520         oldBsTracker->unregisterWidgetSubtree(this);
9521
9522     if (desktopWidget)
9523         parent = 0;
9524
9525     if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9526         if (newParent)
9527             oldBs->removeDirtyWidget(this);
9528         // Move the widget and all its static children from
9529         // the old backing store to the new one.
9530         oldBs->moveStaticWidgets(this);
9531     }
9532
9533     if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9534         create();
9535
9536     d->reparentFocusWidgets(oldtlw);
9537     setAttribute(Qt::WA_Resized, resized);
9538     if (!testAttribute(Qt::WA_StyleSheet)
9539         && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9540         d->resolveFont();
9541         d->resolvePalette();
9542     }
9543     d->resolveLayoutDirection();
9544     d->resolveLocale();
9545
9546     // Note: GL widgets under WGL or EGL will always need a ParentChange
9547     // event to handle recreation/rebinding of the GL context, hence the
9548     // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9549     // platforms).
9550     if (newParent
9551 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9552         || (f & Qt::MSWindowsOwnDC)
9553 #endif
9554         ) {
9555         // propagate enabled updates enabled state to non-windows
9556         if (!isWindow()) {
9557             if (!testAttribute(Qt::WA_ForceDisabled))
9558                 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9559             if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9560                 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9561         }
9562         d->inheritStyle();
9563
9564         // send and post remaining QObject events
9565         if (parent && d->sendChildEvents) {
9566             QChildEvent e(QEvent::ChildAdded, this);
9567             QApplication::sendEvent(parent, &e);
9568         }
9569
9570 //### already hidden above ---> must probably do something smart on the mac
9571 // #ifdef Q_WS_MAC
9572 //             extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9573 //             if(!qt_mac_is_macdrawer(q)) //special case
9574 //                 q->setAttribute(Qt::WA_WState_Hidden);
9575 // #else
9576 //             q->setAttribute(Qt::WA_WState_Hidden);
9577 //#endif
9578
9579         if (parent && d->sendChildEvents && d->polished) {
9580             QChildEvent e(QEvent::ChildPolished, this);
9581             QCoreApplication::sendEvent(parent, &e);
9582         }
9583
9584         QEvent e(QEvent::ParentChange);
9585         QApplication::sendEvent(this, &e);
9586     }
9587
9588     if (!wasCreated) {
9589         if (isWindow() || parentWidget()->isVisible())
9590             setAttribute(Qt::WA_WState_Hidden, true);
9591         else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9592             setAttribute(Qt::WA_WState_Hidden, false);
9593     }
9594
9595     d->updateIsOpaque();
9596
9597 #ifndef QT_NO_GRAPHICSVIEW
9598     // Embed the widget into a proxy if the parent is embedded.
9599     // ### Doesn't handle reparenting out of an embedded widget.
9600     if (oldtlw->graphicsProxyWidget()) {
9601         if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9602             ancestorProxy->d_func()->unembedSubWindow(this);
9603     }
9604     if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9605         if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9606             ancestorProxy->d_func()->embedSubWindow(this);
9607     }
9608 #endif
9609
9610     d->inSetParent = false;
9611 }
9612
9613 /*!
9614     Scrolls the widget including its children \a dx pixels to the
9615     right and \a dy downward. Both \a dx and \a dy may be negative.
9616
9617     After scrolling, the widgets will receive paint events for
9618     the areas that need to be repainted. For widgets that Qt knows to
9619     be opaque, this is only the newly exposed parts.
9620     For example, if an opaque widget is scrolled 8 pixels to the left,
9621     only an 8-pixel wide stripe at the right edge needs updating.
9622
9623     Since widgets propagate the contents of their parents by default,
9624     you need to set the \l autoFillBackground property, or use
9625     setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9626     a widget opaque.
9627
9628     For widgets that use contents propagation, a scroll will cause an
9629     update of the entire scroll area.
9630
9631     \sa {Transparency and Double Buffering}
9632 */
9633
9634 void QWidget::scroll(int dx, int dy)
9635 {
9636     if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9637         return;
9638     if (dx == 0 && dy == 0)
9639         return;
9640     Q_D(QWidget);
9641 #ifndef QT_NO_GRAPHICSVIEW
9642     if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9643         // Graphics View maintains its own dirty region as a list of rects;
9644         // until we can connect item updates directly to the view, we must
9645         // separately add a translated dirty region.
9646         if (!d->dirty.isEmpty()) {
9647             foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9648                 proxy->update(rect);
9649         }
9650         proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9651         return;
9652     }
9653 #endif
9654     d->setDirtyOpaqueRegion();
9655     d->scroll_sys(dx, dy);
9656 }
9657
9658 /*!
9659     \overload
9660
9661     This version only scrolls \a r and does not move the children of
9662     the widget.
9663
9664     If \a r is empty or invalid, the result is undefined.
9665
9666     \sa QScrollArea
9667 */
9668 void QWidget::scroll(int dx, int dy, const QRect &r)
9669 {
9670
9671     if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9672         return;
9673     if (dx == 0 && dy == 0)
9674         return;
9675     Q_D(QWidget);
9676 #ifndef QT_NO_GRAPHICSVIEW
9677     if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9678         // Graphics View maintains its own dirty region as a list of rects;
9679         // until we can connect item updates directly to the view, we must
9680         // separately add a translated dirty region.
9681         if (!d->dirty.isEmpty()) {
9682             foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9683                 proxy->update(rect);
9684         }
9685         proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9686         return;
9687     }
9688 #endif
9689     d->scroll_sys(dx, dy, r);
9690 }
9691
9692 /*!
9693     Repaints the widget directly by calling paintEvent() immediately,
9694     unless updates are disabled or the widget is hidden.
9695
9696     We suggest only using repaint() if you need an immediate repaint,
9697     for example during animation. In almost all circumstances update()
9698     is better, as it permits Qt to optimize for speed and minimize
9699     flicker.
9700
9701     \warning If you call repaint() in a function which may itself be
9702     called from paintEvent(), you may get infinite recursion. The
9703     update() function never causes recursion.
9704
9705     \sa update(), paintEvent(), setUpdatesEnabled()
9706 */
9707
9708 void QWidget::repaint()
9709 {
9710     repaint(rect());
9711 }
9712
9713 /*! \overload
9714
9715     This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9716     the widget.
9717
9718     If \a w is negative, it is replaced with \c{width() - x}, and if
9719     \a h is negative, it is replaced width \c{height() - y}.
9720 */
9721 void QWidget::repaint(int x, int y, int w, int h)
9722 {
9723     if (x > data->crect.width() || y > data->crect.height())
9724         return;
9725
9726     if (w < 0)
9727         w = data->crect.width()  - x;
9728     if (h < 0)
9729         h = data->crect.height() - y;
9730
9731     repaint(QRect(x, y, w, h));
9732 }
9733
9734 /*! \overload
9735
9736     This version repaints a rectangle \a rect inside the widget.
9737 */
9738 void QWidget::repaint(const QRect &rect)
9739 {
9740     Q_D(QWidget);
9741
9742     if (testAttribute(Qt::WA_WState_ConfigPending)) {
9743         update(rect);
9744         return;
9745     }
9746
9747     if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9748         return;
9749
9750     if (hasBackingStoreSupport()) {
9751 #ifdef Q_WS_MAC
9752         if (qt_widget_private(this)->isInUnifiedToolbar) {
9753             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9754             return;
9755         }
9756 #endif // Q_WS_MAC
9757         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9758         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9759             tlwExtra->inRepaint = true;
9760             tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9761             tlwExtra->inRepaint = false;
9762         }
9763     } else {
9764         d->repaint_sys(rect);
9765     }
9766 }
9767
9768 /*!
9769     \overload
9770
9771     This version repaints a region \a rgn inside the widget.
9772 */
9773 void QWidget::repaint(const QRegion &rgn)
9774 {
9775     Q_D(QWidget);
9776
9777     if (testAttribute(Qt::WA_WState_ConfigPending)) {
9778         update(rgn);
9779         return;
9780     }
9781
9782     if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9783         return;
9784
9785     if (hasBackingStoreSupport()) {
9786 #ifdef Q_WS_MAC
9787         if (qt_widget_private(this)->isInUnifiedToolbar) {
9788             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9789             return;
9790         }
9791 #endif // Q_WS_MAC
9792         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9793         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9794             tlwExtra->inRepaint = true;
9795             tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9796             tlwExtra->inRepaint = false;
9797         }
9798     } else {
9799         d->repaint_sys(rgn);
9800     }
9801 }
9802
9803 /*!
9804     Updates the widget unless updates are disabled or the widget is
9805     hidden.
9806
9807     This function does not cause an immediate repaint; instead it
9808     schedules a paint event for processing when Qt returns to the main
9809     event loop. This permits Qt to optimize for more speed and less
9810     flicker than a call to repaint() does.
9811
9812     Calling update() several times normally results in just one
9813     paintEvent() call.
9814
9815     Qt normally erases the widget's area before the paintEvent() call.
9816     If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9817     responsible for painting all its pixels with an opaque color.
9818
9819     \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9820 */
9821 void QWidget::update()
9822 {
9823     update(rect());
9824 }
9825
9826 /*! \fn void QWidget::update(int x, int y, int w, int h)
9827     \overload
9828
9829     This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9830     the widget.
9831 */
9832
9833 /*!
9834     \overload
9835
9836     This version updates a rectangle \a rect inside the widget.
9837 */
9838 void QWidget::update(const QRect &rect)
9839 {
9840     if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9841         return;
9842
9843     if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9844         QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9845         return;
9846     }
9847
9848     if (hasBackingStoreSupport()) {
9849 #ifdef Q_WS_MAC
9850         if (qt_widget_private(this)->isInUnifiedToolbar) {
9851             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9852             return;
9853         }
9854 #endif // Q_WS_MAC
9855         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9856         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9857             tlwExtra->backingStoreTracker->markDirty(rect, this);
9858     } else {
9859         d_func()->repaint_sys(rect);
9860     }
9861 }
9862
9863 /*!
9864     \overload
9865
9866     This version repaints a region \a rgn inside the widget.
9867 */
9868 void QWidget::update(const QRegion &rgn)
9869 {
9870     if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9871         return;
9872
9873     if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9874         QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9875         return;
9876     }
9877
9878     if (hasBackingStoreSupport()) {
9879 #ifdef Q_WS_MAC
9880         if (qt_widget_private(this)->isInUnifiedToolbar) {
9881             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9882             return;
9883         }
9884 #endif // Q_WS_MAC
9885         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9886         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9887             tlwExtra->backingStoreTracker->markDirty(rgn, this);
9888     } else {
9889         d_func()->repaint_sys(rgn);
9890     }
9891 }
9892
9893
9894  /*!
9895   \internal
9896
9897   This just sets the corresponding attribute bit to 1 or 0
9898  */
9899 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9900                                   QWidgetPrivate *d)
9901 {
9902     if (attribute < int(8*sizeof(uint))) {
9903         if (on)
9904             data->widget_attributes |= (1<<attribute);
9905         else
9906             data->widget_attributes &= ~(1<<attribute);
9907     } else {
9908         const int x = attribute - 8*sizeof(uint);
9909         const int int_off = x / (8*sizeof(uint));
9910         if (on)
9911             d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9912         else
9913             d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9914     }
9915 }
9916
9917 /*!
9918     Sets the attribute \a attribute on this widget if \a on is true;
9919     otherwise clears the attribute.
9920
9921     \sa testAttribute()
9922 */
9923 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9924 {
9925     if (testAttribute(attribute) == on)
9926         return;
9927
9928     Q_D(QWidget);
9929     Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9930                "QWidget::setAttribute(WidgetAttribute, bool)",
9931                "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9932 #ifdef Q_WS_WIN
9933     // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
9934     if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
9935         // see qwidget_win.cpp, ::paintEngine for details
9936         paintEngine();
9937         if (d->noPaintOnScreen)
9938             return;
9939     }
9940 #endif
9941
9942     setAttribute_internal(attribute, on, data, d);
9943
9944     switch (attribute) {
9945
9946 #ifndef QT_NO_DRAGANDDROP
9947     case Qt::WA_AcceptDrops:  {
9948         if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9949             setAttribute(Qt::WA_DropSiteRegistered, true);
9950         else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9951             setAttribute(Qt::WA_DropSiteRegistered, false);
9952         QEvent e(QEvent::AcceptDropsChange);
9953         QApplication::sendEvent(this, &e);
9954         break;
9955     }
9956     case Qt::WA_DropSiteRegistered:  {
9957         d->registerDropSite(on);
9958         for (int i = 0; i < d->children.size(); ++i) {
9959             QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9960             if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9961                 w->setAttribute(Qt::WA_DropSiteRegistered, on);
9962         }
9963         break;
9964     }
9965 #endif
9966
9967     case Qt::WA_NoChildEventsForParent:
9968         d->sendChildEvents = !on;
9969         break;
9970     case Qt::WA_NoChildEventsFromChildren:
9971         d->receiveChildEvents = !on;
9972         break;
9973     case Qt::WA_MacBrushedMetal:
9974 #ifdef Q_WS_MAC
9975         d->setStyle_helper(style(), false, true);  // Make sure things get unpolished/polished correctly.
9976         // fall through since changing the metal attribute affects the opaque size grip.
9977     case Qt::WA_MacOpaqueSizeGrip:
9978         d->macUpdateOpaqueSizeGrip();
9979         break;
9980     case Qt::WA_MacShowFocusRect:
9981         if (hasFocus()) {
9982             clearFocus();
9983             setFocus();
9984         }
9985         break;
9986     case Qt::WA_Hover:
9987         qt_mac_update_mouseTracking(this);
9988         break;
9989 #endif
9990     case Qt::WA_MacAlwaysShowToolWindow:
9991 #ifdef Q_WS_MAC
9992         d->macUpdateHideOnSuspend();
9993 #endif
9994         break;
9995     case Qt::WA_MacNormalSize:
9996     case Qt::WA_MacSmallSize:
9997     case Qt::WA_MacMiniSize:
9998 #ifdef Q_WS_MAC
9999         {
10000             // We can only have one of these set at a time
10001             const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10002                                                      Qt::WA_MacMiniSize };
10003             for (int i = 0; i < 3; ++i) {
10004                 if (MacSizes[i] != attribute)
10005                     setAttribute_internal(MacSizes[i], false, data, d);
10006             }
10007             d->macUpdateSizeAttribute();
10008         }
10009 #endif
10010         break;
10011     case Qt::WA_ShowModal:
10012         if (!on) {
10013             if (isVisible())
10014                 QApplicationPrivate::leaveModal(this);
10015             // reset modality type to Modeless when clearing WA_ShowModal
10016             data->window_modality = Qt::NonModal;
10017         } else if (data->window_modality == Qt::NonModal) {
10018             // determine the modality type if it hasn't been set prior
10019             // to setting WA_ShowModal. set the default to WindowModal
10020             // if we are the child of a group leader; otherwise use
10021             // ApplicationModal.
10022             QWidget *w = parentWidget();
10023             if (w)
10024                 w = w->window();
10025             while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10026                 w = w->parentWidget();
10027                 if (w)
10028                     w = w->window();
10029             }
10030             data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10031                                     ? Qt::WindowModal
10032                                     : Qt::ApplicationModal;
10033             // Some window managers does not allow us to enter modal after the
10034             // window is showing. Therefore, to be consistent, we cannot call
10035             // QApplicationPrivate::enterModal(this) here. The window must be
10036             // hidden before changing modality.
10037         }
10038         if (testAttribute(Qt::WA_WState_Created)) {
10039             // don't call setModal_sys() before create_sys()
10040             d->setModal_sys();
10041         }
10042         break;
10043     case Qt::WA_MouseTracking: {
10044         QEvent e(QEvent::MouseTrackingChange);
10045         QApplication::sendEvent(this, &e);
10046         break; }
10047     case Qt::WA_NativeWindow: {
10048         d->createTLExtra();
10049 #ifndef QT_NO_IM
10050         QWidget *focusWidget = d->effectiveFocusWidget();
10051         if (on && !internalWinId() && hasFocus()
10052             && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10053             qApp->inputMethod()->reset();
10054             qApp->inputMethod()->update(Qt::ImEnabled);
10055         }
10056         if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10057 #ifdef Q_WS_MAC
10058             // On Mac, toolbars inside the unified title bar will never overlap with
10059             // siblings in the content view. So we skip enforce native siblings in that case
10060             && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10061 #endif // Q_WS_MAC
10062         )
10063             parentWidget()->d_func()->enforceNativeChildren();
10064         if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10065             d->createWinId();
10066         if (isEnabled() && focusWidget->isEnabled()
10067             && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10068             qApp->inputMethod()->update(Qt::ImEnabled);
10069         }
10070 #endif //QT_NO_IM
10071         break;
10072     }
10073     case Qt::WA_PaintOnScreen:
10074         d->updateIsOpaque();
10075 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10076         // Recreate the widget if it's already created as an alien widget and
10077         // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10078         // So must their children.
10079         if (on) {
10080             setAttribute(Qt::WA_NativeWindow);
10081             d->enforceNativeChildren();
10082         }
10083 #endif
10084         // fall through
10085     case Qt::WA_OpaquePaintEvent:
10086         d->updateIsOpaque();
10087         break;
10088     case Qt::WA_NoSystemBackground:
10089         d->updateIsOpaque();
10090         // fall through...
10091     case Qt::WA_UpdatesDisabled:
10092         d->updateSystemBackground();
10093         break;
10094     case Qt::WA_TransparentForMouseEvents:
10095 #ifdef Q_WS_MAC
10096         d->macUpdateIgnoreMouseEvents();
10097 #endif
10098         break;
10099     case Qt::WA_InputMethodEnabled: {
10100 #ifndef QT_NO_IM
10101         if (qApp->focusObject() == this) {
10102             if (!on)
10103                 qApp->inputMethod()->reset();
10104             qApp->inputMethod()->update(Qt::ImEnabled);
10105         }
10106 #endif //QT_NO_IM
10107         break;
10108     }
10109     case Qt::WA_WindowPropagation:
10110         d->resolvePalette();
10111         d->resolveFont();
10112         d->resolveLocale();
10113         break;
10114 #ifdef Q_WS_X11
10115     case Qt::WA_NoX11EventCompression:
10116         if (!d->extra)
10117             d->createExtra();
10118         d->extra->compress_events = on;
10119         break;
10120     case Qt::WA_X11OpenGLOverlay:
10121         d->updateIsOpaque();
10122         break;
10123     case Qt::WA_X11DoNotAcceptFocus:
10124         if (testAttribute(Qt::WA_WState_Created))
10125             d->updateX11AcceptFocus();
10126         break;
10127 #endif
10128     case Qt::WA_DontShowOnScreen: {
10129         if (on && isVisible()) {
10130             // Make sure we keep the current state and only hide the widget
10131             // from the desktop. show_sys will only update platform specific
10132             // attributes at this point.
10133             d->hide_sys();
10134             d->show_sys();
10135         }
10136         break;
10137     }
10138
10139 #ifdef Q_WS_X11
10140     case Qt::WA_X11NetWmWindowTypeDesktop:
10141     case Qt::WA_X11NetWmWindowTypeDock:
10142     case Qt::WA_X11NetWmWindowTypeToolBar:
10143     case Qt::WA_X11NetWmWindowTypeMenu:
10144     case Qt::WA_X11NetWmWindowTypeUtility:
10145     case Qt::WA_X11NetWmWindowTypeSplash:
10146     case Qt::WA_X11NetWmWindowTypeDialog:
10147     case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10148     case Qt::WA_X11NetWmWindowTypePopupMenu:
10149     case Qt::WA_X11NetWmWindowTypeToolTip:
10150     case Qt::WA_X11NetWmWindowTypeNotification:
10151     case Qt::WA_X11NetWmWindowTypeCombo:
10152     case Qt::WA_X11NetWmWindowTypeDND:
10153         if (testAttribute(Qt::WA_WState_Created))
10154             d->setNetWmWindowTypes();
10155         break;
10156 #endif
10157
10158     case Qt::WA_StaticContents:
10159         if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10160             if (on)
10161                 bs->addStaticWidget(this);
10162             else
10163                 bs->removeStaticWidget(this);
10164         }
10165         break;
10166     case Qt::WA_TranslucentBackground:
10167         if (on) {
10168             setAttribute(Qt::WA_NoSystemBackground);
10169             d->updateIsTranslucent();
10170         }
10171
10172         break;
10173     case Qt::WA_AcceptTouchEvents:
10174 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10175         if (on)
10176             d->registerTouchWindow();
10177 #endif
10178         break;
10179     default:
10180         break;
10181     }
10182 }
10183
10184 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10185
10186   Returns true if attribute \a attribute is set on this widget;
10187   otherwise returns false.
10188
10189   \sa setAttribute()
10190  */
10191 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10192 {
10193     Q_D(const QWidget);
10194     const int x = attribute - 8*sizeof(uint);
10195     const int int_off = x / (8*sizeof(uint));
10196     return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10197 }
10198
10199 /*!
10200   \property QWidget::windowOpacity
10201
10202   \brief The level of opacity for the window.
10203
10204   The valid range of opacity is from 1.0 (completely opaque) to
10205   0.0 (completely transparent).
10206
10207   By default the value of this property is 1.0.
10208
10209   This feature is available on Embedded Linux, Mac OS X, Windows,
10210   and X11 platforms that support the Composite extension.
10211
10212   This feature is not available on Windows CE.
10213
10214   Note that under X11 you need to have a composite manager running,
10215   and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10216   supported by the window manager you are using.
10217
10218   \warning Changing this property from opaque to transparent might issue a
10219   paint event that needs to be processed before the window is displayed
10220   correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10221   that semi-transparent windows update and resize significantly slower than
10222   opaque windows.
10223
10224   \sa setMask()
10225 */
10226 qreal QWidget::windowOpacity() const
10227 {
10228     Q_D(const QWidget);
10229     return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10230 }
10231
10232 void QWidget::setWindowOpacity(qreal opacity)
10233 {
10234     Q_D(QWidget);
10235     if (!isWindow())
10236         return;
10237
10238     opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10239     QTLWExtra *extra = d->topData();
10240     extra->opacity = uint(opacity * 255);
10241     setAttribute(Qt::WA_WState_WindowOpacitySet);
10242
10243     if (!testAttribute(Qt::WA_WState_Created))
10244         return;
10245
10246 #ifndef QT_NO_GRAPHICSVIEW
10247     if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10248         // Avoid invalidating the cache if set.
10249         if (proxy->cacheMode() == QGraphicsItem::NoCache)
10250             proxy->update();
10251         else if (QGraphicsScene *scene = proxy->scene())
10252             scene->update(proxy->sceneBoundingRect());
10253         return;
10254     }
10255 #endif
10256
10257     d->setWindowOpacity_sys(opacity);
10258 }
10259
10260 /*!
10261     \property QWidget::windowModified
10262     \brief whether the document shown in the window has unsaved changes
10263
10264     A modified window is a window whose content has changed but has
10265     not been saved to disk. This flag will have different effects
10266     varied by the platform. On Mac OS X the close button will have a
10267     modified look; on other platforms, the window title will have an
10268     '*' (asterisk).
10269
10270     The window title must contain a "[*]" placeholder, which
10271     indicates where the '*' should appear. Normally, it should appear
10272     right after the file name (e.g., "document1.txt[*] - Text
10273     Editor"). If the window isn't modified, the placeholder is simply
10274     removed.
10275
10276     Note that if a widget is set as modified, all its ancestors will
10277     also be set as modified. However, if you call \c
10278     {setWindowModified(false)} on a widget, this will not propagate to
10279     its parent because other children of the parent might have been
10280     modified.
10281
10282     \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10283 */
10284 bool QWidget::isWindowModified() const
10285 {
10286     return testAttribute(Qt::WA_WindowModified);
10287 }
10288
10289 void QWidget::setWindowModified(bool mod)
10290 {
10291     Q_D(QWidget);
10292     setAttribute(Qt::WA_WindowModified, mod);
10293
10294 #ifndef Q_WS_MAC
10295     if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10296         qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10297 #endif
10298     d->setWindowTitle_helper(windowTitle());
10299     d->setWindowIconText_helper(windowIconText());
10300 #ifdef Q_WS_MAC
10301     d->setWindowModified_sys(mod);
10302 #endif
10303
10304     QEvent e(QEvent::ModifiedChange);
10305     QApplication::sendEvent(this, &e);
10306 }
10307
10308 #ifndef QT_NO_TOOLTIP
10309 /*!
10310   \property QWidget::toolTip
10311
10312   \brief the widget's tooltip
10313
10314   Note that by default tooltips are only shown for widgets that are
10315   children of the active window. You can change this behavior by
10316   setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10317   not on the widget with the tooltip.
10318
10319   If you want to control a tooltip's behavior, you can intercept the
10320   event() function and catch the QEvent::ToolTip event (e.g., if you
10321   want to customize the area for which the tooltip should be shown).
10322
10323   By default, this property contains an empty string.
10324
10325   \sa QToolTip statusTip whatsThis
10326 */
10327 void QWidget::setToolTip(const QString &s)
10328 {
10329     Q_D(QWidget);
10330     d->toolTip = s;
10331
10332     QEvent event(QEvent::ToolTipChange);
10333     QApplication::sendEvent(this, &event);
10334 }
10335
10336 QString QWidget::toolTip() const
10337 {
10338     Q_D(const QWidget);
10339     return d->toolTip;
10340 }
10341 #endif // QT_NO_TOOLTIP
10342
10343
10344 #ifndef QT_NO_STATUSTIP
10345 /*!
10346   \property QWidget::statusTip
10347   \brief the widget's status tip
10348
10349   By default, this property contains an empty string.
10350
10351   \sa toolTip whatsThis
10352 */
10353 void QWidget::setStatusTip(const QString &s)
10354 {
10355     Q_D(QWidget);
10356     d->statusTip = s;
10357 }
10358
10359 QString QWidget::statusTip() const
10360 {
10361     Q_D(const QWidget);
10362     return d->statusTip;
10363 }
10364 #endif // QT_NO_STATUSTIP
10365
10366 #ifndef QT_NO_WHATSTHIS
10367 /*!
10368   \property QWidget::whatsThis
10369
10370   \brief the widget's What's This help text.
10371
10372   By default, this property contains an empty string.
10373
10374   \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10375 */
10376 void QWidget::setWhatsThis(const QString &s)
10377 {
10378     Q_D(QWidget);
10379     d->whatsThis = s;
10380 }
10381
10382 QString QWidget::whatsThis() const
10383 {
10384     Q_D(const QWidget);
10385     return d->whatsThis;
10386 }
10387 #endif // QT_NO_WHATSTHIS
10388
10389 #ifndef QT_NO_ACCESSIBILITY
10390 /*!
10391   \property QWidget::accessibleName
10392
10393   \brief the widget's name as seen by assistive technologies
10394
10395   This property is used by accessible clients to identify, find, or announce
10396   the widget for accessible clients.
10397
10398   By default, this property contains an empty string.
10399
10400   \sa QAccessibleInterface::text()
10401 */
10402 void QWidget::setAccessibleName(const QString &name)
10403 {
10404     Q_D(QWidget);
10405     d->accessibleName = name;
10406     QAccessibleEvent event(QAccessible::NameChanged, this);
10407     QAccessible::updateAccessibility(&event);
10408 }
10409
10410 QString QWidget::accessibleName() const
10411 {
10412     Q_D(const QWidget);
10413     return d->accessibleName;
10414 }
10415
10416 /*!
10417   \property QWidget::accessibleDescription
10418
10419   \brief the widget's description as seen by assistive technologies
10420
10421   By default, this property contains an empty string.
10422
10423   \sa QAccessibleInterface::text()
10424 */
10425 void QWidget::setAccessibleDescription(const QString &description)
10426 {
10427     Q_D(QWidget);
10428     d->accessibleDescription = description;
10429     QAccessibleEvent event(QAccessible::DescriptionChanged, this);
10430     QAccessible::updateAccessibility(&event);
10431 }
10432
10433 QString QWidget::accessibleDescription() const
10434 {
10435     Q_D(const QWidget);
10436     return d->accessibleDescription;
10437 }
10438 #endif // QT_NO_ACCESSIBILITY
10439
10440 #ifndef QT_NO_SHORTCUT
10441 /*!
10442     Adds a shortcut to Qt's shortcut system that watches for the given
10443     \a key sequence in the given \a context. If the \a context is
10444     Qt::ApplicationShortcut, the shortcut applies to the application as a
10445     whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10446     or to the window itself, Qt::WindowShortcut.
10447
10448     If the same \a key sequence has been grabbed by several widgets,
10449     when the \a key sequence occurs a QEvent::Shortcut event is sent
10450     to all the widgets to which it applies in a non-deterministic
10451     order, but with the ``ambiguous'' flag set to true.
10452
10453     \warning You should not normally need to use this function;
10454     instead create \l{QAction}s with the shortcut key sequences you
10455     require (if you also want equivalent menu options and toolbar
10456     buttons), or create \l{QShortcut}s if you just need key sequences.
10457     Both QAction and QShortcut handle all the event filtering for you,
10458     and provide signals which are triggered when the user triggers the
10459     key sequence, so are much easier to use than this low-level
10460     function.
10461
10462     \sa releaseShortcut() setShortcutEnabled()
10463 */
10464 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10465 {
10466     Q_ASSERT(qApp);
10467     if (key.isEmpty())
10468         return 0;
10469     setAttribute(Qt::WA_GrabbedShortcut);
10470     return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10471 }
10472
10473 /*!
10474     Removes the shortcut with the given \a id from Qt's shortcut
10475     system. The widget will no longer receive QEvent::Shortcut events
10476     for the shortcut's key sequence (unless it has other shortcuts
10477     with the same key sequence).
10478
10479     \warning You should not normally need to use this function since
10480     Qt's shortcut system removes shortcuts automatically when their
10481     parent widget is destroyed. It is best to use QAction or
10482     QShortcut to handle shortcuts, since they are easier to use than
10483     this low-level function. Note also that this is an expensive
10484     operation.
10485
10486     \sa grabShortcut() setShortcutEnabled()
10487 */
10488 void QWidget::releaseShortcut(int id)
10489 {
10490     Q_ASSERT(qApp);
10491     if (id)
10492         qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10493 }
10494
10495 /*!
10496     If \a enable is true, the shortcut with the given \a id is
10497     enabled; otherwise the shortcut is disabled.
10498
10499     \warning You should not normally need to use this function since
10500     Qt's shortcut system enables/disables shortcuts automatically as
10501     widgets become hidden/visible and gain or lose focus. It is best
10502     to use QAction or QShortcut to handle shortcuts, since they are
10503     easier to use than this low-level function.
10504
10505     \sa grabShortcut() releaseShortcut()
10506 */
10507 void QWidget::setShortcutEnabled(int id, bool enable)
10508 {
10509     Q_ASSERT(qApp);
10510     if (id)
10511         qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10512 }
10513
10514 /*!
10515     \since 4.2
10516
10517     If \a enable is true, auto repeat of the shortcut with the
10518     given \a id is enabled; otherwise it is disabled.
10519
10520     \sa grabShortcut() releaseShortcut()
10521 */
10522 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10523 {
10524     Q_ASSERT(qApp);
10525     if (id)
10526         qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10527 }
10528 #endif // QT_NO_SHORTCUT
10529
10530 /*!
10531     Updates the widget's micro focus.
10532 */
10533 void QWidget::updateMicroFocus()
10534 {
10535     // updating everything since this is currently called for any kind of state change
10536     qApp->inputMethod()->update(Qt::ImQueryAll);
10537 }
10538
10539 /*!
10540     Raises this widget to the top of the parent widget's stack.
10541
10542     After this call the widget will be visually in front of any
10543     overlapping sibling widgets.
10544
10545     \note When using activateWindow(), you can call this function to
10546     ensure that the window is stacked on top.
10547
10548     \sa lower(), stackUnder()
10549 */
10550
10551 void QWidget::raise()
10552 {
10553     Q_D(QWidget);
10554     if (!isWindow()) {
10555         QWidget *p = parentWidget();
10556         const int parentChildCount = p->d_func()->children.size();
10557         if (parentChildCount < 2)
10558             return;
10559         const int from = p->d_func()->children.indexOf(this);
10560         Q_ASSERT(from >= 0);
10561         // Do nothing if the widget is already in correct stacking order _and_ created.
10562         if (from != parentChildCount -1)
10563             p->d_func()->children.move(from, parentChildCount - 1);
10564         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10565             create();
10566         else if (from == parentChildCount - 1)
10567             return;
10568
10569         QRegion region(rect());
10570         d->subtractOpaqueSiblings(region);
10571         d->invalidateBuffer(region);
10572     }
10573     if (testAttribute(Qt::WA_WState_Created))
10574         d->raise_sys();
10575
10576     QEvent e(QEvent::ZOrderChange);
10577     QApplication::sendEvent(this, &e);
10578 }
10579
10580 /*!
10581     Lowers the widget to the bottom of the parent widget's stack.
10582
10583     After this call the widget will be visually behind (and therefore
10584     obscured by) any overlapping sibling widgets.
10585
10586     \sa raise(), stackUnder()
10587 */
10588
10589 void QWidget::lower()
10590 {
10591     Q_D(QWidget);
10592     if (!isWindow()) {
10593         QWidget *p = parentWidget();
10594         const int parentChildCount = p->d_func()->children.size();
10595         if (parentChildCount < 2)
10596             return;
10597         const int from = p->d_func()->children.indexOf(this);
10598         Q_ASSERT(from >= 0);
10599         // Do nothing if the widget is already in correct stacking order _and_ created.
10600         if (from != 0)
10601             p->d_func()->children.move(from, 0);
10602         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10603             create();
10604         else if (from == 0)
10605             return;
10606     }
10607     if (testAttribute(Qt::WA_WState_Created))
10608         d->lower_sys();
10609
10610     QEvent e(QEvent::ZOrderChange);
10611     QApplication::sendEvent(this, &e);
10612 }
10613
10614
10615 /*!
10616     Places the widget under \a w in the parent widget's stack.
10617
10618     To make this work, the widget itself and \a w must be siblings.
10619
10620     \sa raise(), lower()
10621 */
10622 void QWidget::stackUnder(QWidget* w)
10623 {
10624     Q_D(QWidget);
10625     QWidget *p = parentWidget();
10626     if (!w || isWindow() || p != w->parentWidget() || this == w)
10627         return;
10628     if (p) {
10629         int from = p->d_func()->children.indexOf(this);
10630         int to = p->d_func()->children.indexOf(w);
10631         Q_ASSERT(from >= 0);
10632         Q_ASSERT(to >= 0);
10633         if (from < to)
10634             --to;
10635         // Do nothing if the widget is already in correct stacking order _and_ created.
10636         if (from != to)
10637             p->d_func()->children.move(from, to);
10638         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10639             create();
10640         else if (from == to)
10641             return;
10642     }
10643     if (testAttribute(Qt::WA_WState_Created))
10644         d->stackUnder_sys(w);
10645
10646     QEvent e(QEvent::ZOrderChange);
10647     QApplication::sendEvent(this, &e);
10648 }
10649
10650
10651 /*!
10652     \fn bool QWidget::isTopLevel() const
10653     \obsolete
10654
10655     Use isWindow() instead.
10656 */
10657
10658 /*!
10659     \fn bool QWidget::isRightToLeft() const
10660     \internal
10661 */
10662
10663 /*!
10664     \fn bool QWidget::isLeftToRight() const
10665     \internal
10666 */
10667
10668 /*!
10669      \macro QWIDGETSIZE_MAX
10670      \relates QWidget
10671
10672      Defines the maximum size for a QWidget object.
10673
10674      The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10675      QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10676
10677      \sa QWidget::setMaximumSize()
10678 */
10679
10680 /*!
10681     \fn QWidget::setupUi(QWidget *widget)
10682
10683     Sets up the user interface for the specified \a widget.
10684
10685     \note This function is available with widgets that derive from user
10686     interface descriptions created using \l{uic}.
10687
10688     \sa {Using a Designer UI File in Your Application}
10689 */
10690
10691 QRect QWidgetPrivate::frameStrut() const
10692 {
10693     Q_Q(const QWidget);
10694     if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10695         // x2 = x1 + w - 1, so w/h = 1
10696         return QRect(0, 0, 1, 1);
10697     }
10698
10699     if (data.fstrut_dirty
10700 #ifndef Q_WS_WIN
10701         // ### Fix properly for 4.3
10702         && q->isVisible()
10703 #endif
10704         && q->testAttribute(Qt::WA_WState_Created))
10705         const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10706
10707     return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10708 }
10709
10710 #ifdef QT_KEYPAD_NAVIGATION
10711 /*!
10712     \internal
10713
10714     Changes the focus  from the current focusWidget to a widget in
10715     the \a direction.
10716
10717     Returns true, if there was a widget in that direction
10718 */
10719 bool QWidgetPrivate::navigateToDirection(Direction direction)
10720 {
10721     QWidget *targetWidget = widgetInNavigationDirection(direction);
10722     if (targetWidget)
10723         targetWidget->setFocus();
10724     return (targetWidget != 0);
10725 }
10726
10727 /*!
10728     \internal
10729
10730     Searches for a widget that is positioned in the \a direction, starting
10731     from the current focusWidget.
10732
10733     Returns the pointer to a found widget or 0, if there was no widget in
10734     that direction.
10735 */
10736 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10737 {
10738     const QWidget *sourceWidget = QApplication::focusWidget();
10739     if (!sourceWidget)
10740         return 0;
10741     const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10742     const int sourceX =
10743             (direction == DirectionNorth || direction == DirectionSouth) ?
10744                 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10745                 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10746     const int sourceY =
10747             (direction == DirectionEast || direction == DirectionWest) ?
10748                 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10749                 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10750     const QPoint sourcePoint(sourceX, sourceY);
10751     const QPoint sourceCenter = sourceRect.center();
10752     const QWidget *sourceWindow = sourceWidget->window();
10753
10754     QWidget *targetWidget = 0;
10755     int shortestDistance = INT_MAX;
10756     foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10757
10758         const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10759
10760         // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10761         // but the owner of the proxy cannot.
10762         // Additionally, empty widgets should be ignored.
10763         if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10764             continue;
10765
10766         // Only navigate to a target widget that...
10767         if (       targetCandidate != sourceWidget
10768                    // ...takes the focus,
10769                 && targetCandidate->focusPolicy() & Qt::TabFocus
10770                    // ...is above if DirectionNorth,
10771                 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10772                    // ...is on the right if DirectionEast,
10773                 && !(direction == DirectionEast  && targetCandidateRect.left()   < sourceRect.right())
10774                    // ...is below if DirectionSouth,
10775                 && !(direction == DirectionSouth && targetCandidateRect.top()    < sourceRect.bottom())
10776                    // ...is on the left if DirectionWest,
10777                 && !(direction == DirectionWest  && targetCandidateRect.right()  > sourceRect.left())
10778                    // ...is enabled,
10779                 && targetCandidate->isEnabled()
10780                    // ...is visible,
10781                 && targetCandidate->isVisible()
10782                    // ...is in the same window,
10783                 && targetCandidate->window() == sourceWindow) {
10784             const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10785             if (targetCandidateDistance < shortestDistance) {
10786                 shortestDistance = targetCandidateDistance;
10787                 targetWidget = targetCandidate;
10788             }
10789         }
10790     }
10791     return targetWidget;
10792 }
10793
10794 /*!
10795     \internal
10796
10797     Tells us if it there is currently a reachable widget by keypad navigation in
10798     a certain \a orientation.
10799     If no navigation is possible, occurring key events in that \a orientation may
10800     be used to interact with the value in the focused widget, even though it
10801     currently has not the editFocus.
10802
10803     \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10804 */
10805 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10806 {
10807     return orientation == Qt::Horizontal?
10808             (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10809                     || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10810             :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10811                     || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10812 }
10813 /*!
10814     \internal
10815
10816     Checks, if the \a widget is inside a QTabWidget. If is is inside
10817     one, left/right key events will be used to switch between tabs in keypad
10818     navigation. If there is no QTabWidget, the horizontal key events can be used
10819 to
10820     interact with the value in the focused widget, even though it currently has
10821     not the editFocus.
10822
10823     \sa QWidget::hasEditFocus()
10824 */
10825 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10826 {
10827     for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10828         if (qobject_cast<const QTabWidget*>(tabWidget))
10829             return true;
10830     return false;
10831 }
10832 #endif
10833
10834 /*!
10835     \since 5.0
10836     \internal
10837
10838     Sets the backing store to be the \a store specified.
10839     The QWidget will take ownership of the \a store.
10840 */
10841 void QWidget::setBackingStore(QBackingStore *store)
10842 {
10843     // ### createWinId() ??
10844
10845     if (!isTopLevel())
10846         return;
10847
10848     Q_D(QWidget);
10849
10850     QTLWExtra *topData = d->topData();
10851     if (topData->backingStore == store)
10852         return;
10853
10854     QBackingStore *oldStore = topData->backingStore;
10855     delete topData->backingStore;
10856     topData->backingStore = store;
10857
10858     QWidgetBackingStore *bs = d->maybeBackingStore();
10859     if (!bs)
10860         return;
10861
10862     if (isTopLevel()) {
10863         if (bs->store != oldStore && bs->store != store)
10864             delete bs->store;
10865         bs->store = store;
10866     }
10867 }
10868
10869 /*!
10870     \since 5.0
10871
10872     Returns the QBackingStore this widget will be drawn into.
10873 */
10874 QBackingStore *QWidget::backingStore() const
10875 {
10876     Q_D(const QWidget);
10877     QTLWExtra *extra = d->maybeTopData();
10878     if (extra && extra->backingStore)
10879         return extra->backingStore;
10880
10881     QWidgetBackingStore *bs = d->maybeBackingStore();
10882
10883     return bs ? bs->store : 0;
10884 }
10885
10886 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10887 {
10888     if (left)
10889         *left = (int)leftLayoutItemMargin;
10890     if (top)
10891         *top = (int)topLayoutItemMargin;
10892     if (right)
10893         *right = (int)rightLayoutItemMargin;
10894     if (bottom)
10895         *bottom = (int)bottomLayoutItemMargin;
10896 }
10897
10898 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10899 {
10900     if (leftLayoutItemMargin == left
10901         && topLayoutItemMargin == top
10902         && rightLayoutItemMargin == right
10903         && bottomLayoutItemMargin == bottom)
10904         return;
10905
10906     Q_Q(QWidget);
10907     leftLayoutItemMargin = (signed char)left;
10908     topLayoutItemMargin = (signed char)top;
10909     rightLayoutItemMargin = (signed char)right;
10910     bottomLayoutItemMargin = (signed char)bottom;
10911     q->updateGeometry();
10912 }
10913
10914 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10915 {
10916     Q_Q(QWidget);
10917     QStyleOption myOpt;
10918     if (!opt) {
10919         myOpt.initFrom(q);
10920         myOpt.rect.setRect(0, 0, 32768, 32768);     // arbitrary
10921         opt = &myOpt;
10922     }
10923
10924     QRect liRect = q->style()->subElementRect(element, opt, q);
10925     if (liRect.isValid()) {
10926         leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10927         topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10928         rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10929         bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10930     } else {
10931         leftLayoutItemMargin = 0;
10932         topLayoutItemMargin = 0;
10933         rightLayoutItemMargin = 0;
10934         bottomLayoutItemMargin = 0;
10935     }
10936 }
10937 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10938 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10939 {
10940     Q_Q(QWidget);
10941
10942     if (!q->parentWidget()) {
10943         Qt::WindowType type = q->windowType();
10944         if (type == Qt::Widget || type == Qt::SubWindow)
10945             type = Qt::Window;
10946         if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10947             q->setAttribute(Qt::WA_QuitOnClose, false);
10948     }
10949 }
10950
10951
10952
10953 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10954 {
10955     return widget->data;
10956 }
10957
10958 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10959 {
10960     return widget->d_func();
10961 }
10962
10963
10964 #ifndef QT_NO_GRAPHICSVIEW
10965 /*!
10966    \since 4.5
10967
10968    Returns the proxy widget for the corresponding embedded widget in a graphics
10969    view; otherwise returns 0.
10970
10971    \sa QGraphicsProxyWidget::createProxyForChildWidget(),
10972        QGraphicsScene::addWidget()
10973  */
10974 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
10975 {
10976     Q_D(const QWidget);
10977     if (d->extra) {
10978         return d->extra->proxyWidget;
10979     }
10980     return 0;
10981 }
10982 #endif
10983
10984
10985 /*!
10986     \typedef QWidgetList
10987     \relates QWidget
10988
10989     Synonym for QList<QWidget *>.
10990 */
10991
10992 #ifndef QT_NO_GESTURES
10993 /*!
10994     Subscribes the widget to a given \a gesture with specific \a flags.
10995
10996     \sa ungrabGesture(), QGestureEvent
10997     \since 4.6
10998 */
10999 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11000 {
11001     Q_D(QWidget);
11002     d->gestureContext.insert(gesture, flags);
11003     (void)QGestureManager::instance(); // create a gesture manager
11004 }
11005
11006 /*!
11007     Unsubscribes the widget from a given \a gesture type
11008
11009     \sa grabGesture(), QGestureEvent
11010     \since 4.6
11011 */
11012 void QWidget::ungrabGesture(Qt::GestureType gesture)
11013 {
11014     Q_D(QWidget);
11015     if (d->gestureContext.remove(gesture)) {
11016         if (QGestureManager *manager = QGestureManager::instance())
11017             manager->cleanupCachedGestures(this, gesture);
11018     }
11019 }
11020 #endif // QT_NO_GESTURES
11021
11022 /*!
11023     \typedef WId
11024     \relates QWidget
11025
11026     Platform dependent window identifier.
11027 */
11028
11029 /*!
11030     \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11031
11032     Frees up window system resources. Destroys the widget window if \a
11033     destroyWindow is true.
11034
11035     destroy() calls itself recursively for all the child widgets,
11036     passing \a destroySubWindows for the \a destroyWindow parameter.
11037     To have more control over destruction of subwidgets, destroy
11038     subwidgets selectively first.
11039
11040     This function is usually called from the QWidget destructor.
11041 */
11042
11043 /*!
11044     \fn QPaintEngine *QWidget::paintEngine() const
11045
11046     Returns the widget's paint engine.
11047
11048     Note that this function should not be called explicitly by the
11049     user, since it's meant for reimplementation purposes only. The
11050     function is called by Qt internally, and the default
11051     implementation may not always return a valid pointer.
11052 */
11053
11054 /*!
11055     \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11056
11057     Translates the widget coordinate \a pos to global screen
11058     coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11059     the global coordinates of the top-left pixel of the widget.
11060
11061     \sa mapFromGlobal() mapTo() mapToParent()
11062 */
11063
11064 /*!
11065     \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11066
11067     Translates the global screen coordinate \a pos to widget
11068     coordinates.
11069
11070     \sa mapToGlobal() mapFrom() mapFromParent()
11071 */
11072
11073 /*!
11074     \fn void QWidget::grabMouse()
11075
11076     Grabs the mouse input.
11077
11078     This widget receives all mouse events until releaseMouse() is
11079     called; other widgets get no mouse events at all. Keyboard
11080     events are not affected. Use grabKeyboard() if you want to grab
11081     that.
11082
11083     \warning Bugs in mouse-grabbing applications very often lock the
11084     terminal. Use this function with extreme caution, and consider
11085     using the \c -nograb command line option while debugging.
11086
11087     It is almost never necessary to grab the mouse when using Qt, as
11088     Qt grabs and releases it sensibly. In particular, Qt grabs the
11089     mouse when a mouse button is pressed and keeps it until the last
11090     button is released.
11091
11092     \note Only visible widgets can grab mouse input. If isVisible()
11093     returns false for a widget, that widget cannot call grabMouse().
11094
11095     \note \b{(Mac OS X developers)} For \e Cocoa, calling
11096     grabMouse() on a widget only works when the mouse is inside the
11097     frame of that widget.  For \e Carbon, it works outside the widget's
11098     frame as well, like for Windows and X11.
11099
11100     \sa releaseMouse() grabKeyboard() releaseKeyboard()
11101 */
11102
11103 /*!
11104     \fn void QWidget::grabMouse(const QCursor &cursor)
11105     \overload grabMouse()
11106
11107     Grabs the mouse input and changes the cursor shape.
11108
11109     The cursor will assume shape \a cursor (for as long as the mouse
11110     focus is grabbed) and this widget will be the only one to receive
11111     mouse events until releaseMouse() is called().
11112
11113     \warning Grabbing the mouse might lock the terminal.
11114
11115     \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11116
11117     \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11118 */
11119
11120 /*!
11121     \fn void QWidget::releaseMouse()
11122
11123     Releases the mouse grab.
11124
11125     \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11126 */
11127
11128 /*!
11129     \fn void QWidget::grabKeyboard()
11130
11131     Grabs the keyboard input.
11132
11133     This widget receives all keyboard events until releaseKeyboard()
11134     is called; other widgets get no keyboard events at all. Mouse
11135     events are not affected. Use grabMouse() if you want to grab that.
11136
11137     The focus widget is not affected, except that it doesn't receive
11138     any keyboard events. setFocus() moves the focus as usual, but the
11139     new focus widget receives keyboard events only after
11140     releaseKeyboard() is called.
11141
11142     If a different widget is currently grabbing keyboard input, that
11143     widget's grab is released first.
11144
11145     \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11146 */
11147
11148 /*!
11149     \fn void QWidget::releaseKeyboard()
11150
11151     Releases the keyboard grab.
11152
11153     \sa grabKeyboard(), grabMouse(), releaseMouse()
11154 */
11155
11156 /*!
11157     \fn QWidget *QWidget::mouseGrabber()
11158
11159     Returns the widget that is currently grabbing the mouse input.
11160
11161     If no widget in this application is currently grabbing the mouse,
11162     0 is returned.
11163
11164     \sa grabMouse(), keyboardGrabber()
11165 */
11166
11167 /*!
11168     \fn QWidget *QWidget::keyboardGrabber()
11169
11170     Returns the widget that is currently grabbing the keyboard input.
11171
11172     If no widget in this application is currently grabbing the
11173     keyboard, 0 is returned.
11174
11175     \sa grabMouse(), mouseGrabber()
11176 */
11177
11178 /*!
11179     \fn void QWidget::activateWindow()
11180
11181     Sets the top-level widget containing this widget to be the active
11182     window.
11183
11184     An active window is a visible top-level window that has the
11185     keyboard input focus.
11186
11187     This function performs the same operation as clicking the mouse on
11188     the title bar of a top-level window. On X11, the result depends on
11189     the Window Manager. If you want to ensure that the window is
11190     stacked on top as well you should also call raise(). Note that the
11191     window must be visible, otherwise activateWindow() has no effect.
11192
11193     On Windows, if you are calling this when the application is not
11194     currently the active one then it will not make it the active
11195     window.  It will change the color of the taskbar entry to indicate
11196     that the window has changed in some way. This is because Microsoft
11197     does not allow an application to interrupt what the user is currently
11198     doing in another application.
11199
11200     \sa isActiveWindow(), window(), show()
11201 */
11202
11203 /*!
11204     \fn int QWidget::metric(PaintDeviceMetric m) const
11205
11206     Internal implementation of the virtual QPaintDevice::metric()
11207     function.
11208
11209     \a m is the metric to get.
11210 */
11211
11212 void QWidget::init(QPainter *painter) const
11213 {
11214     const QPalette &pal = palette();
11215     painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11216     painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11217     QFont f(font(), const_cast<QWidget *>(this));
11218     painter->d_func()->state->deviceFont = f;
11219     painter->d_func()->state->font = f;
11220 }
11221
11222 QPaintDevice *QWidget::redirected(QPoint *offset) const
11223 {
11224     return d_func()->redirected(offset);
11225 }
11226
11227 QPainter *QWidget::sharedPainter() const
11228 {
11229     // Someone sent a paint event directly to the widget
11230     if (!d_func()->redirectDev)
11231         return 0;
11232
11233     QPainter *sp = d_func()->sharedPainter();
11234     if (!sp || !sp->isActive())
11235         return 0;
11236
11237     if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11238         return 0;
11239
11240     return sp;
11241 }
11242
11243 /*!
11244     \fn void QWidget::setMask(const QRegion &region)
11245     \overload
11246
11247     Causes only the parts of the widget which overlap \a region to be
11248     visible. If the region includes pixels outside the rect() of the
11249     widget, window system controls in that area may or may not be
11250     visible, depending on the platform.
11251
11252     Note that this effect can be slow if the region is particularly
11253     complex.
11254
11255     \sa windowOpacity
11256 */
11257 void QWidget::setMask(const QRegion &newMask)
11258 {
11259     Q_D(QWidget);
11260
11261     d->createExtra();
11262     if (newMask == d->extra->mask)
11263         return;
11264
11265 #ifndef QT_NO_BACKINGSTORE
11266     const QRegion oldMask(d->extra->mask);
11267 #endif
11268
11269     d->extra->mask = newMask;
11270     d->extra->hasMask = !newMask.isEmpty();
11271
11272 #ifndef Q_WS_MAC
11273     if (!testAttribute(Qt::WA_WState_Created))
11274         return;
11275 #endif
11276
11277     d->setMask_sys(newMask);
11278
11279 #ifndef QT_NO_BACKINGSTORE
11280     if (!isVisible())
11281         return;
11282
11283     if (!d->extra->hasMask) {
11284         // Mask was cleared; update newly exposed area.
11285         QRegion expose(rect());
11286         expose -= oldMask;
11287         if (!expose.isEmpty()) {
11288             d->setDirtyOpaqueRegion();
11289             update(expose);
11290         }
11291         return;
11292     }
11293
11294     if (!isWindow()) {
11295         // Update newly exposed area on the parent widget.
11296         QRegion parentExpose(rect());
11297         parentExpose -= newMask;
11298         if (!parentExpose.isEmpty()) {
11299             d->setDirtyOpaqueRegion();
11300             parentExpose.translate(data->crect.topLeft());
11301             parentWidget()->update(parentExpose);
11302         }
11303
11304         // Update newly exposed area on this widget
11305         if (!oldMask.isEmpty())
11306             update(newMask - oldMask);
11307     }
11308 #endif
11309 }
11310
11311 /*!
11312     \fn void QWidget::setMask(const QBitmap &bitmap)
11313
11314     Causes only the pixels of the widget for which \a bitmap has a
11315     corresponding 1 bit to be visible. If the region includes pixels
11316     outside the rect() of the widget, window system controls in that
11317     area may or may not be visible, depending on the platform.
11318
11319     Note that this effect can be slow if the region is particularly
11320     complex.
11321
11322     The following code shows how an image with an alpha channel can be
11323     used to generate a mask for a widget:
11324
11325     \snippet doc/src/snippets/widget-mask/main.cpp 0
11326
11327     The label shown by this code is masked using the image it contains,
11328     giving the appearance that an irregularly-shaped image is being drawn
11329     directly onto the screen.
11330
11331     Masked widgets receive mouse events only on their visible
11332     portions.
11333
11334     \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11335 */
11336 void QWidget::setMask(const QBitmap &bitmap)
11337 {
11338     setMask(QRegion(bitmap));
11339 }
11340
11341 /*!
11342     \fn void QWidget::clearMask()
11343
11344     Removes any mask set by setMask().
11345
11346     \sa setMask()
11347 */
11348 void QWidget::clearMask()
11349 {
11350     setMask(QRegion());
11351 }
11352
11353 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11354     Returns the X11 Picture handle of the widget for XRender
11355     support. Use of this function is not portable. This function will
11356     return 0 if XRender support is not compiled into Qt, if the
11357     XRender extension is not supported on the X11 display, or if the
11358     handle could not be created.
11359 */
11360
11361 #ifdef Q_WS_MAC
11362 void QWidgetPrivate::syncUnifiedMode() {
11363     // The whole purpose of this method is to keep the unifiedToolbar in sync.
11364     // That means making sure we either exchange the drawing methods or we let
11365     // the toolbar know that it does not require to draw the baseline.
11366     Q_Q(QWidget);
11367     // This function makes sense only if this is a top level
11368     if(!q->isWindow())
11369         return;
11370     OSWindowRef window = qt_mac_window_for(q);
11371     if(changeMethods) {
11372         // Ok, we are in documentMode.
11373         if(originalDrawMethod)
11374             qt_mac_replaceDrawRect(window, this);
11375     } else {
11376         if(!originalDrawMethod)
11377             qt_mac_replaceDrawRectOriginal(window, this);
11378     }
11379 }
11380
11381 #endif // Q_WS_MAC
11382
11383 QT_END_NAMESPACE
11384
11385 #include "moc_qwidget.cpp"
11386