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