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