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