1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qapplication.h"
43 #include "qapplication_p.h"
46 #include "qdesktopwidget.h"
51 #include "qmetaobject.h"
56 #include "qstylefactory.h"
59 #include "qstyleoption.h"
60 #ifndef QT_NO_ACCESSIBILITY
61 # include "qaccessible.h"
64 # include "qt_mac_p.h"
65 # include "qt_cocoa_helpers_mac_p.h"
66 # include "qmainwindow.h"
67 # include "qtoolbar.h"
68 # include <private/qmainwindowlayout_p.h>
70 #include "qplatformwindow_qpa.h"
71 #include "private/qwidgetwindow_qpa_p.h"
74 #include "qwhatsthis.h"
76 #include "private/qstylesheetstyle_p.h"
77 #include "private/qstyle_p.h"
78 #include "qfileinfo.h"
79 #include "private/qsoftkeymanager_p.h"
80 #include <QtGui/qinputmethod.h>
82 #include <private/qgraphicseffect_p.h>
83 #include <qbackingstore.h>
84 #include <private/qwidgetbackingstore_p.h>
86 # include <private/qpaintengine_mac_p.h>
88 #include <private/qpaintengine_raster_p.h>
90 #include "qwidget_p.h"
91 #include <QtGui/private/qwindow_p.h>
92 #include "qaction_p.h"
93 #include "qlayout_p.h"
94 #include "QtWidgets/qgraphicsproxywidget.h"
95 #include "QtWidgets/qgraphicsscene.h"
96 #include "private/qgraphicsproxywidget_p.h"
97 #include "QtWidgets/qabstractscrollarea.h"
98 #include "private/qabstractscrollarea_p.h"
99 #include "private/qevent_p.h"
101 #include "private/qgesturemanager_p.h"
103 #ifdef QT_KEYPAD_NAVIGATION
104 #include "qtabwidget.h" // Needed in inTabWidget()
105 #endif // QT_KEYPAD_NAVIGATION
108 // widget/widget data creation count
109 //#define QWIDGET_EXTRA_DEBUG
110 //#define ALIEN_DEBUG
114 static bool qt_enable_backingstore = true;
116 // for compatibility with Qt 4.0
117 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
119 qt_enable_backingstore = enable;
124 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
127 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
129 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
130 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
133 static inline bool hasBackingStoreSupport()
139 # define QT_NO_PAINT_DEBUG
142 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
143 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
147 \class QWidgetBackingStoreTracker
148 \brief Class which allows tracking of which widgets are using a given backing store
150 QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
151 which maintains a list of the QWidgets which are currently using the backing
152 store. This list is modified via the registerWidget and unregisterWidget functions.
155 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
161 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
168 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
169 widgets using the backing store, then create a new QWidgetBackingStore, providing
172 void QWidgetBackingStoreTracker::create(QWidget *widget)
175 m_ptr = new QWidgetBackingStore(widget);
180 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181 widgets using the backing store.
183 void QWidgetBackingStoreTracker::destroy()
192 Add the widget to the list of widgets currently using the backing store.
193 If the widget was already in the list, this function is a no-op.
195 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
198 Q_ASSERT(w->internalWinId());
199 Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
205 Remove the widget from the list of widgets currently using the backing store.
206 If the widget was in the list, and removing it causes the list to be empty,
207 the backing store is deleted.
208 If the widget was not in the list, this function is a no-op.
210 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
212 if (m_widgets.remove(w) && m_widgets.isEmpty()) {
220 Recursively remove widget and all of its descendents.
222 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
224 unregisterWidget(widget);
225 foreach (QObject *child, widget->children())
226 if (QWidget *childWidget = qobject_cast<QWidget *>(child))
227 unregisterWidgetSubtree(childWidget);
230 QWidgetPrivate::QWidgetPrivate(int version)
231 : QObjectPrivate(version)
240 , extraPaintEngine(0)
243 #if !defined(QT_NO_IM)
244 , imHints(Qt::ImhNone)
246 , inheritedFontResolveMask(0)
247 , inheritedPaletteResolveMask(0)
252 , leftLayoutItemMargin(0)
253 , topLayoutItemMargin(0)
254 , rightLayoutItemMargin(0)
255 , bottomLayoutItemMargin(0)
257 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
258 , fg_role(QPalette::NoRole)
259 , bg_role(QPalette::NoRole)
260 , dirtyOpaqueChildren(1)
266 , usesDoubleBufferedGLContext(0)
268 , inheritsInputMethodHints(0)
271 #if defined(Q_WS_X11)
273 #elif defined(Q_WS_WIN)
275 #ifndef QT_NO_GESTURES
276 , nativeGesturePanEnabled(0)
278 #elif defined(Q_WS_MAC)
279 , needWindowChange(0)
285 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
289 if (version != QObjectPrivateVersion)
290 qFatal("Cannot mix incompatible Qt libraries");
293 memset(high_attributes, 0, sizeof(high_attributes));
295 drawRectOriginalAdded = false;
296 originalDrawMethod = true;
297 changeMethods = false;
298 isInUnifiedToolbar = false;
300 toolbar_ancestor = 0;
301 flushRequested = false;
302 touchEventsEnabled = false;
304 #ifdef QWIDGET_EXTRA_DEBUG
305 static int count = 0;
306 qDebug() << "widgets" << ++count;
311 QWidgetPrivate::~QWidgetPrivate()
319 #ifndef QT_NO_GRAPHICSEFFECT
320 delete graphicsEffect;
321 #endif //QT_NO_GRAPHICSEFFECT
327 void QWidgetPrivate::scrollChildren(int dx, int dy)
330 if (q->children().size() > 0) { // scroll children
332 QObjectList childObjects = q->children();
333 for (int i = 0; i < childObjects.size(); ++i) { // move all children
334 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
335 if (w && !w->isWindow()) {
336 QPoint oldp = w->pos();
337 QRect r(w->pos() + pd, w->size());
339 if (w->testAttribute(Qt::WA_WState_Created))
340 w->d_func()->setWSGeometry();
341 w->d_func()->setDirtyOpaqueRegion();
342 QMoveEvent e(r.topLeft(), oldp);
343 QApplication::sendEvent(w, &e);
349 void QWidgetPrivate::updateWidgetTransform()
352 if (q == qGuiApp->focusObject()) {
354 QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
355 t.translate(p.x(), p.y());
356 qApp->inputMethod()->setInputItemTransform(t);
360 #ifdef QT_KEYPAD_NAVIGATION
361 QPointer<QWidget> QWidgetPrivate::editingWidget;
364 Returns true if this widget currently has edit focus; otherwise false.
366 This feature is only available in Qt for Embedded Linux.
368 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
370 bool QWidget::hasEditFocus() const
372 const QWidget* w = this;
373 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
374 w = w->d_func()->extra->focus_proxy;
375 return QWidgetPrivate::editingWidget == w;
379 \fn void QWidget::setEditFocus(bool enable)
381 If \a enable is true, make this widget have edit focus, in which
382 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
383 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
386 This feature is only available in Qt for Embedded Linux.
388 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
390 void QWidget::setEditFocus(bool on)
393 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
394 f = f->d_func()->extra->focus_proxy;
396 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
397 QWidgetPrivate::editingWidget->setEditFocus(false);
399 if (on && !f->hasFocus())
402 if ((!on && !QWidgetPrivate::editingWidget)
403 || (on && QWidgetPrivate::editingWidget == f)) {
407 if (!on && QWidgetPrivate::editingWidget == f) {
408 QWidgetPrivate::editingWidget = 0;
409 QEvent event(QEvent::LeaveEditFocus);
410 QApplication::sendEvent(f, &event);
411 QApplication::sendEvent(f->style(), &event);
413 QWidgetPrivate::editingWidget = f;
414 QEvent event(QEvent::EnterEditFocus);
415 QApplication::sendEvent(f, &event);
416 QApplication::sendEvent(f->style(), &event);
422 \property QWidget::autoFillBackground
423 \brief whether the widget background is filled automatically
426 If enabled, this property will cause Qt to fill the background of the
427 widget before invoking the paint event. The color used is defined by the
428 QPalette::Window color role from the widget's \l{QPalette}{palette}.
430 In addition, Windows are always filled with QPalette::Window, unless the
431 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
433 This property cannot be turned off (i.e., set to false) if a widget's
434 parent has a static gradient for its background.
436 \warning Use this property with caution in conjunction with
437 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
438 background or a border-image, this property is automatically disabled.
440 By default, this property is false.
442 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
443 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
445 bool QWidget::autoFillBackground() const
448 return d->extra && d->extra->autoFillBackground;
451 void QWidget::setAutoFillBackground(bool enabled)
456 if (d->extra->autoFillBackground == enabled)
459 d->extra->autoFillBackground = enabled;
467 \brief The QWidget class is the base class of all user interface objects.
469 \ingroup basicwidgets
472 The widget is the atom of the user interface: it receives mouse, keyboard
473 and other events from the window system, and paints a representation of
474 itself on the screen. Every widget is rectangular, and they are sorted in a
475 Z-order. A widget is clipped by its parent and by the widgets in front of
478 A widget that is not embedded in a parent widget is called a window.
479 Usually, windows have a frame and a title bar, although it is also possible
480 to create windows without such decoration using suitable
481 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
482 subclasses of QDialog are the most common window types.
484 Every widget's constructor accepts one or two standard arguments:
487 \li \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
488 (the default), the new widget will be a window. If not, it will be
489 a child of \e parent, and be constrained by \e parent's geometry
490 (unless you specify Qt::Window as window flag).
491 \li \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
492 the default is suitable for almost all widgets, but to get, for
493 example, a window without a window system frame, you must use
497 QWidget has many member functions, but some of them have little direct
498 functionality; for example, QWidget has a font property, but never uses
499 this itself. There are many subclasses which provide real functionality,
500 such as QLabel, QPushButton, QListWidget, and QTabWidget.
503 \section1 Top-Level and Child Widgets
505 A widget without a parent widget is always an independent window (top-level
506 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
507 title bar and icon respectively.
509 Non-window widgets are child widgets, displayed within their parent
510 widgets. Most widgets in Qt are mainly useful as child widgets. For
511 example, it is possible to display a button as a top-level window, but most
512 people prefer to put their buttons inside other widgets, such as QDialog.
514 \image parent-child-widgets.png A parent widget containing various child widgets.
516 The diagram above shows a QGroupBox widget being used to hold various child
517 widgets in a layout provided by QGridLayout. The QLabel child widgets have
518 been outlined to indicate their full sizes.
520 If you want to use a QWidget to hold child widgets you will usually want to
521 add a layout to the parent QWidget. See \l{Layout Management} for more
525 \section1 Composite Widgets
527 When a widget is used as a container to group a number of child widgets, it
528 is known as a composite widget. These can be created by constructing a
529 widget with the required visual properties - a QFrame, for example - and
530 adding child widgets to it, usually managed by a layout. The above diagram
531 shows such a composite widget that was created using \l{Qt Designer}.
533 Composite widgets can also be created by subclassing a standard widget,
534 such as QWidget or QFrame, and adding the necessary layout and child
535 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
536 {examples provided with Qt} use this approach, and it is also covered in
537 the Qt \l{Tutorials}.
540 \section1 Custom Widgets and Painting
542 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
543 display custom content that is composed using a series of painting
544 operations with an instance of the QPainter class. This approach contrasts
545 with the canvas-style approach used by the \l{Graphics View}
546 {Graphics View Framework} where items are added to a scene by the
547 application and are rendered by the framework itself.
549 Each widget performs all painting operations from within its paintEvent()
550 function. This is called whenever the widget needs to be redrawn, either
551 as a result of some external change or when requested by the application.
553 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
554 can handle paint events.
557 \section1 Size Hints and Size Policies
559 When implementing a new widget, it is almost always useful to reimplement
560 sizeHint() to provide a reasonable default size for the widget and to set
561 the correct size policy with setSizePolicy().
563 By default, composite widgets which do not provide a size hint will be
564 sized according to the space requirements of their child widgets.
566 The size policy lets you supply good default behavior for the layout
567 management system, so that other widgets can contain and manage yours
568 easily. The default size policy indicates that the size hint represents
569 the preferred size of the widget, and this is often good enough for many
572 \note The size of top-level widgets are constrained to 2/3 of the desktop's
573 height and width. You can resize() the widget manually if these bounds are
579 Widgets respond to events that are typically caused by user actions. Qt
580 delivers events to widgets by calling specific event handler functions with
581 instances of QEvent subclasses containing information about each event.
583 If your widget only contains child widgets, you probably do not need to
584 implement any event handlers. If you want to detect a mouse click in a
585 child widget call the child's underMouse() function inside the widget's
588 The \l{widgets/scribble}{Scribble example} implements a wider set of
589 events to handle mouse movement, button presses, and window resizing.
591 You will need to supply the behavior and content for your own widgets, but
592 here is a brief overview of the events that are relevant to QWidget,
593 starting with the most common ones:
596 \li paintEvent() is called whenever the widget needs to be repainted.
597 Every widget displaying custom content must implement it. Painting
598 using a QPainter can only take place in a paintEvent() or a
599 function called by a paintEvent().
600 \li resizeEvent() is called when the widget has been resized.
601 \li mousePressEvent() is called when a mouse button is pressed while
602 the mouse cursor is inside the widget, or when the widget has
603 grabbed the mouse using grabMouse(). Pressing the mouse without
604 releasing it is effectively the same as calling grabMouse().
605 \li mouseReleaseEvent() is called when a mouse button is released. A
606 widget receives mouse release events when it has received the
607 corresponding mouse press event. This means that if the user
608 presses the mouse inside \e your widget, then drags the mouse
609 somewhere else before releasing the mouse button, \e your widget
610 receives the release event. There is one exception: if a popup menu
611 appears while the mouse button is held down, this popup immediately
612 steals the mouse events.
613 \li mouseDoubleClickEvent() is called when the user double-clicks in
614 the widget. If the user double-clicks, the widget receives a mouse
615 press event, a mouse release event, (a mouse click event,) a second
616 mouse press, this event and finally a second mouse release event.
617 (Some mouse move events may also be
618 received if the mouse is not held steady during this operation.) It
619 is \e{not possible} to distinguish a click from a double-click
620 until the second click arrives. (This is one reason why most GUI
621 books recommend that double-clicks be an extension of
622 single-clicks, rather than trigger a different action.)
625 Widgets that accept keyboard input need to reimplement a few more event
629 \li keyPressEvent() is called whenever a key is pressed, and again when
630 a key has been held down long enough for it to auto-repeat. The
631 \key Tab and \key Shift+Tab keys are only passed to the widget if
632 they are not used by the focus-change mechanisms. To force those
633 keys to be processed by your widget, you must reimplement
635 \li focusInEvent() is called when the widget gains keyboard focus
636 (assuming you have called setFocusPolicy()). Well-behaved widgets
637 indicate that they own the keyboard focus in a clear but discreet
639 \li focusOutEvent() is called when the widget loses keyboard focus.
642 You may be required to also reimplement some of the less common event
646 \li mouseMoveEvent() is called whenever the mouse moves while a mouse
647 button is held down. This can be useful during drag and drop
648 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
649 you get mouse move events even when no buttons are held down.
650 (See also the \l{Drag and Drop} guide.)
651 \li keyReleaseEvent() is called whenever a key is released and while it
652 is held down (if the key is auto-repeating). In that case, the
653 widget will receive a pair of key release and key press event for
654 every repeat. The \key Tab and \key Shift+Tab keys are only passed
655 to the widget if they are not used by the focus-change mechanisms.
656 To force those keys to be processed by your widget, you must
657 reimplement QWidget::event().
658 \li wheelEvent() is called whenever the user turns the mouse wheel
659 while the widget has the focus.
660 \li enterEvent() is called when the mouse enters the widget's screen
661 space. (This excludes screen space owned by any of the widget's
663 \li leaveEvent() is called when the mouse leaves the widget's screen
664 space. If the mouse enters a child widget it will not cause a
666 \li moveEvent() is called when the widget has been moved relative to
668 \li closeEvent() is called when the user closes the widget (or when
672 There are also some rather obscure events described in the documentation
673 for QEvent::Type. To handle these events, you need to reimplement event()
676 The default implementation of event() handles \key Tab and \key Shift+Tab
677 (to move the keyboard focus), and passes on most of the other events to
678 one of the more specialized handlers above.
680 Events and the mechanism used to deliver them are covered in
681 \l{The Event System}.
683 \section1 Groups of Functions and Properties
686 \header \li Context \li Functions and Properties
688 \row \li Window functions \li
695 \row \li Top-level windows \li
696 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
697 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
698 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
701 \row \li Window contents \li
706 \row \li Geometry \li
707 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
708 \l sizePolicy, sizeHint(), minimumSizeHint(),
709 updateGeometry(), layout(),
710 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
712 mapFromGlobal(), mapToGlobal(),
713 mapFromParent(), mapToParent(),
714 \l maximumSize, \l minimumSize, \l sizeIncrement,
715 \l baseSize, setFixedSize()
718 \l visible, isVisibleTo(),
719 \l enabled, isEnabledTo(),
726 \row \li Look and feel \li
733 backgroundRole(), setBackgroundRole(),
734 fontInfo(), fontMetrics().
736 \row \li Keyboard focus functions \li
737 \l focus, \l focusPolicy,
738 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
739 focusNextChild(), focusPreviousChild().
741 \row \li Mouse and keyboard grabbing \li
742 grabMouse(), releaseMouse(),
743 grabKeyboard(), releaseKeyboard(),
744 mouseGrabber(), keyboardGrabber().
746 \row \li Event handlers \li
750 mouseDoubleClickEvent(),
773 \row \li System functions \li
774 parentWidget(), window(), setParent(), winId(),
777 \row \li Interactive help \li
778 setToolTip(), setWhatsThis()
783 \section1 Widget Style Sheets
785 In addition to the standard widget styles for each platform, widgets can
786 also be styled according to rules specified in a \l{styleSheet}
787 {style sheet}. This feature enables you to customize the appearance of
788 specific widgets to provide visual cues to users about their purpose. For
789 example, a button could be styled in a particular way to indicate that it
790 performs a destructive action.
792 The use of widget style sheets is described in more detail in the
793 \l{Qt Style Sheets} document.
796 \section1 Transparency and Double Buffering
798 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
799 is no need to write double-buffering code in paintEvent() to avoid
802 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
803 deprecated. Instead, the contents of parent widgets are propagated by
804 default to each of their children as long as Qt::WA_PaintOnScreen is not
805 set. Custom widgets can be written to take advantage of this feature by
806 updating irregular regions (to create non-rectangular child widgets), or
807 painting with colors that have less than full alpha component. The
808 following diagram shows how attributes and properties of a custom widget
809 can be fine-tuned to achieve different effects.
811 \image propagation-custom.png
813 In the above diagram, a semi-transparent rectangular child widget with an
814 area removed is constructed and added to a parent widget (a QLabel showing
815 a pixmap). Then, different properties and widget attributes are set to
816 achieve different effects:
819 \li The left widget has no additional properties or widget attributes
820 set. This default state suits most custom widgets using
821 transparency, are irregularly-shaped, or do not paint over their
822 entire area with an opaque brush.
823 \li The center widget has the \l autoFillBackground property set. This
824 property is used with custom widgets that rely on the widget to
825 supply a default background, and do not paint over their entire
826 area with an opaque brush.
827 \li The right widget has the Qt::WA_OpaquePaintEvent widget attribute
828 set. This indicates that the widget will paint over its entire area
829 with opaque colors. The widget's area will initially be
830 \e{uninitialized}, represented in the diagram with a red diagonal
831 grid pattern that shines through the overpainted area. The
832 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
833 paint their own specialized contents quickly and do not need a
834 default filled background.
837 To rapidly update custom widgets with simple background colors, such as
838 real-time plotting or graphing widgets, it is better to define a suitable
839 background color (using setBackgroundRole() with the
840 QPalette::Window role), set the \l autoFillBackground property, and only
841 implement the necessary drawing functionality in the widget's paintEvent().
843 To rapidly update custom widgets that constantly paint over their entire
844 areas with opaque content, e.g., video streaming widgets, it is better to
845 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
846 associated with repainting the widget's background.
848 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
849 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
850 attribute takes precedence. Depending on your requirements, you should
851 choose either one of them.
853 Since Qt 4.1, the contents of parent widgets are also propagated to
854 standard Qt widgets. This can lead to some unexpected results if the
855 parent widget is decorated in a non-standard way, as shown in the diagram
858 \image propagation-standard.png
860 The scope for customizing the painting behavior of standard Qt widgets,
861 without resorting to subclassing, is slightly less than that possible for
862 custom widgets. Usually, the desired appearance of a standard widget can be
863 achieved by setting its \l autoFillBackground property.
866 \section1 Creating Translucent Windows
868 Since Qt 4.5, it has been possible to create windows with translucent regions
869 on window systems that support compositing.
871 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
872 attribute with setAttribute() and ensure that its background is painted with
873 non-opaque colors in the regions you want to be partially transparent.
878 \li X11: This feature relies on the use of an X server that supports ARGB visuals
879 and a compositing window manager.
880 \li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
881 for the translucency to work.
885 \section1 Native Widgets vs Alien Widgets
887 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
888 system. They do not have a native window handle associated with them. This
889 feature significantly speeds up widget painting, resizing, and removes flicker.
891 Should you require the old behavior with native windows, you can choose
892 one of the following options:
895 \li Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
896 \li Set the Qt::AA_NativeWindows attribute on your application. All
897 widgets will be native widgets.
898 \li Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
899 and all of its ancestors will become native (unless
900 Qt::WA_DontCreateNativeAncestors is set).
901 \li Call QWidget::winId to enforce a native window (this implies 3).
902 \li Set the Qt::WA_PaintOnScreen attribute to enforce a native window
906 \sa QEvent, QPainter, QGridLayout, QBoxLayout
910 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
911 other visual representation on the screen that is generally located next to its
912 physical counterpart. They are most often found on mobile phone platforms. In
913 modern touch based user interfaces it is also possible to have softkeys that do
914 not correspond to any physical keys. Softkeys differ from other onscreen labels
915 in that they are contextual.
917 In Qt, contextual softkeys are added to a widget by calling addAction() and
918 passing a \c QAction with a softkey role set on it. When the widget
919 containing the softkey actions has focus, its softkeys should appear in
920 the user interface. Softkeys are discovered by traversing the widget
921 hierarchy so it is possible to define a single set of softkeys that are
922 present at all times by calling addAction() for a given top level widget.
924 On some platforms, this concept overlaps with \c QMenuBar such that if no
925 other softkeys are found and the top level widget is a QMainWindow containing
926 a QMenuBar, the menubar actions may appear on one of the softkeys.
928 Note: Currently softkeys are only supported on the Symbian Platform.
930 \sa addAction(), QAction, QMenuBar
934 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
935 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
938 /*****************************************************************************
939 QWidget utility functions
940 *****************************************************************************/
942 QRegion qt_dirtyRegion(QWidget *widget)
947 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
951 return bs->dirtyRegion(widget);
954 /*****************************************************************************
955 QWidget member functions
956 *****************************************************************************/
961 \li Qt::WA_WState_Created The widget has a valid winId().
962 \li Qt::WA_WState_Visible The widget is currently visible.
963 \li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
964 become visible unless you call show() on it. Qt::WA_WState_Hidden
965 implies !Qt::WA_WState_Visible.
966 \li Qt::WA_WState_CompressKeys Compress keyboard events.
967 \li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
968 \li Qt::WA_WState_InPaintEvent Currently processing a paint event.
969 \li Qt::WA_WState_Reparented The widget has been reparented.
970 \li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
971 \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
975 struct QWidgetExceptionCleaner
977 /* this cleans up when the constructor throws an exception */
978 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
980 #ifdef QT_NO_EXCEPTIONS
984 QWidgetPrivate::allWidgets->remove(that);
985 if (d->focus_next != that) {
987 d->focus_next->d_func()->focus_prev = d->focus_prev;
989 d->focus_prev->d_func()->focus_next = d->focus_next;
996 Constructs a widget which is a child of \a parent, with widget
999 If \a parent is 0, the new widget becomes a window. If
1000 \a parent is another widget, this widget becomes a child window
1001 inside \a parent. The new widget is deleted when its \a parent is
1004 The widget flags argument, \a f, is normally 0, but it can be set
1005 to customize the frame of a window (i.e. \a
1006 parent must be 0). To customize the frame, use a value composed
1007 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1009 If you add a child widget to an already visible widget you must
1010 explicitly show the child to make it visible.
1012 Note that the X11 version of Qt may not be able to deliver all
1013 combinations of style flags on all systems. This is because on
1014 X11, Qt can only ask the window manager, and the window manager
1015 can override the application's settings. On Windows, Qt can set
1016 whatever flags you want.
1020 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1021 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1024 d_func()->init(parent, f);
1026 QWidgetExceptionCleaner::cleanup(this, d_func());
1034 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1035 : QObject(dd, 0), QPaintDevice()
1041 QWidgetExceptionCleaner::cleanup(this, d_func());
1049 int QWidget::devType() const
1051 return QInternal::Widget;
1055 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1056 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1058 bool customize = (flags & (Qt::CustomizeWindowHint
1059 | Qt::FramelessWindowHint
1060 | Qt::WindowTitleHint
1061 | Qt::WindowSystemMenuHint
1062 | Qt::WindowMinimizeButtonHint
1063 | Qt::WindowMaximizeButtonHint
1064 | Qt::WindowCloseButtonHint
1065 | Qt::WindowContextHelpButtonHint));
1067 uint type = (flags & Qt::WindowType_Mask);
1069 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1071 flags |= Qt::Window;
1074 if (flags & Qt::CustomizeWindowHint) {
1075 // modify window flags to make them consistent.
1076 // Only enable this on non-Mac platforms. Since the old way of doing this would
1077 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1078 // we can't just add this in.
1080 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1081 flags |= Qt::WindowSystemMenuHint;
1083 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1084 | Qt::WindowSystemMenuHint)) {
1086 flags |= Qt::WindowTitleHint;
1087 flags &= ~Qt::FramelessWindowHint;
1089 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1090 // if any of the window hints that affect the titlebar are set
1091 // and the window is supposed to have frame, we add a titlebar
1092 // and system menu by default.
1093 flags |= Qt::WindowSystemMenuHint;
1094 flags |= Qt::WindowTitleHint;
1097 ; // don't modify window flags if the user explicitly set them.
1098 else if (type == Qt::Dialog || type == Qt::Sheet)
1100 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1102 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1104 else if (type == Qt::Tool)
1105 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1107 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1112 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1115 if (QApplication::type() == QApplication::Tty)
1116 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1118 Q_ASSERT(allWidgets);
1120 allWidgets->insert(q);
1122 QWidget *desktopWidget = 0;
1123 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1124 desktopWidget = parentWidget;
1130 #ifndef QT_NO_THREAD
1132 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1133 "Widgets must be created in the GUI thread.");
1137 #if defined(Q_WS_X11)
1138 if (desktopWidget) {
1139 // make sure the widget is created on the same screen as the
1140 // programmer specified desktop widget
1141 xinfo = desktopWidget->d_func()->xinfo;
1144 if (desktopWidget) {
1145 const int screen = desktopWidget->d_func()->topData()->screenIndex;
1146 if (QWindow *window = q->windowHandle())
1147 window->setScreen(QGuiApplication::screens().value(screen, 0));
1150 data.fstrut_dirty = true;
1153 data.widget_attributes = 0;
1154 data.window_flags = f;
1155 data.window_state = 0;
1156 data.focus_policy = 0;
1157 data.context_menu_policy = Qt::DefaultContextMenu;
1158 data.window_modality = Qt::NonModal;
1160 data.sizehint_forced = 0;
1161 data.is_closing = 0;
1163 data.in_set_window_state = 0;
1164 data.in_destructor = false;
1166 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1167 if (f & Qt::MSWindowsOwnDC)
1168 q->setAttribute(Qt::WA_NativeWindow);
1171 // q->setAttribute(Qt::WA_NativeWindow);
1174 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1175 adjustQuitOnCloseAttribute();
1177 q->setAttribute(Qt::WA_WState_Hidden);
1179 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1180 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1181 focus_next = focus_prev = q;
1183 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1185 else if (parentWidget)
1186 q->setParent(parentWidget, data.window_flags);
1188 adjustFlags(data.window_flags, q);
1189 resolveLayoutDirection();
1190 // opaque system background?
1191 const QBrush &background = q->palette().brush(QPalette::Window);
1192 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1194 data.fnt = QFont(data.fnt, q);
1195 #if defined(Q_WS_X11)
1196 data.fnt.x11SetScreen(xinfo.screen());
1199 q->setAttribute(Qt::WA_PendingMoveEvent);
1200 q->setAttribute(Qt::WA_PendingResizeEvent);
1202 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1203 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1205 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1208 QEvent e(QEvent::Create);
1209 QApplication::sendEvent(q, &e);
1210 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1212 extraPaintEngine = 0;
1215 // If we add a child to the unified toolbar, we have to redirect the painting.
1216 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1217 if (parentWidget->d_func()->unifiedSurface) {
1218 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1219 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1227 void QWidgetPrivate::createRecursively()
1230 q->create(0, true, true);
1231 for (int i = 0; i < children.size(); ++i) {
1232 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1233 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1234 child->d_func()->createRecursively();
1242 Creates a new widget window if \a window is 0, otherwise sets the
1243 widget's window to \a window.
1245 Initializes the window (sets the geometry etc.) if \a
1246 initializeWindow is true. If \a initializeWindow is false, no
1247 initialization is performed. This parameter only makes sense if \a
1248 window is a valid window.
1250 Destroys the old window if \a destroyOldWindow is true. If \a
1251 destroyOldWindow is false, you are responsible for destroying the
1252 window yourself (using platform native code).
1254 The QWidget constructor calls create(0,true,true) to create a
1255 window for this widget.
1258 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1261 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1264 if (d->data.in_destructor)
1267 Qt::WindowType type = windowType();
1268 Qt::WindowFlags &flags = data->window_flags;
1270 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1272 flags |= Qt::Window;
1275 if (QWidget *parent = parentWidget()) {
1276 if (type & Qt::Window) {
1277 if (!parent->testAttribute(Qt::WA_WState_Created))
1278 parent->createWinId();
1279 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1280 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1281 // We're about to create a native child widget that doesn't have a native parent;
1282 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1283 // attribute is set.
1284 d->createWinId(window);
1285 // Nothing more to do.
1286 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1287 Q_ASSERT(internalWinId());
1293 static int paintOnScreenEnv = -1;
1294 if (paintOnScreenEnv == -1)
1295 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1296 if (paintOnScreenEnv == 1)
1297 setAttribute(Qt::WA_PaintOnScreen);
1299 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1300 setAttribute(Qt::WA_NativeWindow);
1303 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1304 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1307 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1308 // Unregister the dropsite (if already registered) before we
1309 // re-create the widget with a native window.
1310 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1311 && d->extra && d->extra->dropTarget) {
1312 d->registerDropSite(false);
1314 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1316 d->updateIsOpaque();
1318 setAttribute(Qt::WA_WState_Created); // set created flag
1319 d->create_sys(window, initializeWindow, destroyOldWindow);
1321 // a real toplevel window needs a backing store
1322 if (isWindow() && windowType() != Qt::Desktop) {
1323 d->topData()->backingStoreTracker.destroy();
1324 if (hasBackingStoreSupport())
1325 d->topData()->backingStoreTracker.create(this);
1330 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1331 setAttribute(Qt::WA_DropSiteRegistered, true);
1334 extern void qt_eval_init_widget(QWidget *w);
1335 qt_eval_init_widget(this);
1338 // need to force the resting of the icon after changing parents
1339 if (testAttribute(Qt::WA_SetWindowIcon))
1340 d->setWindowIcon_sys(true);
1341 if (isWindow() && !d->topData()->iconText.isEmpty())
1342 d->setWindowIconText_helper(d->topData()->iconText);
1343 if (isWindow() && !d->topData()->caption.isEmpty())
1344 d->setWindowTitle_helper(d->topData()->caption);
1345 if (windowType() != Qt::Desktop) {
1346 d->updateSystemBackground();
1348 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1349 d->setWindowIcon_sys();
1354 Destroys the widget.
1356 All this widget's children are deleted first. The application
1357 exits if this widget is the main widget.
1363 d->data.in_destructor = true;
1365 #if defined (QT_CHECK_STATE)
1366 if (paintingActive())
1367 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1370 #ifndef QT_NO_GESTURES
1371 foreach (Qt::GestureType type, d->gestureContext.keys())
1372 ungrabGesture(type);
1375 // force acceptDrops false before winId is destroyed.
1376 d->registerDropSite(false);
1378 #ifndef QT_NO_ACTION
1379 // remove all actions from this widget
1380 for (int i = 0; i < d->actions.size(); ++i) {
1381 QActionPrivate *apriv = d->actions.at(i)->d_func();
1382 apriv->widgets.removeAll(this);
1387 #ifndef QT_NO_SHORTCUT
1388 // Remove all shortcuts grabbed by this
1389 // widget, unless application is closing
1390 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1391 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1394 // delete layout while we still are a valid widget
1397 // Remove myself from focus list
1399 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1400 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1402 if (d->focus_next != this) {
1403 d->focus_next->d_func()->focus_prev = d->focus_prev;
1404 d->focus_prev->d_func()->focus_next = d->focus_next;
1405 d->focus_next = d->focus_prev = 0;
1412 // swallow this problem because we are in a destructor
1415 d->setDirtyOpaqueRegion();
1417 if (isWindow() && isVisible() && internalWinId()) {
1419 d->close_helper(QWidgetPrivate::CloseNoEvent);
1421 // if we're out of memory, at least hide the window.
1425 // and if that also doesn't work, then give up
1430 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1431 else if (!internalWinId() && isVisible()) {
1432 qApp->d_func()->sendSyntheticEnterLeave(this);
1435 else if (isVisible()) {
1436 qApp->d_func()->sendSyntheticEnterLeave(this);
1439 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1440 bs->removeDirtyWidget(this);
1441 if (testAttribute(Qt::WA_StaticContents))
1442 bs->removeStaticWidget(this);
1445 delete d->needsFlush;
1448 if (d->declarativeData) {
1449 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1450 d->declarativeData = 0; // don't activate again in ~QObject
1454 // QCocoaView holds a pointer back to this widget. Clear it now
1455 // to make sure it's not followed later on. The lifetime of the
1456 // QCocoaView might exceed the lifetime of this widget in cases
1457 // where Cocoa itself holds references to it.
1458 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1459 qt_mac_clearCocoaViewQWidgetPointers(this);
1462 if (!d->children.isEmpty())
1463 d->deleteChildren();
1465 QApplication::removePostedEvents(this);
1468 destroy(); // platform-dependent cleanup
1470 // if this fails we can't do anything about it but at least we are not allowed to throw.
1472 --QWidgetPrivate::instanceCounter;
1474 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1475 QWidgetPrivate::allWidgets->remove(this);
1478 QEvent e(QEvent::Destroy);
1479 QCoreApplication::sendEvent(this, &e);
1480 } QT_CATCH(const std::exception&) {
1481 // if this fails we can't do anything about it but at least we are not allowed to throw.
1485 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1486 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1488 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1491 // the user might create a widget with Qt::Desktop window
1492 // attribute (or create another QDesktopWidget instance), which
1493 // will have the same windowid (the root window id) as the
1494 // qt_desktopWidget. We should not add the second desktop widget
1496 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1497 if (mapper && data.winid && !userDesktopWidget) {
1498 mapper->remove(data.winid);
1501 const WId oldWinId = data.winid;
1504 #if defined(Q_WS_X11)
1505 hd = id; // X11: hd == ident
1507 if (mapper && id && !userDesktopWidget) {
1508 mapper->insert(data.winid, q);
1511 if(oldWinId != id) {
1512 QEvent e(QEvent::WinIdChange);
1513 QCoreApplication::sendEvent(q, &e);
1517 void QWidgetPrivate::createTLExtra()
1521 if (!extra->topextra) {
1522 QTLWExtra* x = extra->topextra = new QTLWExtra;
1525 x->backingStore = 0;
1526 x->sharedPainter = 0;
1527 x->incw = x->inch = 0;
1528 x->basew = x->baseh = 0;
1529 x->frameStrut.setCoords(0, 0, 0, 0);
1530 x->normalGeometry = QRect(0,0,-1,-1);
1533 x->posFromMove = false;
1534 x->sizeAdjusted = false;
1535 x->inTopLevelResize = false;
1536 x->inRepaint = false;
1539 x->wasMaximized = false;
1542 #ifdef QWIDGET_EXTRA_DEBUG
1543 static int count = 0;
1544 qDebug() << "tlextra" << ++count;
1551 Creates the widget extra data.
1554 void QWidgetPrivate::createExtra()
1556 if (!extra) { // if not exists
1557 extra = new QWExtra;
1558 extra->glContext = 0;
1559 extra->topextra = 0;
1560 #ifndef QT_NO_GRAPHICSVIEW
1561 extra->proxyWidget = 0;
1563 #ifndef QT_NO_CURSOR
1568 extra->maxw = QWIDGETSIZE_MAX;
1569 extra->maxh = QWIDGETSIZE_MAX;
1570 extra->customDpiX = 0;
1571 extra->customDpiY = 0;
1572 extra->explicitMinSize = 0;
1573 extra->explicitMaxSize = 0;
1574 extra->autoFillBackground = 0;
1575 extra->nativeChildrenForced = 0;
1576 extra->inRenderWithPainter = 0;
1579 #ifdef QWIDGET_EXTRA_DEBUG
1580 static int count = 0;
1581 qDebug() << "extra" << ++count;
1589 Deletes the widget extra data.
1592 void QWidgetPrivate::deleteExtra()
1594 if (extra) { // if exists
1595 #ifndef QT_NO_CURSOR
1599 #ifndef QT_NO_STYLE_STYLESHEET
1600 // dereference the stylesheet style
1601 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1604 if (extra->topextra) {
1606 extra->topextra->backingStoreTracker.destroy();
1607 delete extra->topextra->icon;
1608 delete extra->topextra->iconPixmap;
1609 delete extra->topextra->backingStore;
1610 delete extra->topextra;
1613 // extra->xic destroyed in QWidget::destroy()
1619 Returns true if there are widgets above this which overlap with
1620 \a rect, which is in parent's coordinate system (same as crect).
1623 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1627 const QWidget *w = q;
1632 QWidgetPrivate *pd = w->parentWidget()->d_func();
1634 for (int i = 0; i < pd->children.size(); ++i) {
1635 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1636 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1639 above = (sibling == w);
1643 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1644 const QWExtra *siblingExtra = sibling->d_func()->extra;
1645 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1646 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1652 w = w->parentWidget();
1653 r.translate(pd->data.crect.topLeft());
1658 void QWidgetPrivate::syncBackingStore()
1660 if (paintOnScreen()) {
1663 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1668 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1670 if (paintOnScreen())
1671 repaint_sys(region);
1672 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1673 bs->sync(q_func(), region);
1677 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1681 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1682 return; // nothing we can do
1684 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1685 return; // nothing to do
1687 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1691 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1692 for (int i = 0; i < children.size(); ++i) {
1693 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1694 if (w && !w->isWindow() && !w->testAttribute(attribute))
1695 w->d_func()->setUpdatesEnabled_helper(enable);
1702 Propagate this widget's palette to all children, except style sheet
1703 widgets, and windows that don't enable window propagation (palettes don't
1704 normally propagate to windows).
1706 void QWidgetPrivate::propagatePaletteChange()
1709 // Propagate a new inherited mask to all children.
1710 #ifndef QT_NO_GRAPHICSVIEW
1711 if (!q->parentWidget() && extra && extra->proxyWidget) {
1712 QGraphicsProxyWidget *p = extra->proxyWidget;
1713 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1715 #endif //QT_NO_GRAPHICSVIEW
1716 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1717 inheritedPaletteResolveMask = 0;
1719 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1721 QEvent pc(QEvent::PaletteChange);
1722 QApplication::sendEvent(q, &pc);
1723 for (int i = 0; i < children.size(); ++i) {
1724 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1725 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1726 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1727 QWidgetPrivate *wd = w->d_func();
1728 wd->inheritedPaletteResolveMask = mask;
1729 wd->resolvePalette();
1735 Returns the widget's clipping rectangle.
1737 QRect QWidgetPrivate::clipRect() const
1740 const QWidget * w = q;
1741 if (!w->isVisible())
1743 QRect r = effectiveRectFor(q->rect());
1749 && w->parentWidget()) {
1752 w = w->parentWidget();
1753 r &= QRect(ox, oy, w->width(), w->height());
1759 Returns the widget's clipping region (without siblings).
1761 QRegion QWidgetPrivate::clipRegion() const
1764 if (!q->isVisible())
1766 QRegion r(q->rect());
1767 const QWidget * w = q;
1768 const QWidget *ignoreUpTo;
1774 && w->parentWidget()) {
1778 w = w->parentWidget();
1779 r &= QRegion(ox, oy, w->width(), w->height());
1782 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1784 for ( ; i < w->d_func()->children.size(); ++i) {
1785 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1786 if(sibling->isVisible() && !sibling->isWindow()) {
1787 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1788 sibling->width(), sibling->height());
1789 if (qRectIntersects(siblingRect, q->rect()))
1790 r -= QRegion(siblingRect);
1798 #ifndef QT_NO_GRAPHICSEFFECT
1799 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1804 if (w->graphicsEffect()) {
1805 QWidgetEffectSourcePrivate *sourced =
1806 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1807 if (!sourced->updateDueToGraphicsEffect)
1808 w->graphicsEffect()->source()->d_func()->invalidateCache();
1810 w = w->parentWidget();
1813 #endif //QT_NO_GRAPHICSEFFECT
1815 void QWidgetPrivate::setDirtyOpaqueRegion()
1819 dirtyOpaqueChildren = true;
1821 #ifndef QT_NO_GRAPHICSEFFECT
1822 invalidateGraphicsEffectsRecursively();
1823 #endif //QT_NO_GRAPHICSEFFECT
1828 QWidget *parent = q->parentWidget();
1832 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1833 QWidgetPrivate *pd = parent->d_func();
1834 if (!pd->dirtyOpaqueChildren)
1835 pd->setDirtyOpaqueRegion();
1838 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1840 if (!dirtyOpaqueChildren)
1841 return opaqueChildren;
1843 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1844 that->opaqueChildren = QRegion();
1846 for (int i = 0; i < children.size(); ++i) {
1847 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1848 if (!child || !child->isVisible() || child->isWindow())
1851 const QPoint offset = child->geometry().topLeft();
1852 QWidgetPrivate *childd = child->d_func();
1853 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1854 if (childd->extra && childd->extra->hasMask)
1855 r &= childd->extra->mask;
1858 r.translate(offset);
1859 that->opaqueChildren += r;
1862 that->opaqueChildren &= q_func()->rect();
1863 that->dirtyOpaqueChildren = false;
1865 return that->opaqueChildren;
1868 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1870 if (children.isEmpty() || clipRect.isEmpty())
1873 const QRegion &r = getOpaqueChildren();
1875 source -= (r & clipRect);
1878 //subtract any relatives that are higher up than me --- this is too expensive !!!
1879 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1880 bool alsoNonOpaque) const
1883 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1884 if (disableSubtractOpaqueSiblings || q->isWindow())
1888 if (q->d_func()->isInUnifiedToolbar)
1892 QRect clipBoundingRect;
1893 bool dirtyClipBoundingRect = true;
1896 bool dirtyParentClip = true;
1898 QPoint parentOffset = data.crect.topLeft();
1900 const QWidget *w = q;
1905 QWidgetPrivate *pd = w->parentWidget()->d_func();
1906 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1907 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1908 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1909 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1910 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1913 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1914 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1917 if (dirtyClipBoundingRect) {
1918 clipBoundingRect = sourceRegion.boundingRect();
1919 dirtyClipBoundingRect = false;
1922 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1925 if (dirtyParentClip) {
1926 parentClip = sourceRegion.translated(parentOffset);
1927 dirtyParentClip = false;
1930 const QPoint siblingPos(sibling->data->crect.topLeft());
1931 const QRect siblingClipRect(sibling->d_func()->clipRect());
1932 QRegion siblingDirty(parentClip);
1933 siblingDirty &= (siblingClipRect.translated(siblingPos));
1934 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1935 && !sibling->d_func()->graphicsEffect;
1937 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1938 if (siblingDirty.isEmpty())
1941 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1943 siblingDirty.translate(-parentOffset);
1944 sourceRegion -= siblingDirty;
1946 sourceRegion -= siblingGeometry.translated(-parentOffset);
1949 if (hasDirtySiblingsAbove)
1950 *hasDirtySiblingsAbove = true;
1951 if (sibling->d_func()->children.isEmpty())
1953 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1954 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1955 sourceRegion -= opaqueSiblingChildren;
1957 if (sourceRegion.isEmpty())
1960 dirtyClipBoundingRect = true;
1961 dirtyParentClip = true;
1964 w = w->parentWidget();
1965 parentOffset += pd->data.crect.topLeft();
1966 dirtyParentClip = true;
1970 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
1974 const QWidget *w = q;
1977 #ifndef QT_NO_GRAPHICSEFFECT
1978 if (graphicsEffect) {
1979 w = q->parentWidget();
1980 offset -= data.crect.topLeft();
1982 #endif //QT_NO_GRAPHICSEFFECT
1985 const QWidgetPrivate *wd = w->d_func();
1986 if (wd->extra && wd->extra->hasMask)
1987 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
1990 offset -= wd->data.crect.topLeft();
1991 w = w->parentWidget();
1995 bool QWidgetPrivate::paintOnScreen() const
1997 #if defined(QT_NO_BACKINGSTORE)
2001 if (q->testAttribute(Qt::WA_PaintOnScreen)
2002 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2006 return !qt_enable_backingstore;
2010 void QWidgetPrivate::updateIsOpaque()
2012 // hw: todo: only needed if opacity actually changed
2013 setDirtyOpaqueRegion();
2015 #ifndef QT_NO_GRAPHICSEFFECT
2016 if (graphicsEffect) {
2017 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2021 #endif //QT_NO_GRAPHICSEFFECT
2025 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2031 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2036 const QPalette &pal = q->palette();
2038 if (q->autoFillBackground()) {
2039 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2040 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2046 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2047 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2048 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2056 void QWidgetPrivate::setOpaque(bool opaque)
2058 if (isOpaque == opaque)
2062 macUpdateIsOpaque();
2065 x11UpdateIsOpaque();
2068 winUpdateIsOpaque();
2072 void QWidgetPrivate::updateIsTranslucent()
2075 macUpdateIsOpaque();
2078 x11UpdateIsOpaque();
2081 winUpdateIsOpaque();
2085 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2089 if (brush.style() == Qt::TexturePattern) {
2091 // Optimize pattern filling on mac by using HITheme directly
2092 // when filling with the standard widget background.
2093 // Defined in qmacstyle_mac.cpp
2094 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2095 qt_mac_fill_background(painter, rgn, brush);
2098 const QRect rect(rgn.boundingRect());
2099 painter->setClipRegion(rgn);
2100 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2104 } else if (brush.gradient()
2105 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2107 painter->setClipRegion(rgn);
2108 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2111 const QVector<QRect> &rects = rgn.rects();
2112 for (int i = 0; i < rects.size(); ++i)
2113 painter->fillRect(rects.at(i), brush);
2117 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2121 #ifndef QT_NO_SCROLLAREA
2122 bool resetBrushOrigin = false;
2123 QPointF oldBrushOrigin;
2124 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2125 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2126 if (scrollArea && scrollArea->viewport() == q) {
2127 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2128 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2129 oldBrushOrigin = painter->brushOrigin();
2130 resetBrushOrigin = true;
2131 painter->setBrushOrigin(-priv->contentsOffset());
2134 #endif // QT_NO_SCROLLAREA
2136 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2138 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2139 const QBrush bg = q->palette().brush(QPalette::Window);
2140 if (!(flags & DontSetCompositionMode)) {
2141 //copy alpha straight in
2142 QPainter::CompositionMode oldMode = painter->compositionMode();
2143 painter->setCompositionMode(QPainter::CompositionMode_Source);
2144 fillRegion(painter, rgn, bg);
2145 painter->setCompositionMode(oldMode);
2147 fillRegion(painter, rgn, bg);
2151 if (q->autoFillBackground())
2152 fillRegion(painter, rgn, autoFillBrush);
2154 if (q->testAttribute(Qt::WA_StyledBackground)) {
2155 painter->setClipRegion(rgn);
2158 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2161 #ifndef QT_NO_SCROLLAREA
2162 if (resetBrushOrigin)
2163 painter->setBrushOrigin(oldBrushOrigin);
2164 #endif // QT_NO_SCROLLAREA
2169 This function is called when a widget is hidden or destroyed.
2170 It resets some application global pointers that should only refer active,
2175 extern QPointer<QWidget> qt_button_down;
2177 extern QWidget *qt_button_down;
2180 void QWidgetPrivate::deactivateWidgetCleanup()
2183 // If this was the active application window, reset it
2184 if (QApplication::activeWindow() == q)
2185 QApplication::setActiveWindow(0);
2186 // If the is the active mouse press widget, reset it
2187 if (q == qt_button_down)
2193 Returns a pointer to the widget with window identifer/handle \a
2196 The window identifier type depends on the underlying window
2197 system, see \c qwindowdefs.h for the actual definition. If there
2198 is no widget with this identifier, 0 is returned.
2201 QWidget *QWidget::find(WId id)
2203 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2209 \fn WId QWidget::internalWinId() const
2211 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2216 \fn WId QWidget::winId() const
2218 Returns the window system identifier of the widget.
2220 Portable in principle, but if you use it you are probably about to
2221 do something non-portable. Be careful.
2223 If a widget is non-native (alien) and winId() is invoked on it, that widget
2224 will be provided a native handle.
2226 On Mac OS X, the type returned depends on which framework Qt was linked
2227 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2228 is using Cocoa, {WId} is a pointer to an NSView.
2230 This value may change at run-time. An event with type QEvent::WinIdChange
2231 will be sent to the widget following a change in window system identifier.
2235 WId QWidget::winId() const
2237 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2239 qDebug() << "QWidget::winId: creating native window for" << this;
2241 QWidget *that = const_cast<QWidget*>(this);
2242 that->setAttribute(Qt::WA_NativeWindow);
2243 that->d_func()->createWinId();
2244 return that->data->winid;
2250 void QWidgetPrivate::createWinId(WId winid)
2255 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2257 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2258 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2259 if (!q->isWindow()) {
2260 QWidget *parent = q->parentWidget();
2261 QWidgetPrivate *pd = parent->d_func();
2262 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2263 parent->setAttribute(Qt::WA_NativeWindow);
2264 if (!parent->internalWinId()) {
2268 for (int i = 0; i < pd->children.size(); ++i) {
2269 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2270 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2271 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2276 // if the window has already been created, we
2277 // need to raise it to its proper stacking position
2292 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2296 void QWidget::createWinId()
2300 qDebug() << "QWidget::createWinId" << this;
2302 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2309 Returns the effective window system identifier of the widget, i.e. the
2310 native parent's window system identifier.
2312 If the widget is native, this function returns the native widget ID.
2313 Otherwise, the window ID of the first native parent widget, i.e., the
2314 top-level widget that contains this widget, is returned.
2316 \note We recommend that you do not store this value as it is likely to
2319 \sa nativeParentWidget()
2321 WId QWidget::effectiveWinId() const
2323 WId id = internalWinId();
2324 if (id || !testAttribute(Qt::WA_WState_Created))
2326 QWidget *realParent = nativeParentWidget();
2327 if (!realParent && d_func()->inSetParent) {
2328 // In transitional state. This is really just a workaround. The real problem
2329 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2330 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2331 // attribute to false. The correct way is to do it the other way around, and
2332 // in that case the Qt::WA_WState_Created logic above will kick in and
2333 // return 0 whenever the widget is in a transitional state. However, changing
2334 // the original logic for all platforms is far more intrusive and might
2335 // break existing applications.
2336 // Note: The widget can only be in a transitional state when changing its
2337 // parent -- everything else is an internal error -- hence explicitly checking
2338 // against 'inSetParent' rather than doing an unconditional return whenever
2339 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2342 // This widget *must* have a native parent widget.
2343 Q_ASSERT(realParent);
2344 Q_ASSERT(realParent->internalWinId());
2345 return realParent->internalWinId();
2348 #ifndef QT_NO_STYLE_STYLESHEET
2351 \property QWidget::styleSheet
2352 \brief the widget's style sheet
2355 The style sheet contains a textual description of customizations to the
2356 widget's style, as described in the \l{Qt Style Sheets} document.
2358 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2360 \warning Qt style sheets are currently not supported for custom QStyle
2361 subclasses. We plan to address this in some future release.
2363 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2365 QString QWidget::styleSheet() const
2370 return d->extra->styleSheet;
2373 void QWidget::setStyleSheet(const QString& styleSheet)
2378 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2379 d->extra->styleSheet = styleSheet;
2380 if (styleSheet.isEmpty()) { // stylesheet removed
2388 if (proxy) { // style sheet update
2389 proxy->repolish(this);
2393 if (testAttribute(Qt::WA_SetStyle)) {
2394 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2396 d->setStyle_helper(new QStyleSheetStyle(0), true);
2400 #endif // QT_NO_STYLE_STYLESHEET
2403 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2406 QStyle *QWidget::style() const
2410 if (d->extra && d->extra->style)
2411 return d->extra->style;
2412 return QApplication::style();
2416 Sets the widget's GUI style to \a style. The ownership of the style
2417 object is not transferred.
2419 If no style is set, the widget uses the application's style,
2420 QApplication::style() instead.
2422 Setting a widget's style has no effect on existing or future child
2425 \warning This function is particularly useful for demonstration
2426 purposes, where you want to show Qt's styling capabilities. Real
2427 applications should avoid it and use one consistent GUI style
2430 \warning Qt style sheets are currently not supported for custom QStyle
2431 subclasses. We plan to address this in some future release.
2433 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2436 void QWidget::setStyle(QStyle *style)
2439 setAttribute(Qt::WA_SetStyle, style != 0);
2441 #ifndef QT_NO_STYLE_STYLESHEET
2442 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2443 //if for some reason someone try to set a QStyleSheetStyle, ref it
2444 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2446 d->setStyle_helper(style, false);
2447 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2448 // if we have an application stylesheet or have a proxy already, propagate
2449 d->setStyle_helper(new QStyleSheetStyle(style), true);
2452 d->setStyle_helper(style, false);
2455 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2462 QStyle *oldStyle = q->style();
2463 #ifndef QT_NO_STYLE_STYLESHEET
2464 QWeakPointer<QStyle> origStyle;
2468 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2469 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2470 // set when changing that attribute and passes the widget's CURRENT style.
2471 // therefore no need to do a reassignment.
2477 #ifndef QT_NO_STYLE_STYLESHEET
2478 origStyle = extra->style.data();
2480 extra->style = newStyle;
2484 if (q->windowType() != Qt::Desktop) {
2486 oldStyle->unpolish(q);
2489 macUpdateMetalAttribute();
2491 q->style()->polish(q);
2493 } else if (metalHack) {
2494 macUpdateMetalAttribute();
2500 for (int i = 0; i < children.size(); ++i) {
2501 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2503 c->d_func()->inheritStyle();
2507 #ifndef QT_NO_STYLE_STYLESHEET
2508 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2509 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2510 cssStyle->clearWidgetFont(q);
2515 QEvent e(QEvent::StyleChange);
2516 QApplication::sendEvent(q, &e);
2518 #ifndef QT_NO_STYLE_STYLESHEET
2519 // dereference the old stylesheet style
2520 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2525 // Inherits style from the current parent and propagates it as necessary
2526 void QWidgetPrivate::inheritStyle()
2528 #ifndef QT_NO_STYLE_STYLESHEET
2531 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2533 if (!q->styleSheet().isEmpty()) {
2539 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2540 QWidget *parent = q->parentWidget();
2541 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2542 // If we have stylesheet on app or parent has stylesheet style, we need
2543 // to be running a proxy
2544 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2545 QStyle *newStyle = parentStyle;
2546 if (q->testAttribute(Qt::WA_SetStyle))
2547 newStyle = new QStyleSheetStyle(origStyle);
2548 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2551 setStyle_helper(newStyle, true);
2555 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2556 // we just need our original style back
2557 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2560 // We could have inherited the proxy from our parent (which has a custom style)
2561 // In such a case we need to start following the application style (i.e revert
2562 // the propagation behavior of QStyleSheetStyle)
2563 if (!q->testAttribute(Qt::WA_SetStyle))
2566 setStyle_helper(origStyle, true);
2567 #endif // QT_NO_STYLE_STYLESHEET
2572 \fn bool QWidget::isWindow() const
2574 Returns true if the widget is an independent window, otherwise
2577 A window is a widget that isn't visually the child of any other
2578 widget and that usually has a frame and a
2579 \l{QWidget::setWindowTitle()}{window title}.
2581 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2582 It will then be grouped with its parent and deleted when the
2583 parent is deleted, minimized when the parent is minimized etc. If
2584 supported by the window manager, it will also have a common
2585 taskbar entry with its parent.
2587 QDialog and QMainWindow widgets are by default windows, even if a
2588 parent widget is specified in the constructor. This behavior is
2589 specified by the Qt::Window flag.
2591 \sa window(), isModal(), parentWidget()
2595 \property QWidget::modal
2596 \brief whether the widget is a modal widget
2598 This property only makes sense for windows. A modal widget
2599 prevents widgets in all other windows from getting any input.
2601 By default, this property is false.
2603 \sa isWindow(), windowModality, QDialog
2607 \property QWidget::windowModality
2608 \brief which windows are blocked by the modal widget
2611 This property only makes sense for windows. A modal widget
2612 prevents widgets in other windows from getting input. The value of
2613 this property controls which windows are blocked when the widget
2614 is visible. Changing this property while the window is visible has
2615 no effect; you must hide() the widget first, then show() it again.
2617 By default, this property is Qt::NonModal.
2619 \sa isWindow(), QWidget::modal, QDialog
2622 Qt::WindowModality QWidget::windowModality() const
2624 return static_cast<Qt::WindowModality>(data->window_modality);
2627 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2629 data->window_modality = windowModality;
2630 // setModal_sys() will be called by setAttribute()
2631 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2632 setAttribute(Qt::WA_SetWindowModality, true);
2636 \fn bool QWidget::underMouse() const
2638 Returns true if the widget is under the mouse cursor; otherwise
2641 This value is not updated properly during drag and drop
2644 \sa enterEvent(), leaveEvent()
2648 \property QWidget::minimized
2649 \brief whether this widget is minimized (iconified)
2651 This property is only relevant for windows.
2653 By default, this property is false.
2655 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2657 bool QWidget::isMinimized() const
2658 { return data->window_state & Qt::WindowMinimized; }
2661 Shows the widget minimized, as an icon.
2663 Calling this function only affects \l{isWindow()}{windows}.
2665 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2668 void QWidget::showMinimized()
2670 bool isMin = isMinimized();
2671 if (isMin && isVisible())
2677 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2682 \property QWidget::maximized
2683 \brief whether this widget is maximized
2685 This property is only relevant for windows.
2687 \note Due to limitations on some window systems, this does not always
2688 report the expected results (e.g., if the user on X11 maximizes the
2689 window via the window manager, Qt has no way of distinguishing this
2690 from any other resize). This is expected to improve as window manager
2693 By default, this property is false.
2695 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2697 bool QWidget::isMaximized() const
2698 { return data->window_state & Qt::WindowMaximized; }
2703 Returns the current window state. The window state is a OR'ed
2704 combination of Qt::WindowState: Qt::WindowMinimized,
2705 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2707 \sa Qt::WindowState setWindowState()
2709 Qt::WindowStates QWidget::windowState() const
2711 return Qt::WindowStates(data->window_state);
2716 The function sets the window state on child widgets similar to
2717 setWindowState(). The difference is that the window state changed
2718 event has the isOverride() flag set. It exists mainly to keep
2721 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2723 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2724 data->window_state = newstate;
2725 QApplication::sendEvent(this, &e);
2729 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2731 Sets the window state to \a windowState. The window state is a OR'ed
2732 combination of Qt::WindowState: Qt::WindowMinimized,
2733 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2735 If the window is not visible (i.e. isVisible() returns false), the
2736 window state will take effect when show() is called. For visible
2737 windows, the change is immediate. For example, to toggle between
2738 full-screen and normal mode, use the following code:
2740 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2742 In order to restore and activate a minimized window (while
2743 preserving its maximized and/or full-screen state), use the following:
2745 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2747 Calling this function will hide the widget. You must call show() to make
2748 the widget visible again.
2750 \note On some window systems Qt::WindowActive is not immediate, and may be
2751 ignored in certain cases.
2753 When the window state changes, the widget receives a changeEvent()
2754 of type QEvent::WindowStateChange.
2756 \sa Qt::WindowState windowState()
2760 \property QWidget::fullScreen
2761 \brief whether the widget is shown in full screen mode
2763 A widget in full screen mode occupies the whole screen area and does not
2764 display window decorations, such as a title bar.
2766 By default, this property is false.
2768 \sa windowState(), minimized, maximized
2770 bool QWidget::isFullScreen() const
2771 { return data->window_state & Qt::WindowFullScreen; }
2774 Shows the widget in full-screen mode.
2776 Calling this function only affects \l{isWindow()}{windows}.
2778 To return from full-screen mode, call showNormal().
2780 Full-screen mode works fine under Windows, but has certain
2781 problems under X. These problems are due to limitations of the
2782 ICCCM protocol that specifies the communication between X11
2783 clients and the window manager. ICCCM simply does not understand
2784 the concept of non-decorated full-screen windows. Therefore, the
2785 best we can do is to request a borderless window and place and
2786 resize it to fill the entire screen. Depending on the window
2787 manager, this may or may not work. The borderless window is
2788 requested using MOTIF hints, which are at least partially
2789 supported by virtually all modern window managers.
2791 An alternative would be to bypass the window manager entirely and
2792 create a window with the Qt::X11BypassWindowManagerHint flag. This
2793 has other severe problems though, like totally broken keyboard focus
2794 and very strange effects on desktop changes or when the user raises
2797 X11 window managers that follow modern post-ICCCM specifications
2798 support full-screen mode properly.
2800 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2802 void QWidget::showFullScreen()
2805 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2806 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2807 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2808 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2809 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2810 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2815 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2816 | Qt::WindowFullScreen);
2822 Shows the widget maximized.
2824 Calling this function only affects \l{isWindow()}{windows}.
2826 On X11, this function may not work properly with certain window
2827 managers. See the \l{Window Geometry} documentation for an explanation.
2829 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2831 void QWidget::showMaximized()
2835 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2836 | Qt::WindowMaximized);
2838 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2839 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2842 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2843 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2844 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2845 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2853 Restores the widget after it has been maximized or minimized.
2855 Calling this function only affects \l{isWindow()}{windows}.
2857 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2859 void QWidget::showNormal()
2863 setWindowState(windowState() & ~(Qt::WindowMinimized
2864 | Qt::WindowMaximized
2865 | Qt::WindowFullScreen));
2867 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2868 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2871 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2872 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2873 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2874 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2882 Returns true if this widget would become enabled if \a ancestor is
2883 enabled; otherwise returns false.
2887 This is the case if neither the widget itself nor every parent up
2888 to but excluding \a ancestor has been explicitly disabled.
2890 isEnabledTo(0) is equivalent to isEnabled().
2892 \sa setEnabled() enabled
2895 bool QWidget::isEnabledTo(QWidget* ancestor) const
2897 const QWidget * w = this;
2898 while (!w->testAttribute(Qt::WA_ForceDisabled)
2900 && w->parentWidget()
2901 && w->parentWidget() != ancestor)
2902 w = w->parentWidget();
2903 return !w->testAttribute(Qt::WA_ForceDisabled);
2906 #ifndef QT_NO_ACTION
2908 Appends the action \a action to this widget's list of actions.
2910 All QWidgets have a list of \l{QAction}s, however they can be
2911 represented graphically in many different ways. The default use of
2912 the QAction list (as returned by actions()) is to create a context
2915 A QWidget should only have one of each action and adding an action
2916 it already has will not cause the same action to be in the widget twice.
2918 The ownership of \a action is not transferred to this QWidget.
2920 \sa removeAction(), insertAction(), actions(), QMenu
2922 void QWidget::addAction(QAction *action)
2924 insertAction(0, action);
2928 Appends the actions \a actions to this widget's list of actions.
2930 \sa removeAction(), QMenu, addAction()
2932 void QWidget::addActions(QList<QAction*> actions)
2934 for(int i = 0; i < actions.count(); i++)
2935 insertAction(0, actions.at(i));
2939 Inserts the action \a action to this widget's list of actions,
2940 before the action \a before. It appends the action if \a before is 0 or
2941 \a before is not a valid action for this widget.
2943 A QWidget should only have one of each action.
2945 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2947 void QWidget::insertAction(QAction *before, QAction *action)
2950 qWarning("QWidget::insertAction: Attempt to insert null action");
2955 if(d->actions.contains(action))
2956 removeAction(action);
2958 int pos = d->actions.indexOf(before);
2961 pos = d->actions.size();
2963 d->actions.insert(pos, action);
2965 QActionPrivate *apriv = action->d_func();
2966 apriv->widgets.append(this);
2968 QActionEvent e(QEvent::ActionAdded, action, before);
2969 QApplication::sendEvent(this, &e);
2973 Inserts the actions \a actions to this widget's list of actions,
2974 before the action \a before. It appends the action if \a before is 0 or
2975 \a before is not a valid action for this widget.
2977 A QWidget can have at most one of each action.
2979 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2981 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2983 for(int i = 0; i < actions.count(); ++i)
2984 insertAction(before, actions.at(i));
2988 Removes the action \a action from this widget's list of actions.
2989 \sa insertAction(), actions(), insertAction()
2991 void QWidget::removeAction(QAction *action)
2998 QActionPrivate *apriv = action->d_func();
2999 apriv->widgets.removeAll(this);
3001 if (d->actions.removeAll(action)) {
3002 QActionEvent e(QEvent::ActionRemoved, action);
3003 QApplication::sendEvent(this, &e);
3008 Returns the (possibly empty) list of this widget's actions.
3010 \sa contextMenuPolicy, insertAction(), removeAction()
3012 QList<QAction*> QWidget::actions() const
3017 #endif // QT_NO_ACTION
3020 \fn bool QWidget::isEnabledToTLW() const
3023 This function is deprecated. It is equivalent to isEnabled()
3027 \property QWidget::enabled
3028 \brief whether the widget is enabled
3030 In general an enabled widget handles keyboard and mouse events; a disabled
3031 widget does not. An exception is made with \l{QAbstractButton}.
3033 Some widgets display themselves differently when they are
3034 disabled. For example a button might draw its label grayed out. If
3035 your widget needs to know when it becomes enabled or disabled, you
3036 can use the changeEvent() with type QEvent::EnabledChange.
3038 Disabling a widget implicitly disables all its children. Enabling
3039 respectively enables all child widgets unless they have been
3040 explicitly disabled.
3042 By default, this property is true.
3044 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3046 void QWidget::setEnabled(bool enable)
3049 setAttribute(Qt::WA_ForceDisabled, !enable);
3050 d->setEnabled_helper(enable);
3053 void QWidgetPrivate::setEnabled_helper(bool enable)
3057 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3058 return; // nothing we can do
3060 if (enable != q->testAttribute(Qt::WA_Disabled))
3061 return; // nothing to do
3063 q->setAttribute(Qt::WA_Disabled, !enable);
3064 updateSystemBackground();
3066 if (!enable && q->window()->focusWidget() == q) {
3067 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3068 if (!parentIsEnabled || !q->focusNextChild())
3072 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3073 for (int i = 0; i < children.size(); ++i) {
3074 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3075 if (w && !w->testAttribute(attribute))
3076 w->d_func()->setEnabled_helper(enable);
3078 #if defined(Q_WS_X11)
3079 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3080 // enforce the windows behavior of clearing the cursor on
3082 qt_x11_enforce_cursor(q);
3085 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3086 // enforce the windows behavior of clearing the cursor on
3088 qt_qpa_set_cursor(q, false);
3090 #if defined(Q_WS_MAC)
3091 setEnabled_helper_sys(enable);
3094 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3095 QWidget *focusWidget = effectiveFocusWidget();
3098 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3099 qApp->inputMethod()->update(Qt::ImEnabled);
3101 qApp->inputMethod()->commit();
3102 qApp->inputMethod()->update(Qt::ImEnabled);
3106 QEvent e(QEvent::EnabledChange);
3107 QApplication::sendEvent(q, &e);
3111 \property QWidget::acceptDrops
3112 \brief whether drop events are enabled for this widget
3114 Setting this property to true announces to the system that this
3115 widget \e may be able to accept drop events.
3117 If the widget is the desktop (windowType() == Qt::Desktop), this may
3118 fail if another application is using the desktop; you can call
3119 acceptDrops() to test if this occurs.
3121 \warning Do not modify this property in a drag and drop event handler.
3123 By default, this property is false.
3127 bool QWidget::acceptDrops() const
3129 return testAttribute(Qt::WA_AcceptDrops);
3132 void QWidget::setAcceptDrops(bool on)
3134 setAttribute(Qt::WA_AcceptDrops, on);
3140 Disables widget input events if \a disable is true; otherwise
3141 enables input events.
3143 See the \l enabled documentation for more information.
3145 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3147 void QWidget::setDisabled(bool disable)
3149 setEnabled(!disable);
3153 \property QWidget::frameGeometry
3154 \brief geometry of the widget relative to its parent including any
3157 See the \l{Window Geometry} documentation for an overview of geometry
3158 issues with windows.
3160 By default, this property contains a value that depends on the user's
3161 platform and screen geometry.
3163 \sa geometry() x() y() pos()
3165 QRect QWidget::frameGeometry() const
3168 if (isWindow() && ! (windowType() == Qt::Popup)) {
3169 QRect fs = d->frameStrut();
3170 return QRect(data->crect.x() - fs.left(),
3171 data->crect.y() - fs.top(),
3172 data->crect.width() + fs.left() + fs.right(),
3173 data->crect.height() + fs.top() + fs.bottom());
3179 \property QWidget::x
3181 \brief the x coordinate of the widget relative to its parent including
3184 See the \l{Window Geometry} documentation for an overview of geometry
3185 issues with windows.
3187 By default, this property has a value of 0.
3189 \sa frameGeometry, y, pos
3191 int QWidget::x() const
3194 if (isWindow() && ! (windowType() == Qt::Popup))
3195 return data->crect.x() - d->frameStrut().left();
3196 return data->crect.x();
3200 \property QWidget::y
3201 \brief the y coordinate of the widget relative to its parent and
3202 including any window frame
3204 See the \l{Window Geometry} documentation for an overview of geometry
3205 issues with windows.
3207 By default, this property has a value of 0.
3209 \sa frameGeometry, x, pos
3211 int QWidget::y() const
3214 if (isWindow() && ! (windowType() == Qt::Popup))
3215 return data->crect.y() - d->frameStrut().top();
3216 return data->crect.y();
3220 \property QWidget::pos
3221 \brief the position of the widget within its parent widget
3223 If the widget is a window, the position is that of the widget on
3224 the desktop, including its frame.
3226 When changing the position, the widget, if visible, receives a
3227 move event (moveEvent()) immediately. If the widget is not
3228 currently visible, it is guaranteed to receive an event before it
3231 By default, this property contains a position that refers to the
3234 \warning Calling move() or setGeometry() inside moveEvent() can
3235 lead to infinite recursion.
3237 See the \l{Window Geometry} documentation for an overview of geometry
3238 issues with windows.
3240 \sa frameGeometry, size x(), y()
3242 QPoint QWidget::pos() const
3245 if (isWindow() && ! (windowType() == Qt::Popup)) {
3246 QRect fs = d->frameStrut();
3247 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3249 return data->crect.topLeft();
3253 \property QWidget::geometry
3254 \brief the geometry of the widget relative to its parent and
3255 excluding the window frame
3257 When changing the geometry, the widget, if visible, receives a
3258 move event (moveEvent()) and/or a resize event (resizeEvent())
3259 immediately. If the widget is not currently visible, it is
3260 guaranteed to receive appropriate events before it is shown.
3262 The size component is adjusted if it lies outside the range
3263 defined by minimumSize() and maximumSize().
3265 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3266 can lead to infinite recursion.
3268 See the \l{Window Geometry} documentation for an overview of geometry
3269 issues with windows.
3271 By default, this property contains a value that depends on the user's
3272 platform and screen geometry.
3274 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3275 resizeEvent(), minimumSize(), maximumSize()
3279 \property QWidget::normalGeometry
3281 \brief the geometry of the widget as it will appear when shown as
3282 a normal (not maximized or full screen) top-level widget
3284 For child widgets this property always holds an empty rectangle.
3286 By default, this property contains an empty rectangle.
3288 \sa QWidget::windowState(), QWidget::geometry
3292 \property QWidget::size
3293 \brief the size of the widget excluding any window frame
3295 If the widget is visible when it is being resized, it receives a resize event
3296 (resizeEvent()) immediately. If the widget is not currently
3297 visible, it is guaranteed to receive an event before it is shown.
3299 The size is adjusted if it lies outside the range defined by
3300 minimumSize() and maximumSize().
3302 By default, this property contains a value that depends on the user's
3303 platform and screen geometry.
3305 \warning Calling resize() or setGeometry() inside resizeEvent() can
3306 lead to infinite recursion.
3308 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3309 appear on screen. This also applies to windows.
3311 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3315 \property QWidget::width
3316 \brief the width of the widget excluding any window frame
3318 See the \l{Window Geometry} documentation for an overview of geometry
3319 issues with windows.
3321 \note Do not use this function to find the width of a screen on
3322 a \l{QDesktopWidget}{multiple screen desktop}. Read
3323 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3325 By default, this property contains a value that depends on the user's
3326 platform and screen geometry.
3328 \sa geometry, height, size
3332 \property QWidget::height
3333 \brief the height of the widget excluding any window frame
3335 See the \l{Window Geometry} documentation for an overview of geometry
3336 issues with windows.
3338 \note Do not use this function to find the height of a screen
3339 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3340 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3342 By default, this property contains a value that depends on the user's
3343 platform and screen geometry.
3345 \sa geometry, width, size
3349 \property QWidget::rect
3350 \brief the internal geometry of the widget excluding any window
3353 The rect property equals QRect(0, 0, width(), height()).
3355 See the \l{Window Geometry} documentation for an overview of geometry
3356 issues with windows.
3358 By default, this property contains a value that depends on the user's
3359 platform and screen geometry.
3365 QRect QWidget::normalGeometry() const
3368 if (!d->extra || !d->extra->topextra)
3371 if (!isMaximized() && !isFullScreen())
3374 return d->topData()->normalGeometry;
3379 \property QWidget::childrenRect
3380 \brief the bounding rectangle of the widget's children
3382 Hidden children are excluded.
3384 By default, for a widget with no children, this property contains a
3385 rectangle with zero width and height located at the origin.
3387 \sa childrenRegion() geometry()
3390 QRect QWidget::childrenRect() const
3393 QRect r(0, 0, 0, 0);
3394 for (int i = 0; i < d->children.size(); ++i) {
3395 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3396 if (w && !w->isWindow() && !w->isHidden())
3403 \property QWidget::childrenRegion
3404 \brief the combined region occupied by the widget's children
3406 Hidden children are excluded.
3408 By default, for a widget with no children, this property contains an
3411 \sa childrenRect() geometry() mask()
3414 QRegion QWidget::childrenRegion() const
3418 for (int i = 0; i < d->children.size(); ++i) {
3419 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3420 if (w && !w->isWindow() && !w->isHidden()) {
3421 QRegion mask = w->mask();
3425 r |= mask.translated(w->pos());
3433 \property QWidget::minimumSize
3434 \brief the widget's minimum size
3436 The widget cannot be resized to a smaller size than the minimum
3437 widget size. The widget's size is forced to the minimum size if
3438 the current size is smaller.
3440 The minimum size set by this function will override the minimum size
3441 defined by QLayout. In order to unset the minimum size, use a
3442 value of \c{QSize(0, 0)}.
3444 By default, this property contains a size with zero width and height.
3446 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3449 QSize QWidget::minimumSize() const
3452 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3456 \property QWidget::maximumSize
3457 \brief the widget's maximum size in pixels
3459 The widget cannot be resized to a larger size than the maximum
3462 By default, this property contains a size in which both width and height
3463 have values of 16777215.
3465 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3468 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3471 QSize QWidget::maximumSize() const
3474 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3475 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3480 \property QWidget::minimumWidth
3481 \brief the widget's minimum width in pixels
3483 This property corresponds to the width held by the \l minimumSize property.
3485 By default, this property has a value of 0.
3487 \sa minimumSize, minimumHeight
3491 \property QWidget::minimumHeight
3492 \brief the widget's minimum height in pixels
3494 This property corresponds to the height held by the \l minimumSize property.
3496 By default, this property has a value of 0.
3498 \sa minimumSize, minimumWidth
3502 \property QWidget::maximumWidth
3503 \brief the widget's maximum width in pixels
3505 This property corresponds to the width held by the \l maximumSize property.
3507 By default, this property contains a value of 16777215.
3509 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3512 \sa maximumSize, maximumHeight
3516 \property QWidget::maximumHeight
3517 \brief the widget's maximum height in pixels
3519 This property corresponds to the height held by the \l maximumSize property.
3521 By default, this property contains a value of 16777215.
3523 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3526 \sa maximumSize, maximumWidth
3530 \property QWidget::sizeIncrement
3531 \brief the size increment of the widget
3533 When the user resizes the window, the size will move in steps of
3534 sizeIncrement().width() pixels horizontally and
3535 sizeIncrement.height() pixels vertically, with baseSize() as the
3536 basis. Preferred widget sizes are for non-negative integers \e i
3538 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3540 Note that while you can set the size increment for all widgets, it
3541 only affects windows.
3543 By default, this property contains a size with zero width and height.
3545 \warning The size increment has no effect under Windows, and may
3546 be disregarded by the window manager on X11.
3548 \sa size, minimumSize, maximumSize
3550 QSize QWidget::sizeIncrement() const
3553 return (d->extra && d->extra->topextra)
3554 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3559 \property QWidget::baseSize
3560 \brief the base size of the widget
3562 The base size is used to calculate a proper widget size if the
3563 widget defines sizeIncrement().
3565 By default, for a newly-created widget, this property contains a size with
3566 zero width and height.
3568 \sa setSizeIncrement()
3571 QSize QWidget::baseSize() const
3574 return (d->extra != 0 && d->extra->topextra != 0)
3575 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3579 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3583 int mw = minw, mh = minh;
3584 if (mw == QWIDGETSIZE_MAX)
3586 if (mh == QWIDGETSIZE_MAX)
3588 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3589 qWarning("QWidget::setMinimumSize: (%s/%s) "
3590 "The largest allowed size is (%d,%d)",
3591 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3593 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3594 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3596 if (minw < 0 || minh < 0) {
3597 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3599 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3600 minw = mw = qMax(minw, 0);
3601 minh = mh = qMax(minh, 0);
3604 if (extra->minw == mw && extra->minh == mh)
3608 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3615 This function corresponds to setMinimumSize(QSize(minw, minh)).
3616 Sets the minimum width to \a minw and the minimum height to \a
3620 void QWidget::setMinimumSize(int minw, int minh)
3623 if (!d->setMinimumSize_helper(minw, minh))
3627 d->setConstraints_sys();
3628 if (minw > width() || minh > height()) {
3629 bool resized = testAttribute(Qt::WA_Resized);
3630 bool maximized = isMaximized();
3631 resize(qMax(minw,width()), qMax(minh,height()));
3632 setAttribute(Qt::WA_Resized, resized); //not a user resize
3634 data->window_state = data->window_state | Qt::WindowMaximized;
3636 #ifndef QT_NO_GRAPHICSVIEW
3638 if (d->extra->proxyWidget)
3639 d->extra->proxyWidget->setMinimumSize(minw, minh);
3642 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3645 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3648 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3649 qWarning("QWidget::setMaximumSize: (%s/%s) "
3650 "The largest allowed size is (%d,%d)",
3651 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3653 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3654 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3656 if (maxw < 0 || maxh < 0) {
3657 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3659 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3660 maxw = qMax(maxw, 0);
3661 maxh = qMax(maxh, 0);
3664 if (extra->maxw == maxw && extra->maxh == maxh)
3668 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3669 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3676 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3677 maxh)). Sets the maximum width to \a maxw and the maximum height
3680 void QWidget::setMaximumSize(int maxw, int maxh)
3683 if (!d->setMaximumSize_helper(maxw, maxh))
3687 d->setConstraints_sys();
3688 if (maxw < width() || maxh < height()) {
3689 bool resized = testAttribute(Qt::WA_Resized);
3690 resize(qMin(maxw,width()), qMin(maxh,height()));
3691 setAttribute(Qt::WA_Resized, resized); //not a user resize
3694 #ifndef QT_NO_GRAPHICSVIEW
3696 if (d->extra->proxyWidget)
3697 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3701 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3707 Sets the x (width) size increment to \a w and the y (height) size
3710 void QWidget::setSizeIncrement(int w, int h)
3714 QTLWExtra* x = d->topData();
3715 if (x->incw == w && x->inch == h)
3720 d->setConstraints_sys();
3726 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3727 the widgets base size to width \a basew and height \a baseh.
3729 void QWidget::setBaseSize(int basew, int baseh)
3733 QTLWExtra* x = d->topData();
3734 if (x->basew == basew && x->baseh == baseh)
3739 d->setConstraints_sys();
3743 Sets both the minimum and maximum sizes of the widget to \a s,
3744 thereby preventing it from ever growing or shrinking.
3746 This will override the default size constraints set by QLayout.
3748 To remove constraints, set the size to QWIDGETSIZE_MAX.
3750 Alternatively, if you want the widget to have a
3751 fixed size based on its contents, you can call
3752 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3754 \sa maximumSize, minimumSize
3757 void QWidget::setFixedSize(const QSize & s)
3759 setFixedSize(s.width(), s.height());
3764 \fn void QWidget::setFixedSize(int w, int h)
3767 Sets the width of the widget to \a w and the height to \a h.
3770 void QWidget::setFixedSize(int w, int h)
3773 bool minSizeSet = d->setMinimumSize_helper(w, h);
3774 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3775 if (!minSizeSet && !maxSizeSet)
3779 d->setConstraints_sys();
3781 d->updateGeometry_helper(true);
3783 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3787 void QWidget::setMinimumWidth(int w)
3791 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3792 setMinimumSize(w, minimumSize().height());
3793 d->extra->explicitMinSize = expl;
3796 void QWidget::setMinimumHeight(int h)
3800 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3801 setMinimumSize(minimumSize().width(), h);
3802 d->extra->explicitMinSize = expl;
3805 void QWidget::setMaximumWidth(int w)
3809 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3810 setMaximumSize(w, maximumSize().height());
3811 d->extra->explicitMaxSize = expl;
3814 void QWidget::setMaximumHeight(int h)
3818 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3819 setMaximumSize(maximumSize().width(), h);
3820 d->extra->explicitMaxSize = expl;
3824 Sets both the minimum and maximum width of the widget to \a w
3825 without changing the heights. Provided for convenience.
3827 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3830 void QWidget::setFixedWidth(int w)
3834 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3835 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3836 setMinimumSize(w, minimumSize().height());
3837 setMaximumSize(w, maximumSize().height());
3838 d->extra->explicitMinSize = explMin;
3839 d->extra->explicitMaxSize = explMax;
3844 Sets both the minimum and maximum heights of the widget to \a h
3845 without changing the widths. Provided for convenience.
3847 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3850 void QWidget::setFixedHeight(int h)
3854 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3855 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3856 setMinimumSize(minimumSize().width(), h);
3857 setMaximumSize(maximumSize().width(), h);
3858 d->extra->explicitMinSize = explMin;
3859 d->extra->explicitMaxSize = explMax;
3864 Translates the widget coordinate \a pos to the coordinate system
3865 of \a parent. The \a parent must not be 0 and must be a parent
3866 of the calling widget.
3868 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3871 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3875 const QWidget * w = this;
3876 while (w != parent) {
3877 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3878 "parent must be in parent hierarchy");
3879 p = w->mapToParent(p);
3880 w = w->parentWidget();
3888 Translates the widget coordinate \a pos from the coordinate system
3889 of \a parent to this widget's coordinate system. The \a parent
3890 must not be 0 and must be a parent of the calling widget.
3892 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3895 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3899 const QWidget * w = this;
3900 while (w != parent) {
3901 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3902 "parent must be in parent hierarchy");
3904 p = w->mapFromParent(p);
3905 w = w->parentWidget();
3913 Translates the widget coordinate \a pos to a coordinate in the
3916 Same as mapToGlobal() if the widget has no parent.
3918 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3921 QPoint QWidget::mapToParent(const QPoint &pos) const
3923 return pos + data->crect.topLeft();
3927 Translates the parent widget coordinate \a pos to widget
3930 Same as mapFromGlobal() if the widget has no parent.
3932 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3935 QPoint QWidget::mapFromParent(const QPoint &pos) const
3937 return pos - data->crect.topLeft();
3942 Returns the window for this widget, i.e. the next ancestor widget
3943 that has (or could have) a window-system frame.
3945 If the widget is a window, the widget itself is returned.
3947 Typical usage is changing the window title:
3949 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3954 QWidget *QWidget::window() const
3956 QWidget *w = (QWidget *)this;
3957 QWidget *p = w->parentWidget();
3958 while (!w->isWindow() && p) {
3960 p = p->parentWidget();
3968 Returns the native parent for this widget, i.e. the next ancestor widget
3969 that has a system identifier, or 0 if it does not have any native parent.
3971 \sa effectiveWinId()
3973 QWidget *QWidget::nativeParentWidget() const
3975 QWidget *parent = parentWidget();
3976 while (parent && !parent->internalWinId())
3977 parent = parent->parentWidget();
3981 /*! \fn QWidget *QWidget::topLevelWidget() const
3984 Use window() instead.
3990 Returns the background role of the widget.
3992 The background role defines the brush from the widget's \l palette that
3993 is used to render the background.
3995 If no explicit background role is set, the widget inherts its parent
3996 widget's background role.
3998 \sa setBackgroundRole(), foregroundRole()
4000 QPalette::ColorRole QWidget::backgroundRole() const
4003 const QWidget *w = this;
4005 QPalette::ColorRole role = w->d_func()->bg_role;
4006 if (role != QPalette::NoRole)
4008 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4010 w = w->parentWidget();
4012 return QPalette::Window;
4016 Sets the background role of the widget to \a role.
4018 The background role defines the brush from the widget's \l palette that
4019 is used to render the background.
4021 If \a role is QPalette::NoRole, then the widget inherits its
4022 parent's background role.
4024 Note that styles are free to choose any color from the palette.
4025 You can modify the palette or set a style sheet if you don't
4026 achieve the result you want with setBackgroundRole().
4028 \sa backgroundRole(), foregroundRole()
4031 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4035 d->updateSystemBackground();
4036 d->propagatePaletteChange();
4037 d->updateIsOpaque();
4041 Returns the foreground role.
4043 The foreground role defines the color from the widget's \l palette that
4044 is used to draw the foreground.
4046 If no explicit foreground role is set, the function returns a role
4047 that contrasts with the background role.
4049 \sa setForegroundRole(), backgroundRole()
4051 QPalette::ColorRole QWidget::foregroundRole() const
4054 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4055 if (rl != QPalette::NoRole)
4057 QPalette::ColorRole role = QPalette::WindowText;
4058 switch (backgroundRole()) {
4059 case QPalette::Button:
4060 role = QPalette::ButtonText;
4062 case QPalette::Base:
4063 role = QPalette::Text;
4065 case QPalette::Dark:
4066 case QPalette::Shadow:
4067 role = QPalette::Light;
4069 case QPalette::Highlight:
4070 role = QPalette::HighlightedText;
4072 case QPalette::ToolTipBase:
4073 role = QPalette::ToolTipText;
4082 Sets the foreground role of the widget to \a role.
4084 The foreground role defines the color from the widget's \l palette that
4085 is used to draw the foreground.
4087 If \a role is QPalette::NoRole, the widget uses a foreground role
4088 that contrasts with the background role.
4090 Note that styles are free to choose any color from the palette.
4091 You can modify the palette or set a style sheet if you don't
4092 achieve the result you want with setForegroundRole().
4094 \sa foregroundRole(), backgroundRole()
4096 void QWidget::setForegroundRole(QPalette::ColorRole role)
4100 d->updateSystemBackground();
4101 d->propagatePaletteChange();
4105 \property QWidget::palette
4106 \brief the widget's palette
4108 This property describes the widget's palette. The palette is used by the
4109 widget's style when rendering standard components, and is available as a
4110 means to ensure that custom widgets can maintain consistency with the
4111 native platform's look and feel. It's common that different platforms, or
4112 different styles, have different palettes.
4114 When you assign a new palette to a widget, the color roles from this
4115 palette are combined with the widget's default palette to form the
4116 widget's final palette. The palette entry for the widget's background role
4117 is used to fill the widget's background (see QWidget::autoFillBackground),
4118 and the foreground role initializes QPainter's pen.
4120 The default depends on the system environment. QApplication maintains a
4121 system/theme palette which serves as a default for all widgets. There may
4122 also be special palette defaults for certain types of widgets (e.g., on
4123 Windows XP and Vista, all classes that derive from QMenuBar have a special
4124 default palette). You can also define default palettes for widgets
4125 yourself by passing a custom palette and the name of a widget to
4126 QApplication::setPalette(). Finally, the style always has the option of
4127 polishing the palette as it's assigned (see QStyle::polish()).
4129 QWidget propagates explicit palette roles from parent to child. If you
4130 assign a brush or color to a specific role on a palette and assign that
4131 palette to a widget, that role will propagate to all the widget's
4132 children, overriding any system defaults for that role. Note that palettes
4133 by default don't propagate to windows (see isWindow()) unless the
4134 Qt::WA_WindowPropagation attribute is enabled.
4136 QWidget's palette propagation is similar to its font propagation.
4138 The current style, which is used to render the content of all standard Qt
4139 widgets, is free to choose colors and brushes from the widget palette, or
4140 in some cases, to ignore the palette (partially, or completely). In
4141 particular, certain styles like GTK style, Mac style, Windows XP, and
4142 Vista style, depend on third party APIs to render the content of widgets,
4143 and these styles typically do not follow the palette. Because of this,
4144 assigning roles to a widget's palette is not guaranteed to change the
4145 appearance of the widget. Instead, you may choose to apply a \l
4146 styleSheet. You can refer to our Knowledge Base article
4147 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4150 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4151 When using style sheets, the palette of a widget can be customized using
4152 the "color", "background-color", "selection-color",
4153 "selection-background-color" and "alternate-background-color".
4155 \sa QApplication::palette(), QWidget::font()
4157 const QPalette &QWidget::palette() const
4160 data->pal.setCurrentColorGroup(QPalette::Disabled);
4161 } else if ((!isVisible() || isActiveWindow())
4162 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4163 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4166 data->pal.setCurrentColorGroup(QPalette::Active);
4169 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4170 if (qt_mac_can_clickThrough(this))
4171 data->pal.setCurrentColorGroup(QPalette::Active);
4174 data->pal.setCurrentColorGroup(QPalette::Inactive);
4179 void QWidget::setPalette(const QPalette &palette)
4182 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4184 // Determine which palette is inherited from this widget's ancestors and
4185 // QApplication::palette, resolve this against \a palette (attributes from
4186 // the inherited palette are copied over this widget's palette). Then
4187 // propagate this palette to this widget's children.
4188 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4189 QPalette resolvedPalette = palette.resolve(naturalPalette);
4190 d->setPalette_helper(resolvedPalette);
4196 Returns the palette that the widget \a w inherits from its ancestors and
4197 QApplication::palette. \a inheritedMask is the combination of the widget's
4198 ancestors palette request masks (i.e., which attributes from the parent
4199 widget's palette are implicitly imposed on this widget by the user). Note
4200 that this font does not take into account the palette set on \a w itself.
4202 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4205 QPalette naturalPalette = QApplication::palette(q);
4206 if (!q->testAttribute(Qt::WA_StyleSheet)
4207 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4208 #ifndef QT_NO_GRAPHICSVIEW
4209 || (extra && extra->proxyWidget)
4210 #endif //QT_NO_GRAPHICSVIEW
4212 if (QWidget *p = q->parentWidget()) {
4213 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4214 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4215 QPalette inheritedPalette = p->palette();
4216 inheritedPalette.resolve(inheritedMask);
4217 naturalPalette = inheritedPalette.resolve(naturalPalette);
4219 naturalPalette = p->palette();
4223 #ifndef QT_NO_GRAPHICSVIEW
4224 else if (extra && extra->proxyWidget) {
4225 QPalette inheritedPalette = extra->proxyWidget->palette();
4226 inheritedPalette.resolve(inheritedMask);
4227 naturalPalette = inheritedPalette.resolve(naturalPalette);
4229 #endif //QT_NO_GRAPHICSVIEW
4231 naturalPalette.resolve(0);
4232 return naturalPalette;
4237 Determine which palette is inherited from this widget's ancestors and
4238 QApplication::palette, resolve this against this widget's palette
4239 (attributes from the inherited palette are copied over this widget's
4240 palette). Then propagate this palette to this widget's children.
4242 void QWidgetPrivate::resolvePalette()
4244 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4245 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4246 setPalette_helper(resolvedPalette);
4249 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4252 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4255 updateSystemBackground();
4256 propagatePaletteChange();
4263 \property QWidget::font
4264 \brief the font currently set for the widget
4266 This property describes the widget's requested font. The font is used by
4267 the widget's style when rendering standard components, and is available as
4268 a means to ensure that custom widgets can maintain consistency with the
4269 native platform's look and feel. It's common that different platforms, or
4270 different styles, define different fonts for an application.
4272 When you assign a new font to a widget, the properties from this font are
4273 combined with the widget's default font to form the widget's final
4274 font. You can call fontInfo() to get a copy of the widget's final
4275 font. The final font is also used to initialize QPainter's font.
4277 The default depends on the system environment. QApplication maintains a
4278 system/theme font which serves as a default for all widgets. There may
4279 also be special font defaults for certain types of widgets. You can also
4280 define default fonts for widgets yourself by passing a custom font and the
4281 name of a widget to QApplication::setFont(). Finally, the font is matched
4282 against Qt's font database to find the best match.
4284 QWidget propagates explicit font properties from parent to child. If you
4285 change a specific property on a font and assign that font to a widget,
4286 that property will propagate to all the widget's children, overriding any
4287 system defaults for that property. Note that fonts by default don't
4288 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4289 attribute is enabled.
4291 QWidget's font propagation is similar to its palette propagation.
4293 The current style, which is used to render the content of all standard Qt
4294 widgets, is free to choose to use the widget font, or in some cases, to
4295 ignore it (partially, or completely). In particular, certain styles like
4296 GTK style, Mac style, Windows XP, and Vista style, apply special
4297 modifications to the widget font to match the platform's native look and
4298 feel. Because of this, assigning properties to a widget's font is not
4299 guaranteed to change the appearance of the widget. Instead, you may choose
4300 to apply a \l styleSheet.
4302 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4303 style sheets will take precedence if the settings conflict.
4305 \sa fontInfo(), fontMetrics()
4308 void QWidget::setFont(const QFont &font)
4312 #ifndef QT_NO_STYLE_STYLESHEET
4313 const QStyleSheetStyle* style;
4314 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4315 style->saveWidgetFont(this, font);
4319 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4321 // Determine which font is inherited from this widget's ancestors and
4322 // QApplication::font, resolve this against \a font (attributes from the
4323 // inherited font are copied over). Then propagate this font to this
4324 // widget's children.
4325 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4326 QFont resolvedFont = font.resolve(naturalFont);
4327 d->setFont_helper(resolvedFont);
4333 Returns the font that the widget \a w inherits from its ancestors and
4334 QApplication::font. \a inheritedMask is the combination of the widget's
4335 ancestors font request masks (i.e., which attributes from the parent
4336 widget's font are implicitly imposed on this widget by the user). Note
4337 that this font does not take into account the font set on \a w itself.
4339 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4340 is applied, fonts are not propagated anymore
4342 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4345 QFont naturalFont = QApplication::font(q);
4346 if (!q->testAttribute(Qt::WA_StyleSheet)
4347 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4348 #ifndef QT_NO_GRAPHICSVIEW
4349 || (extra && extra->proxyWidget)
4350 #endif //QT_NO_GRAPHICSVIEW
4352 if (QWidget *p = q->parentWidget()) {
4353 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4354 if (!naturalFont.isCopyOf(QApplication::font())) {
4355 QFont inheritedFont = p->font();
4356 inheritedFont.resolve(inheritedMask);
4357 naturalFont = inheritedFont.resolve(naturalFont);
4359 naturalFont = p->font();
4363 #ifndef QT_NO_GRAPHICSVIEW
4364 else if (extra && extra->proxyWidget) {
4365 QFont inheritedFont = extra->proxyWidget->font();
4366 inheritedFont.resolve(inheritedMask);
4367 naturalFont = inheritedFont.resolve(naturalFont);
4369 #endif //QT_NO_GRAPHICSVIEW
4371 naturalFont.resolve(0);
4378 Determine which font is implicitly imposed on this widget by its ancestors
4379 and QApplication::font, resolve this against its own font (attributes from
4380 the implicit font are copied over). Then propagate this font to this
4383 void QWidgetPrivate::resolveFont()
4385 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4386 QFont resolvedFont = data.fnt.resolve(naturalFont);
4387 setFont_helper(resolvedFont);
4393 Assign \a font to this widget, and propagate it to all children, except
4394 style sheet widgets (handled differently) and windows that don't enable
4395 window propagation. \a implicitMask is the union of all ancestor widgets'
4396 font request masks, and determines which attributes from this widget's
4397 font should propagate.
4399 void QWidgetPrivate::updateFont(const QFont &font)
4402 #ifndef QT_NO_STYLE_STYLESHEET
4403 const QStyleSheetStyle* cssStyle;
4404 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4407 data.fnt = QFont(font, q);
4408 #if defined(Q_WS_X11)
4409 // make sure the font set on this widget is associated with the correct screen
4410 data.fnt.x11SetScreen(xinfo.screen());
4412 // Combine new mask with natural mask and propagate to children.
4413 #ifndef QT_NO_GRAPHICSVIEW
4414 if (!q->parentWidget() && extra && extra->proxyWidget) {
4415 QGraphicsProxyWidget *p = extra->proxyWidget;
4416 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4418 #endif //QT_NO_GRAPHICSVIEW
4419 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4420 inheritedFontResolveMask = 0;
4422 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4424 for (int i = 0; i < children.size(); ++i) {
4425 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4428 #ifndef QT_NO_STYLE_STYLESHEET
4429 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4430 // Style sheets follow a different font propagation scheme.
4432 cssStyle->updateStyleSheetFont(w);
4434 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4435 // Propagate font changes.
4436 QWidgetPrivate *wd = w->d_func();
4437 wd->inheritedFontResolveMask = newMask;
4443 #ifndef QT_NO_STYLE_STYLESHEET
4445 cssStyle->updateStyleSheetFont(q);
4449 QEvent e(QEvent::FontChange);
4450 QApplication::sendEvent(q, &e);
4453 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4457 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4459 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4460 if (!children.isEmpty()) {
4461 for (int i = 0; i < children.size(); ++i) {
4462 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4463 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4464 w->d_func()->setLayoutDirection_helper(direction);
4467 QEvent e(QEvent::LayoutDirectionChange);
4468 QApplication::sendEvent(q, &e);
4471 void QWidgetPrivate::resolveLayoutDirection()
4474 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4475 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4479 \property QWidget::layoutDirection
4481 \brief the layout direction for this widget
4483 By default, this property is set to Qt::LeftToRight.
4485 When the layout direction is set on a widget, it will propagate to
4486 the widget's children, but not to a child that is a window and not
4487 to a child for which setLayoutDirection() has been explicitly
4488 called. Also, child widgets added \e after setLayoutDirection()
4489 has been called for the parent do not inherit the parent's layout
4492 This method no longer affects text layout direction since Qt 4.7.
4494 \sa QApplication::layoutDirection
4496 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4500 if (direction == Qt::LayoutDirectionAuto) {
4501 unsetLayoutDirection();
4505 setAttribute(Qt::WA_SetLayoutDirection);
4506 d->setLayoutDirection_helper(direction);
4509 Qt::LayoutDirection QWidget::layoutDirection() const
4511 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4514 void QWidget::unsetLayoutDirection()
4517 setAttribute(Qt::WA_SetLayoutDirection, false);
4518 d->resolveLayoutDirection();
4522 \fn QFontMetrics QWidget::fontMetrics() const
4524 Returns the font metrics for the widget's current font.
4525 Equivalent to QFontMetrics(widget->font()).
4527 \sa font(), fontInfo(), setFont()
4531 \fn QFontInfo QWidget::fontInfo() const
4533 Returns the font info for the widget's current font.
4534 Equivalent to QFontInto(widget->font()).
4536 \sa font(), fontMetrics(), setFont()
4541 \property QWidget::cursor
4542 \brief the cursor shape for this widget
4544 The mouse cursor will assume this shape when it's over this
4545 widget. See the \link Qt::CursorShape list of predefined cursor
4546 objects\endlink for a range of useful shapes.
4548 An editor widget might use an I-beam cursor:
4549 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4551 If no cursor has been set, or after a call to unsetCursor(), the
4552 parent's cursor is used.
4554 By default, this property contains a cursor with the Qt::ArrowCursor
4557 Some underlying window implementations will reset the cursor if it
4558 leaves a widget even if the mouse is grabbed. If you want to have
4559 a cursor set for all widgets, even when outside the window, consider
4560 QApplication::setOverrideCursor().
4562 \sa QApplication::setOverrideCursor()
4565 #ifndef QT_NO_CURSOR
4566 QCursor QWidget::cursor() const
4569 if (testAttribute(Qt::WA_SetCursor))
4570 return (d->extra && d->extra->curs)
4572 : QCursor(Qt::ArrowCursor);
4573 if (isWindow() || !parentWidget())
4574 return QCursor(Qt::ArrowCursor);
4575 return parentWidget()->cursor();
4578 void QWidget::setCursor(const QCursor &cursor)
4581 // On Mac we must set the cursor even if it is the ArrowCursor.
4582 #if !defined(Q_WS_MAC)
4583 if (cursor.shape() != Qt::ArrowCursor
4584 || (d->extra && d->extra->curs))
4588 QCursor *newCursor = new QCursor(cursor);
4589 delete d->extra->curs;
4590 d->extra->curs = newCursor;
4592 setAttribute(Qt::WA_SetCursor);
4593 d->setCursor_sys(cursor);
4595 QEvent event(QEvent::CursorChange);
4596 QApplication::sendEvent(this, &event);
4599 void QWidget::unsetCursor()
4603 delete d->extra->curs;
4607 setAttribute(Qt::WA_SetCursor, false);
4608 d->unsetCursor_sys();
4610 QEvent event(QEvent::CursorChange);
4611 QApplication::sendEvent(this, &event);
4617 \enum QWidget::RenderFlag
4619 This enum describes how to render the widget when calling QWidget::render().
4621 \value DrawWindowBackground If you enable this option, the widget's background
4622 is rendered into the target even if autoFillBackground is not set. By default,
4623 this option is enabled.
4625 \value DrawChildren If you enable this option, the widget's children
4626 are rendered recursively into the target. By default, this option is enabled.
4628 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4629 is ignored when rendering into the target. By default, this option is disabled.
4637 Renders the \a sourceRegion of this widget into the \a target
4638 using \a renderFlags to determine how to render. Rendering
4639 starts at \a targetOffset in the \a target. For example:
4641 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4643 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4644 the region, i.e. the entire widget.
4646 Ensure that you call QPainter::end() for the \a target device's
4647 active painter (if any) before rendering. For example:
4649 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4651 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4652 or QGLWidget::renderPixmap() instead.
4654 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4655 const QRegion &sourceRegion, RenderFlags renderFlags)
4657 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4663 Renders the widget into the \a painter's QPainter::device().
4665 Transformations and settings applied to the \a painter will be used
4668 \note The \a painter must be active. On Mac OS X the widget will be
4669 rendered into a QPixmap and then drawn by the \a painter.
4671 \sa QPainter::device()
4673 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4674 const QRegion &sourceRegion, RenderFlags renderFlags)
4677 qWarning("QWidget::render: Null pointer to painter");
4681 if (!painter->isActive()) {
4682 qWarning("QWidget::render: Cannot render with an inactive painter");
4686 const qreal opacity = painter->opacity();
4687 if (qFuzzyIsNull(opacity))
4688 return; // Fully transparent.
4691 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4692 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4694 if (toBePainted.isEmpty())
4699 d->extra->inRenderWithPainter = true;
4702 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4704 QPaintEngine *engine = painter->paintEngine();
4706 QPaintEnginePrivate *enginePriv = engine->d_func();
4707 Q_ASSERT(enginePriv);
4708 QPaintDevice *target = engine->paintDevice();
4711 // Render via a pixmap when dealing with non-opaque painters or printers.
4712 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4713 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4714 d->extra->inRenderWithPainter = false;
4718 // Set new shared painter.
4719 QPainter *oldPainter = d->sharedPainter();
4720 d->setSharedPainter(painter);
4722 // Save current system clip, viewport and transform,
4723 const QTransform oldTransform = enginePriv->systemTransform;
4724 const QRegion oldSystemClip = enginePriv->systemClip;
4725 const QRegion oldSystemViewport = enginePriv->systemViewport;
4727 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4728 if (painter->hasClipping()) {
4729 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4730 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4732 enginePriv->setSystemViewport(oldSystemClip);
4735 render(target, targetOffset, toBePainted, renderFlags);
4737 // Restore system clip, viewport and transform.
4738 enginePriv->systemClip = oldSystemClip;
4739 enginePriv->setSystemViewport(oldSystemViewport);
4740 enginePriv->setSystemTransform(oldTransform);
4742 // Restore shared painter.
4743 d->setSharedPainter(oldPainter);
4746 d->extra->inRenderWithPainter = false;
4749 static void sendResizeEvents(QWidget *target)
4751 QResizeEvent e(target->size(), QSize());
4752 QApplication::sendEvent(target, &e);
4754 const QObjectList children = target->children();
4755 for (int i = 0; i < children.size(); ++i) {
4756 QWidget *child = static_cast<QWidget*>(children.at(i));
4757 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4758 sendResizeEvents(child);
4765 Renders the widget into a pixmap restricted by the
4766 given \a rectangle. If the \a widget has any children, then
4767 they are also painted in the appropriate positions.
4769 If no rectangle is specified (the default) the entire widget is
4772 Replacement for Qt 4's QPixmap::grabWidget().
4774 \sa render(), QPixmap
4777 /* INVOKABLE since used by QPixmap::grabWidget(). */
4778 QPixmap QWidget::grab(const QRect &rectangle)
4781 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4782 sendResizeEvents(this);
4788 r.setWidth(width() - rectangle.x());
4790 r.setHeight(height() - rectangle.y());
4792 if (!r.intersects(rect()))
4795 QPixmap res(r.size());
4797 res.fill(Qt::transparent);
4798 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4799 | QWidget::DrawChildren | QWidget::IgnoreMask);
4804 \brief The graphicsEffect function returns a pointer to the
4805 widget's graphics effect.
4807 If the widget has no graphics effect, 0 is returned.
4811 \sa setGraphicsEffect()
4813 #ifndef QT_NO_GRAPHICSEFFECT
4814 QGraphicsEffect *QWidget::graphicsEffect() const
4817 return d->graphicsEffect;
4819 #endif //QT_NO_GRAPHICSEFFECT
4823 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4825 Sets \a effect as the widget's effect. If there already is an effect installed
4826 on this widget, QWidget will delete the existing effect before installing
4829 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4830 the effect from the widget and install it on this widget.
4832 QWidget takes ownership of \a effect.
4834 \note This function will apply the effect on itself and all its children.
4838 \sa graphicsEffect()
4840 #ifndef QT_NO_GRAPHICSEFFECT
4841 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4844 if (d->graphicsEffect == effect)
4847 if (d->graphicsEffect) {
4848 d->invalidateBuffer(rect());
4849 delete d->graphicsEffect;
4850 d->graphicsEffect = 0;
4855 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4856 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4857 d->graphicsEffect = effect;
4858 effect->d_func()->setGraphicsEffectSource(source);
4862 d->updateIsOpaque();
4864 #endif //QT_NO_GRAPHICSEFFECT
4866 bool QWidgetPrivate::isAboutToShow() const
4875 // The widget will be shown if any of its ancestors are about to show.
4876 QWidget *parent = q->parentWidget();
4877 return parent ? parent->d_func()->isAboutToShow() : false;
4880 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4883 const bool isVisible = q->isVisible();
4885 // Make sure the widget is laid out correctly.
4886 if (!isVisible && !isAboutToShow()) {
4887 QWidget *topLevel = q->window();
4888 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4889 topLevel->ensurePolished();
4891 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4892 // they're not explicitly hidden.
4893 QWidget *widget = q;
4894 QWidgetList hiddenWidgets;
4896 if (widget->isHidden()) {
4897 widget->setAttribute(Qt::WA_WState_Hidden, false);
4898 hiddenWidgets.append(widget);
4899 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4900 widget->d_func()->updateGeometry_helper(true);
4902 widget = widget->parentWidget();
4905 // Activate top-level layout.
4906 if (topLevel->d_func()->layout)
4907 topLevel->d_func()->layout->activate();
4909 // Adjust size if necessary.
4910 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4911 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4912 && !topLevel->testAttribute(Qt::WA_Resized)) {
4913 topLevel->adjustSize();
4914 topLevel->setAttribute(Qt::WA_Resized, false);
4917 // Activate child layouts.
4918 topLevel->d_func()->activateChildLayoutsRecursively();
4920 // We're not cheating with WA_WState_Hidden anymore.
4921 for (int i = 0; i < hiddenWidgets.size(); ++i) {
4922 QWidget *widget = hiddenWidgets.at(i);
4923 widget->setAttribute(Qt::WA_WState_Hidden);
4924 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4925 widget->parentWidget()->d_func()->layout->invalidate();
4927 } else if (isVisible) {
4928 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4931 // Calculate the region to be painted.
4932 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4933 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4934 toBePainted &= extra->mask;
4938 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4939 QWidget::RenderFlags renderFlags)
4942 Q_ASSERT(!toBePainted.isEmpty());
4946 const QTransform originalTransform = painter->worldTransform();
4947 const bool useDeviceCoordinates = originalTransform.isScaling();
4948 if (!useDeviceCoordinates) {
4950 // Render via a pixmap.
4951 const QRect rect = toBePainted.boundingRect();
4952 const QSize size = rect.size();
4956 QPixmap pixmap(size);
4957 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4958 pixmap.fill(Qt::transparent);
4959 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4961 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4962 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4964 painter->drawPixmap(targetOffset, pixmap);
4967 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4971 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4972 QTransform transform = originalTransform;
4973 transform.translate(targetOffset.x(), targetOffset.y());
4975 QPaintDevice *device = painter->device();
4978 // Calculate device rect.
4979 const QRectF rect(toBePainted.boundingRect());
4980 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4981 deviceRect &= QRect(0, 0, device->width(), device->height());
4983 QPixmap pixmap(deviceRect.size());
4984 pixmap.fill(Qt::transparent);
4986 // Create a pixmap device coordinate painter.
4987 QPainter pixmapPainter(&pixmap);
4988 pixmapPainter.setRenderHints(painter->renderHints());
4989 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4990 pixmapPainter.setTransform(transform);
4992 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4993 pixmapPainter.end();
4995 // And then draw the pixmap.
4996 painter->setTransform(QTransform());
4997 painter->drawPixmap(deviceRect.topLeft(), pixmap);
4998 painter->setTransform(originalTransform);
5003 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5004 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5010 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5011 dirtyOnWidget = QRegion();
5013 // We disable the rendering of QToolBar in the backingStore if
5014 // it's supposed to be in the unified toolbar on Mac OS X.
5015 if (backingStore && isInUnifiedToolbar)
5021 #ifndef QT_NO_GRAPHICSEFFECT
5022 if (graphicsEffect && graphicsEffect->isEnabled()) {
5023 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5024 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5026 if (!sourced->context) {
5027 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5028 sourced->context = &context;
5029 if (!sharedPainter) {
5030 QPaintEngine *paintEngine = pdev->paintEngine();
5031 paintEngine->d_func()->systemClip = rgn.translated(offset);
5033 p.translate(offset);
5034 context.painter = &p;
5035 graphicsEffect->draw(&p);
5036 paintEngine->d_func()->systemClip = QRegion();
5038 context.painter = sharedPainter;
5039 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5040 sourced->invalidateCache();
5041 sourced->lastEffectTransform = sharedPainter->worldTransform();
5043 sharedPainter->save();
5044 sharedPainter->translate(offset);
5045 graphicsEffect->draw(sharedPainter);
5046 sharedPainter->restore();
5048 sourced->context = 0;
5052 #endif //QT_NO_GRAFFICSEFFECT
5054 const bool asRoot = flags & DrawAsRoot;
5055 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5056 const bool recursive = flags & DrawRecursive;
5057 const bool alsoInvisible = flags & DrawInvisible;
5059 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5061 QRegion toBePainted(rgn);
5062 if (asRoot && !alsoInvisible)
5063 toBePainted &= clipRect(); //(rgn & visibleRegion());
5064 if (!(flags & DontSubtractOpaqueChildren))
5065 subtractOpaqueChildren(toBePainted, q->rect());
5067 if (!toBePainted.isEmpty()) {
5068 bool onScreen = paintOnScreen();
5069 if (!onScreen || alsoOnScreen) {
5070 //update the "in paint event" flag
5071 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5072 qWarning("QWidget::repaint: Recursive repaint detected");
5073 q->setAttribute(Qt::WA_WState_InPaintEvent);
5075 //clip away the new area
5076 #ifndef QT_NO_PAINT_DEBUG
5077 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5079 QPaintEngine *paintEngine = pdev->paintEngine();
5081 setRedirected(pdev, -offset);
5084 // (Alien support) Special case for Mac when redirecting: If the paint device
5085 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5086 // outside the paint event is not supported on QWidgets. The attributeis
5087 // restored further down.
5088 if (pdev->devType() == QInternal::Widget)
5089 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5093 paintEngine->d_func()->systemClip = toBePainted;
5095 paintEngine->d_func()->systemRect = q->data->crect;
5097 //paint the background
5098 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5099 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5101 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5105 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5107 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5109 QColor tint = q->palette().window().color();
5110 tint.setAlphaF(qreal(.6));
5111 p.fillRect(toBePainted.boundingRect(), tint);
5116 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5117 qDebug() << "clipping to" << toBePainted << "location == " << offset
5118 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5121 //actually send the paint event
5122 QPaintEvent e(toBePainted);
5123 QCoreApplication::sendSpontaneousEvent(q, &e);
5128 if (pdev->devType() == QInternal::Widget)
5129 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5131 restoreRedirected();
5133 paintEngine->d_func()->systemRect = QRect();
5135 paintEngine->d_func()->currentClipDevice = 0;
5136 paintEngine->d_func()->systemClip = QRegion();
5138 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5139 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5140 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5142 if (paintEngine && paintEngine->autoDestruct()) {
5146 #ifndef QT_NO_PAINT_DEBUG
5148 QWidgetBackingStore::unflushPaint(q, toBePainted);
5150 } else if (q->isWindow()) {
5151 QPaintEngine *engine = pdev->paintEngine();
5154 p.setClipRegion(toBePainted);
5155 const QBrush bg = q->palette().brush(QPalette::Window);
5156 if (bg.style() == Qt::TexturePattern)
5157 p.drawTiledPixmap(q->rect(), bg.texture());
5159 p.fillRect(q->rect(), bg);
5161 if (engine->autoDestruct())
5167 if (recursive && !children.isEmpty()) {
5168 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5169 , sharedPainter, backingStore);
5173 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5174 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5178 qWarning("QWidget::render: null pointer to paint device");
5182 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5183 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5184 ? prepareToRender(sourceRegion, renderFlags)
5186 if (paintRegion.isEmpty())
5190 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5192 // Use the target's shared painter if set (typically set when doing
5193 // "other->render(widget);" in the widget's paintEvent.
5194 if (target->devType() == QInternal::Widget) {
5195 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5196 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5197 QPainter *targetPainter = targetPrivate->sharedPainter();
5198 if (targetPainter && targetPainter->isActive())
5199 setSharedPainter(targetPainter);
5204 // Use the target's redirected device if set and adjust offset and paint
5205 // region accordingly. This is typically the case when people call render
5206 // from the paintEvent.
5207 QPoint offset = targetOffset;
5208 offset -= paintRegion.boundingRect().topLeft();
5209 QPoint redirectionOffset;
5210 QPaintDevice *redirected = 0;
5212 if (target->devType() == QInternal::Widget)
5213 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5215 redirected = QPainter::redirected(target, &redirectionOffset);
5218 target = redirected;
5219 offset -= redirectionOffset;
5222 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5223 if (QPaintEngine *targetEngine = target->paintEngine()) {
5224 const QRegion targetSystemClip = targetEngine->systemClip();
5225 if (!targetSystemClip.isEmpty())
5226 paintRegion &= targetSystemClip.translated(-offset);
5230 // Set backingstore flags.
5231 int flags = DrawPaintOnScreen | DrawInvisible;
5232 if (renderFlags & QWidget::DrawWindowBackground)
5233 flags |= DrawAsRoot;
5235 if (renderFlags & QWidget::DrawChildren)
5236 flags |= DrawRecursive;
5238 flags |= DontSubtractOpaqueChildren;
5240 flags |= DontSetCompositionMode;
5242 if (target->devType() == QInternal::Printer) {
5244 render_helper(&p, targetOffset, paintRegion, renderFlags);
5249 // Render via backingstore.
5250 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5252 // Restore shared painter.
5253 if (oldSharedPainter)
5254 setSharedPainter(oldSharedPainter);
5256 // Render via backingstore (no shared painter).
5257 drawWidget(target, paintRegion, offset, flags, 0);
5261 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5262 const QPoint &offset, int flags
5263 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5267 bool dirtyBoundingRect = true;
5268 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5269 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5272 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5273 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5274 && !(excludeNativeChildren && x->internalWinId())) {
5275 if (dirtyBoundingRect) {
5276 boundingRect = rgn.boundingRect();
5277 dirtyBoundingRect = false;
5280 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5286 } while (index >= 0);
5291 QWidgetPrivate *wd = w->d_func();
5292 const QPoint widgetPos(w->data->crect.topLeft());
5293 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5297 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5298 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5299 , sharedPainter, backingStore);
5302 if (w->updatesEnabled()
5303 #ifndef QT_NO_GRAPHICSVIEW
5304 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5305 #endif //QT_NO_GRAPHICSVIEW
5307 QRegion wRegion(rgn);
5308 wRegion &= wd->effectiveRectFor(w->data->crect);
5309 wRegion.translate(-widgetPos);
5311 wRegion &= wd->extra->mask;
5312 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5316 #ifndef QT_NO_GRAPHICSEFFECT
5317 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5319 if (system != Qt::DeviceCoordinates)
5320 return m_widget->rect();
5323 // Device coordinates without context not yet supported.
5324 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5328 return context->painter->worldTransform().mapRect(m_widget->rect());
5331 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5333 if (!context || context->painter != painter) {
5334 m_widget->render(painter);
5338 // The region saved in the context is neither clipped to the rect
5339 // nor the mask, so we have to clip it here before calling drawWidget.
5340 QRegion toBePainted = context->rgn;
5341 toBePainted &= m_widget->rect();
5342 QWidgetPrivate *wd = qt_widget_private(m_widget);
5343 if (wd->extra && wd->extra->hasMask)
5344 toBePainted &= wd->extra->mask;
5346 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5347 context->sharedPainter, context->backingStore);
5350 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5351 QGraphicsEffect::PixmapPadMode mode) const
5353 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5354 if (!context && deviceCoordinates) {
5355 // Device coordinates without context not yet supported.
5356 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5360 QPoint pixmapOffset;
5361 QRectF sourceRect = m_widget->rect();
5363 if (deviceCoordinates) {
5364 const QTransform &painterTransform = context->painter->worldTransform();
5365 sourceRect = painterTransform.mapRect(sourceRect);
5366 pixmapOffset = painterTransform.map(pixmapOffset);
5371 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5372 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5373 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5374 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5376 effectRect = sourceRect.toAlignedRect();
5379 *offset = effectRect.topLeft();
5381 pixmapOffset -= effectRect.topLeft();
5383 QPixmap pixmap(effectRect.size());
5384 pixmap.fill(Qt::transparent);
5385 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5388 #endif //QT_NO_GRAPHICSEFFECT
5390 #ifndef QT_NO_GRAPHICSVIEW
5394 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5395 widget and its ancestors. The search starts at \a origin (inclusive).
5396 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5399 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5402 QWExtra *extra = origin->d_func()->extra;
5403 if (extra && extra->proxyWidget)
5404 return extra->proxyWidget;
5405 return nearestGraphicsProxyWidget(origin->parentWidget());
5412 \property QWidget::locale
5413 \brief the widget's locale
5416 As long as no special locale has been set, this is either
5417 the parent's locale or (if this widget is a top level widget),
5420 If the widget displays dates or numbers, these should be formatted
5421 using the widget's locale.
5423 \sa QLocale QLocale::setDefault()
5426 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5429 if (locale == loc && !forceUpdate)
5434 if (!children.isEmpty()) {
5435 for (int i = 0; i < children.size(); ++i) {
5436 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5439 if (w->testAttribute(Qt::WA_SetLocale))
5441 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5443 w->d_func()->setLocale_helper(loc, forceUpdate);
5446 QEvent e(QEvent::LocaleChange);
5447 QApplication::sendEvent(q, &e);
5450 void QWidget::setLocale(const QLocale &locale)
5454 setAttribute(Qt::WA_SetLocale);
5455 d->setLocale_helper(locale);
5458 QLocale QWidget::locale() const
5465 void QWidgetPrivate::resolveLocale()
5469 if (!q->testAttribute(Qt::WA_SetLocale)) {
5470 setLocale_helper(q->isWindow()
5472 : q->parentWidget()->locale());
5476 void QWidget::unsetLocale()
5479 setAttribute(Qt::WA_SetLocale, false);
5483 static QString constructWindowTitleFromFilePath(const QString &filePath)
5485 QFileInfo fi(filePath);
5486 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5488 QString appName = QApplication::applicationName();
5489 if (!appName.isEmpty())
5490 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5496 \property QWidget::windowTitle
5497 \brief the window title (caption)
5499 This property only makes sense for top-level widgets, such as
5500 windows and dialogs. If no caption has been set, the title is based of the
5501 \l windowFilePath. If neither of these is set, then the title is
5504 If you use the \l windowModified mechanism, the window title must
5505 contain a "[*]" placeholder, which indicates where the '*' should
5506 appear. Normally, it should appear right after the file name
5507 (e.g., "document1.txt[*] - Text Editor"). If the \l
5508 windowModified property is false (the default), the placeholder
5511 \sa windowIcon, windowIconText, windowModified, windowFilePath
5513 QString QWidget::windowTitle() const
5516 if (d->extra && d->extra->topextra) {
5517 if (!d->extra->topextra->caption.isEmpty())
5518 return d->extra->topextra->caption;
5519 if (!d->extra->topextra->filePath.isEmpty())
5520 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5526 Returns a modified window title with the [*] place holder
5527 replaced according to the rules described in QWidget::setWindowTitle
5529 This function assumes that "[*]" can be quoted by another
5530 "[*]", so it will replace two place holders by one and
5531 a single last one by either "*" or nothing depending on
5536 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5541 extern QString qt_eval_adapt_window_title(const QString &title);
5542 QString cap = qt_eval_adapt_window_title(title);
5544 QString cap = title;
5550 QLatin1String placeHolder("[*]");
5551 int placeHolderLength = 3; // QLatin1String doesn't have length()
5553 int index = cap.indexOf(placeHolder);
5555 // here the magic begins
5556 while (index != -1) {
5557 index += placeHolderLength;
5559 while (cap.indexOf(placeHolder, index) == index) {
5561 index += placeHolderLength;
5564 if (count%2) { // odd number of [*] -> replace last one
5565 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5566 if (widget->isWindowModified()
5567 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5568 cap.replace(lastIndex, 3, QWidget::tr("*"));
5570 cap.remove(lastIndex, 3);
5573 index = cap.indexOf(placeHolder, index);
5576 cap.replace(QLatin1String("[*][*]"), placeHolder);
5581 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5584 if (q->testAttribute(Qt::WA_WState_Created))
5585 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5588 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5591 if (q->testAttribute(Qt::WA_WState_Created))
5592 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5595 void QWidget::setWindowIconText(const QString &iconText)
5597 if (QWidget::windowIconText() == iconText)
5601 d->topData()->iconText = iconText;
5602 d->setWindowIconText_helper(iconText);
5604 QEvent e(QEvent::IconTextChange);
5605 QApplication::sendEvent(this, &e);
5608 void QWidget::setWindowTitle(const QString &title)
5610 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5614 d->topData()->caption = title;
5615 d->setWindowTitle_helper(title);
5617 QEvent e(QEvent::WindowTitleChange);
5618 QApplication::sendEvent(this, &e);
5623 \property QWidget::windowIcon
5624 \brief the widget's icon
5626 This property only makes sense for windows. If no icon
5627 has been set, windowIcon() returns the application icon
5628 (QApplication::windowIcon()).
5630 \sa windowIconText, windowTitle
5632 QIcon QWidget::windowIcon() const
5634 const QWidget *w = this;
5636 const QWidgetPrivate *d = w->d_func();
5637 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5638 return *d->extra->topextra->icon;
5639 w = w->parentWidget();
5641 return QApplication::windowIcon();
5644 void QWidgetPrivate::setWindowIcon_helper()
5646 QEvent e(QEvent::WindowIconChange);
5647 QApplication::sendEvent(q_func(), &e);
5648 for (int i = 0; i < children.size(); ++i) {
5649 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5650 if (w && !w->isWindow())
5651 QApplication::sendEvent(w, &e);
5655 void QWidget::setWindowIcon(const QIcon &icon)
5659 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5662 if (!d->extra->topextra->icon)
5663 d->extra->topextra->icon = new QIcon();
5664 *d->extra->topextra->icon = icon;
5666 delete d->extra->topextra->iconPixmap;
5667 d->extra->topextra->iconPixmap = 0;
5669 d->setWindowIcon_sys();
5670 d->setWindowIcon_helper();
5675 \property QWidget::windowIconText
5676 \brief the widget's icon text
5678 This property only makes sense for windows. If no icon
5679 text has been set, this functions returns an empty string.
5681 \sa windowIcon, windowTitle
5684 QString QWidget::windowIconText() const
5687 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5691 \property QWidget::windowFilePath
5693 \brief the file path associated with a widget
5695 This property only makes sense for windows. It associates a file path with
5696 a window. If you set the file path, but have not set the window title, Qt
5697 sets the window title to contain a string created using the following
5703 \li The file name of the specified path, obtained using QFileInfo::fileName().
5709 \li The file name of the specified path, obtained using QFileInfo::fileName().
5710 \li An optional \c{*} character, if the \l windowModified property is set.
5711 \li The \c{0x2014} unicode character, padded either side by spaces.
5712 \li The application name, obtained from the application's
5713 \l{QCoreApplication::}{applicationName} property.
5716 If the window title is set at any point, then the window title takes precedence and
5717 will be shown instead of the file path string.
5719 Additionally, on Mac OS X, this has an added benefit that it sets the
5720 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5721 for the window, assuming that the file path exists.
5723 If no file path is set, this property contains an empty string.
5725 By default, this property contains an empty string.
5727 \sa windowTitle, windowIcon
5730 QString QWidget::windowFilePath() const
5733 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5736 void QWidget::setWindowFilePath(const QString &filePath)
5738 if (filePath == windowFilePath())
5744 d->extra->topextra->filePath = filePath;
5745 d->setWindowFilePath_helper(filePath);
5748 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5750 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5752 setWindowTitle_helper(QFileInfo(filePath).fileName());
5756 setWindowTitle_helper(q->windowTitle());
5760 setWindowFilePath_sys(filePath);
5765 Returns the window's role, or an empty string.
5767 \sa windowIcon, windowTitle
5770 QString QWidget::windowRole() const
5773 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5777 Sets the window's role to \a role. This only makes sense for
5780 void QWidget::setWindowRole(const QString &role)
5782 #if defined(Q_WS_X11)
5784 d->topData()->role = role;
5792 \property QWidget::mouseTracking
5793 \brief whether mouse tracking is enabled for the widget
5795 If mouse tracking is disabled (the default), the widget only
5796 receives mouse move events when at least one mouse button is
5797 pressed while the mouse is being moved.
5799 If mouse tracking is enabled, the widget receives mouse move
5800 events even if no buttons are pressed.
5802 \sa mouseMoveEvent()
5807 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5808 function resets this widget to have no focus proxy.
5810 Some widgets can "have focus", but create a child widget, such as
5811 QLineEdit, to actually handle the focus. In this case, the widget
5812 can set the line edit to be its focus proxy.
5814 setFocusProxy() sets the widget which will actually get focus when
5815 "this widget" gets it. If there is a focus proxy, setFocus() and
5816 hasFocus() operate on the focus proxy.
5821 void QWidget::setFocusProxy(QWidget * w)
5824 if (!w && !d->extra)
5827 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5829 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5835 d->extra->focus_proxy = w;
5840 Returns the focus proxy, or 0 if there is no focus proxy.
5845 QWidget * QWidget::focusProxy() const
5848 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5853 \property QWidget::focus
5854 \brief whether this widget (or its focus proxy) has the keyboard
5857 By default, this property is false.
5859 \note Obtaining the value of this property for a widget is effectively equivalent
5860 to checking whether QApplication::focusWidget() refers to the widget.
5862 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5864 bool QWidget::hasFocus() const
5866 const QWidget* w = this;
5867 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5868 w = w->d_func()->extra->focus_proxy;
5869 if (QWidget *window = w->window()) {
5870 #ifndef QT_NO_GRAPHICSVIEW
5871 QWExtra *e = window->d_func()->extra;
5872 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5876 return (QApplication::focusWidget() == w);
5880 Gives the keyboard input focus to this widget (or its focus
5881 proxy) if this widget or one of its parents is the \link
5882 isActiveWindow() active window\endlink. The \a reason argument will
5883 be passed into any focus event sent from this function, it is used
5884 to give an explanation of what caused the widget to get focus.
5885 If the window is not active, the widget will be given the focus when
5886 the window becomes active.
5888 First, a focus about to change event is sent to the focus widget (if any) to
5889 tell it that it is about to lose the focus. Then focus is changed, a
5890 focus out event is sent to the previous focus item and a focus in event is sent
5891 to the new item to tell it that it just received the focus.
5892 (Nothing happens if the focus in and focus out widgets are the
5895 \note On embedded platforms, setFocus() will not cause an input panel
5896 to be opened by the input method. If you want this to happen, you
5897 have to send a QEvent::RequestSoftwareInputPanel event to the
5900 setFocus() gives focus to a widget regardless of its focus policy,
5901 but does not clear any keyboard grab (see grabKeyboard()).
5903 Be aware that if the widget is hidden, it will not accept focus
5906 \warning If you call setFocus() in a function which may itself be
5907 called from focusOutEvent() or focusInEvent(), you may get an
5910 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5911 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5912 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5915 void QWidget::setFocus(Qt::FocusReason reason)
5921 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5922 f = f->d_func()->extra->focus_proxy;
5924 if (QApplication::focusWidget() == f
5925 #if defined(Q_WS_WIN)
5926 && GetFocus() == f->internalWinId()
5931 #ifndef QT_NO_GRAPHICSVIEW
5932 QWidget *previousProxyFocus = 0;
5933 if (QWExtra *topData = window()->d_func()->extra) {
5934 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5935 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5936 if (previousProxyFocus && previousProxyFocus->focusProxy())
5937 previousProxyFocus = previousProxyFocus->focusProxy();
5938 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5944 #ifndef QT_NO_GRAPHICSVIEW
5945 // Update proxy state
5946 if (QWExtra *topData = window()->d_func()->extra) {
5947 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5948 f->d_func()->updateFocusChild();
5949 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5950 topData->proxyWidget->setFocus(reason);
5951 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5956 if (f->isActiveWindow()) {
5957 QWidget *prev = QApplicationPrivate::focus_widget;
5959 if (reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
5960 && prev->testAttribute(Qt::WA_InputMethodEnabled)) {
5961 qApp->inputMethod()->commit();
5964 if (reason != Qt::NoFocusReason) {
5965 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, reason);
5966 QApplication::sendEvent(prev, &focusAboutToChange);
5970 f->d_func()->updateFocusChild();
5972 QApplicationPrivate::setFocusWidget(f, reason);
5973 #ifndef QT_NO_ACCESSIBILITY
5975 // The negation of the condition in setFocus_sys
5976 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5977 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5980 // menus update the focus manually and this would create bogus events
5981 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5984 QAccessibleEvent event(f, QAccessible::Focus);
5985 QAccessible::updateAccessibility(&event);
5988 #ifndef QT_NO_GRAPHICSVIEW
5989 if (QWExtra *topData = window()->d_func()->extra) {
5990 if (topData->proxyWidget) {
5991 if (previousProxyFocus && previousProxyFocus != f) {
5992 // Send event to self
5993 QFocusEvent event(QEvent::FocusOut, reason);
5994 QPointer<QWidget> that = previousProxyFocus;
5995 QApplication::sendEvent(previousProxyFocus, &event);
5997 QApplication::sendEvent(that->style(), &event);
6000 #ifndef QT_NO_GRAPHICSVIEW
6001 // Update proxy state
6002 if (QWExtra *topData = window()->d_func()->extra)
6003 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
6004 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
6006 // Send event to self
6007 QFocusEvent event(QEvent::FocusIn, reason);
6008 QPointer<QWidget> that = f;
6009 QApplication::sendEvent(f, &event);
6011 QApplication::sendEvent(that->style(), &event);
6017 f->d_func()->updateFocusChild();
6020 if (QTLWExtra *extra = f->window()->d_func()->maybeTopData())
6021 emit extra->window->focusObjectChanged(f);
6024 // updates focus_child on parent widgets to point into this widget
6025 void QWidgetPrivate::updateFocusChild()
6030 if (q->isHidden()) {
6031 while (w && w->isHidden()) {
6032 w->d_func()->focus_child = q;
6033 w = w->isWindow() ? 0 : w->parentWidget();
6037 w->d_func()->focus_child = q;
6038 w = w->isWindow() ? 0 : w->parentWidget();
6044 \fn void QWidget::setFocus()
6047 Gives the keyboard input focus to this widget (or its focus
6048 proxy) if this widget or one of its parents is the
6049 \l{isActiveWindow()}{active window}.
6053 Takes keyboard input focus from the widget.
6055 If the widget has active focus, a \link focusOutEvent() focus out
6056 event\endlink is sent to this widget to tell it that it has
6059 This widget must enable focus setting in order to get the keyboard
6060 input focus, i.e. it must call setFocusPolicy().
6062 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6063 setFocusPolicy(), QApplication::focusWidget()
6066 void QWidget::clearFocus()
6069 if (testAttribute(Qt::WA_InputMethodEnabled))
6070 qApp->inputMethod()->commit();
6072 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
6073 QApplication::sendEvent(this, &focusAboutToChange);
6078 if (w->d_func()->focus_child == this)
6079 w->d_func()->focus_child = 0;
6080 w = w->parentWidget();
6082 #ifndef QT_NO_GRAPHICSVIEW
6083 QWExtra *topData = d_func()->extra;
6084 if (topData && topData->proxyWidget)
6085 topData->proxyWidget->clearFocus();
6089 // Update proxy state
6090 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6091 #if defined(Q_WS_WIN)
6092 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6097 #ifndef QT_NO_ACCESSIBILITY
6098 QAccessibleEvent event(this, QAccessible::Focus);
6099 QAccessible::updateAccessibility(&event);
6107 \fn bool QWidget::focusNextChild()
6109 Finds a new widget to give the keyboard focus to, as appropriate
6110 for \key Tab, and returns true if it can find a new widget, or
6113 \sa focusPreviousChild()
6117 \fn bool QWidget::focusPreviousChild()
6119 Finds a new widget to give the keyboard focus to, as appropriate
6120 for \key Shift+Tab, and returns true if it can find a new widget,
6121 or false if it can't.
6123 \sa focusNextChild()
6127 Finds a new widget to give the keyboard focus to, as appropriate
6128 for Tab and Shift+Tab, and returns true if it can find a new
6129 widget, or false if it can't.
6131 If \a next is true, this function searches forward, if \a next
6132 is false, it searches backward.
6134 Sometimes, you will want to reimplement this function. For
6135 example, a web browser might reimplement it to move its "current
6136 active link" forward or backward, and call
6137 focusNextPrevChild() only when it reaches the last or
6138 first link on the "page".
6140 Child widgets call focusNextPrevChild() on their parent widgets,
6141 but only the window that contains the child widgets decides where
6142 to redirect focus. By reimplementing this function for an object,
6143 you thus gain control of focus traversal for all child widgets.
6145 \sa focusNextChild(), focusPreviousChild()
6148 bool QWidget::focusNextPrevChild(bool next)
6151 QWidget* p = parentWidget();
6152 bool isSubWindow = (windowType() == Qt::SubWindow);
6153 if (!isWindow() && !isSubWindow && p)
6154 return p->focusNextPrevChild(next);
6155 #ifndef QT_NO_GRAPHICSVIEW
6156 if (d->extra && d->extra->proxyWidget)
6157 return d->extra->proxyWidget->focusNextPrevChild(next);
6159 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6160 if (!w) return false;
6162 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6167 Returns the last child of this widget that setFocus had been
6168 called on. For top level widgets this is the widget that will get
6169 focus in case this window gets activated
6171 This is not the same as QApplication::focusWidget(), which returns
6172 the focus widget in the currently active window.
6175 QWidget *QWidget::focusWidget() const
6177 return const_cast<QWidget *>(d_func()->focus_child);
6181 Returns the next widget in this widget's focus chain.
6183 \sa previousInFocusChain()
6185 QWidget *QWidget::nextInFocusChain() const
6187 return const_cast<QWidget *>(d_func()->focus_next);
6191 \brief The previousInFocusChain function returns the previous
6192 widget in this widget's focus chain.
6194 \sa nextInFocusChain()
6198 QWidget *QWidget::previousInFocusChain() const
6200 return const_cast<QWidget *>(d_func()->focus_prev);
6204 \property QWidget::isActiveWindow
6205 \brief whether this widget's window is the active window
6207 The active window is the window that contains the widget that has
6208 keyboard focus (The window may still have focus if it has no
6209 widgets or none of its widgets accepts keyboard focus).
6211 When popup windows are visible, this property is true for both the
6212 active window \e and for the popup.
6214 By default, this property is false.
6216 \sa activateWindow(), QApplication::activeWindow()
6218 bool QWidget::isActiveWindow() const
6220 QWidget *tlw = window();
6221 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6224 #ifndef QT_NO_GRAPHICSVIEW
6225 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6226 if (isVisible() && tlwExtra->proxyWidget)
6227 return tlwExtra->proxyWidget->isActiveWindow();
6232 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6233 if(qt_mac_is_macdrawer(tlw) &&
6234 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6237 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6238 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6241 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6242 if(tlw->windowType() == Qt::Tool &&
6244 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6246 QWidget *w = QApplication::activeWindow();
6247 while(w && tlw->windowType() == Qt::Tool &&
6248 !w->isModal() && w->parentWidget()) {
6249 w = w->parentWidget()->window();
6254 #if defined(Q_WS_WIN32)
6255 HWND active = GetActiveWindow();
6256 if (!tlw->testAttribute(Qt::WA_WState_Created))
6258 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6265 Puts the \a second widget after the \a first widget in the focus order.
6267 Note that since the tab order of the \a second widget is changed, you
6268 should order a chain like this:
6270 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6274 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6276 If \a first or \a second has a focus proxy, setTabOrder()
6277 correctly substitutes the proxy.
6279 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6281 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6283 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6286 if (first->window() != second->window()) {
6287 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6291 QWidget *fp = first->focusProxy();
6293 // If first is redirected, set first to the last child of first
6294 // that can take keyboard focus so that second is inserted after
6295 // that last child, and the focus order within first is (more
6296 // likely to be) preserved.
6297 QList<QWidget *> l = first->findChildren<QWidget *>();
6298 for (int i = l.size()-1; i >= 0; --i) {
6299 QWidget * next = l.at(i);
6300 if (next->window() == fp->window()) {
6302 if (fp->focusPolicy() != Qt::NoFocus)
6312 if (QWidget *sp = second->focusProxy())
6315 // QWidget *fp = first->d_func()->focus_prev;
6316 QWidget *fn = first->d_func()->focus_next;
6318 if (fn == second || first == second)
6321 QWidget *sp = second->d_func()->focus_prev;
6322 QWidget *sn = second->d_func()->focus_next;
6324 fn->d_func()->focus_prev = second;
6325 first->d_func()->focus_next = second;
6327 second->d_func()->focus_next = fn;
6328 second->d_func()->focus_prev = first;
6330 sp->d_func()->focus_next = sn;
6331 sn->d_func()->focus_prev = sp;
6334 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6335 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6337 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6338 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6343 Moves the relevant subwidgets of this widget from the \a oldtlw's
6344 tab chain to that of the new parent, if there's anything to move and
6347 This function is called from QWidget::reparent() *after* the widget
6348 has been reparented.
6353 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6356 if (oldtlw == q->window())
6357 return; // nothing to do
6360 focus_child->clearFocus();
6362 // separate the focus chain into new (children of myself) and old (the rest)
6363 QWidget *firstOld = 0;
6364 //QWidget *firstNew = q; //invariant
6365 QWidget *o = 0; // last in the old list
6366 QWidget *n = q; // last in the new list
6368 bool prevWasNew = true;
6369 QWidget *w = focus_next;
6371 //Note: for efficiency, we do not maintain the list invariant inside the loop
6372 //we append items to the relevant list, and we optimize by not changing pointers
6373 //when subsequent items are going into the same list.
6375 bool currentIsNew = q->isAncestorOf(w);
6378 //prev was old -- append to new list
6379 n->d_func()->focus_next = w;
6380 w->d_func()->focus_prev = n;
6385 //prev was new -- append to old list, if there is one
6387 o->d_func()->focus_next = w;
6388 w->d_func()->focus_prev = o;
6390 // "create" the old list
6396 w = w->d_func()->focus_next;
6397 prevWasNew = currentIsNew;
6400 //repair the old list:
6402 o->d_func()->focus_next = firstOld;
6403 firstOld->d_func()->focus_prev = o;
6406 if (!q->isWindow()) {
6407 QWidget *topLevel = q->window();
6408 //insert new chain into toplevel's chain
6410 QWidget *prev = topLevel->d_func()->focus_prev;
6412 topLevel->d_func()->focus_prev = n;
6413 prev->d_func()->focus_next = q;
6416 n->d_func()->focus_next = topLevel;
6418 //repair the new list
6419 n->d_func()->focus_next = q;
6427 Measures the shortest distance from a point to a rect.
6429 This function is called from QDesktopwidget::screen(QPoint) to find the
6430 closest screen for a point.
6431 In directional KeypadNavigation, it is called to find the closest
6432 widget to the current focus widget center.
6434 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6438 if (p.x() < r.left())
6439 dx = r.left() - p.x();
6440 else if (p.x() > r.right())
6441 dx = p.x() - r.right();
6442 if (p.y() < r.top())
6443 dy = r.top() - p.y();
6444 else if (p.y() > r.bottom())
6445 dy = p.y() - r.bottom();
6450 \property QWidget::frameSize
6451 \brief the size of the widget including any window frame
6453 By default, this property contains a value that depends on the user's
6454 platform and screen geometry.
6456 QSize QWidget::frameSize() const
6459 if (isWindow() && !(windowType() == Qt::Popup)) {
6460 QRect fs = d->frameStrut();
6461 return QSize(data->crect.width() + fs.left() + fs.right(),
6462 data->crect.height() + fs.top() + fs.bottom());
6464 return data->crect.size();
6467 /*! \fn void QWidget::move(int x, int y)
6471 This corresponds to move(QPoint(\a x, \a y)).
6474 void QWidget::move(const QPoint &p)
6477 setAttribute(Qt::WA_Moved);
6479 d->topData()->posFromMove = true;
6480 if (testAttribute(Qt::WA_WState_Created)) {
6481 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6482 p.y() + geometry().y() - QWidget::y(),
6483 width(), height(), true);
6484 d->setDirtyOpaqueRegion();
6486 data->crect.moveTopLeft(p); // no frame yet
6487 setAttribute(Qt::WA_PendingMoveEvent);
6491 /*! \fn void QWidget::resize(int w, int h)
6494 This corresponds to resize(QSize(\a w, \a h)).
6497 void QWidget::resize(const QSize &s)
6500 setAttribute(Qt::WA_Resized);
6501 if (testAttribute(Qt::WA_WState_Created)) {
6502 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6503 d->setDirtyOpaqueRegion();
6505 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6506 setAttribute(Qt::WA_PendingResizeEvent);
6510 void QWidget::setGeometry(const QRect &r)
6513 setAttribute(Qt::WA_Resized);
6514 setAttribute(Qt::WA_Moved);
6516 d->topData()->posFromMove = false;
6517 if (testAttribute(Qt::WA_WState_Created)) {
6518 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6519 d->setDirtyOpaqueRegion();
6521 data->crect.setTopLeft(r.topLeft());
6522 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6523 setAttribute(Qt::WA_PendingMoveEvent);
6524 setAttribute(Qt::WA_PendingResizeEvent);
6530 Saves the current geometry and state for top-level widgets.
6532 To save the geometry when the window closes, you can
6533 implement a close event like this:
6535 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6537 See the \l{Window Geometry} documentation for an overview of geometry
6538 issues with windows.
6540 Use QMainWindow::saveState() to save the geometry and the state of
6541 toolbars and dock widgets.
6543 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6545 QByteArray QWidget::saveGeometry() const
6548 // We check if the window was maximized during this invocation. If so, we need to record the
6549 // starting position as 0,0.
6551 QRect newFramePosition = frameGeometry();
6552 QRect newNormalPosition = normalGeometry();
6553 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6554 // Change the starting position
6555 newFramePosition.moveTo(0, 0);
6556 newNormalPosition.moveTo(0, 0);
6560 QDataStream stream(&array, QIODevice::WriteOnly);
6561 stream.setVersion(QDataStream::Qt_4_0);
6562 const quint32 magicNumber = 0x1D9D0CB;
6563 quint16 majorVersion = 1;
6564 quint16 minorVersion = 0;
6565 stream << magicNumber
6570 << newNormalPosition
6575 << qint32(QApplication::desktop()->screenNumber(this))
6576 << quint8(windowState() & Qt::WindowMaximized)
6577 << quint8(windowState() & Qt::WindowFullScreen);
6584 Restores the geometry and state top-level widgets stored in the
6585 byte array \a geometry. Returns true on success; otherwise
6588 If the restored geometry is off-screen, it will be modified to be
6589 inside the available screen geometry.
6591 To restore geometry saved using QSettings, you can use code like
6594 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6596 See the \l{Window Geometry} documentation for an overview of geometry
6597 issues with windows.
6599 Use QMainWindow::restoreState() to restore the geometry and the
6600 state of toolbars and dock widgets.
6602 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6604 bool QWidget::restoreGeometry(const QByteArray &geometry)
6606 if (geometry.size() < 4)
6608 QDataStream stream(geometry);
6609 stream.setVersion(QDataStream::Qt_4_0);
6611 const quint32 magicNumber = 0x1D9D0CB;
6612 quint32 storedMagicNumber;
6613 stream >> storedMagicNumber;
6614 if (storedMagicNumber != magicNumber)
6617 const quint16 currentMajorVersion = 1;
6618 quint16 majorVersion = 0;
6619 quint16 minorVersion = 0;
6621 stream >> majorVersion >> minorVersion;
6623 if (majorVersion != currentMajorVersion)
6625 // (Allow all minor versions.)
6627 QRect restoredFrameGeometry;
6628 QRect restoredNormalGeometry;
6629 qint32 restoredScreenNumber;
6633 stream >> restoredFrameGeometry
6634 >> restoredNormalGeometry
6635 >> restoredScreenNumber
6639 const int frameHeight = 20;
6640 if (!restoredFrameGeometry.isValid())
6641 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6643 if (!restoredNormalGeometry.isValid())
6644 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6645 if (!restoredNormalGeometry.isValid()) {
6646 // use the widget's adjustedSize if the sizeHint() doesn't help
6647 restoredNormalGeometry.setSize(restoredNormalGeometry
6649 .expandedTo(d_func()->adjustedSize()));
6652 const QDesktopWidget * const desktop = QApplication::desktop();
6653 if (restoredScreenNumber >= desktop->numScreens())
6654 restoredScreenNumber = desktop->primaryScreen();
6656 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6658 // Modify the restored geometry if we are about to restore to coordinates
6659 // that would make the window "lost". This happens if:
6660 // - The restored geometry is completely oustside the available geometry
6661 // - The title bar is outside the available geometry.
6662 // - (Mac only) The window is higher than the available geometry. It must
6663 // be possible to bring the size grip on screen by moving the window.
6665 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6666 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6669 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6670 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6671 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6672 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6674 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6676 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6677 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6678 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6679 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6681 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6683 if (maximized || fullScreen) {
6684 // set geomerty before setting the window state to make
6685 // sure the window is maximized to the right screen.
6686 // Skip on windows: the window is restored into a broken
6687 // half-maximized state.
6689 setGeometry(restoredNormalGeometry);
6691 Qt::WindowStates ws = windowState();
6693 ws |= Qt::WindowMaximized;
6695 ws |= Qt::WindowFullScreen;
6697 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6702 offset = d_func()->topData()->fullScreenOffset;
6704 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6705 move(restoredFrameGeometry.topLeft() + offset);
6706 resize(restoredNormalGeometry.size());
6711 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6714 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6718 Sets the margins around the contents of the widget to have the sizes
6719 \a left, \a top, \a right, and \a bottom. The margins are used by
6720 the layout system, and may be used by subclasses to specify the area
6721 to draw in (e.g. excluding the frame).
6723 Changing the margins will trigger a resizeEvent().
6725 \sa contentsRect(), getContentsMargins()
6727 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6730 if (left == d->leftmargin && top == d->topmargin
6731 && right == d->rightmargin && bottom == d->bottommargin)
6733 d->leftmargin = left;
6735 d->rightmargin = right;
6736 d->bottommargin = bottom;
6738 if (QLayout *l=d->layout)
6739 l->update(); //force activate; will do updateGeometry
6745 QResizeEvent e(data->crect.size(), data->crect.size());
6746 QApplication::sendEvent(this, &e);
6748 setAttribute(Qt::WA_PendingResizeEvent, true);
6751 QEvent e(QEvent::ContentsRectChange);
6752 QApplication::sendEvent(this, &e);
6759 \brief The setContentsMargins function sets the margins around the
6762 Sets the margins around the contents of the widget to have the
6763 sizes determined by \a margins. The margins are
6764 used by the layout system, and may be used by subclasses to
6765 specify the area to draw in (e.g. excluding the frame).
6767 Changing the margins will trigger a resizeEvent().
6769 \sa contentsRect(), getContentsMargins()
6771 void QWidget::setContentsMargins(const QMargins &margins)
6773 setContentsMargins(margins.left(), margins.top(),
6774 margins.right(), margins.bottom());
6778 Returns the widget's contents margins for \a left, \a top, \a
6779 right, and \a bottom.
6781 \sa setContentsMargins(), contentsRect()
6783 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6787 *left = d->leftmargin;
6789 *top = d->topmargin;
6791 *right = d->rightmargin;
6793 *bottom = d->bottommargin;
6799 \brief The contentsMargins function returns the widget's contents margins.
6801 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6803 QMargins QWidget::contentsMargins() const
6806 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6811 Returns the area inside the widget's margins.
6813 \sa setContentsMargins(), getContentsMargins()
6815 QRect QWidget::contentsRect() const
6818 return QRect(QPoint(d->leftmargin, d->topmargin),
6819 QPoint(data->crect.width() - 1 - d->rightmargin,
6820 data->crect.height() - 1 - d->bottommargin));
6827 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6829 This signal is emitted when the widget's \l contextMenuPolicy is
6830 Qt::CustomContextMenu, and the user has requested a context menu on
6831 the widget. The position \a pos is the position of the context menu
6832 event that the widget receives. Normally this is in widget
6833 coordinates. The exception to this rule is QAbstractScrollArea and
6834 its subclasses that map the context menu event to coordinates of the
6835 \link QAbstractScrollArea::viewport() viewport() \endlink .
6838 \sa mapToGlobal() QMenu contextMenuPolicy
6843 \property QWidget::contextMenuPolicy
6844 \brief how the widget shows a context menu
6846 The default value of this property is Qt::DefaultContextMenu,
6847 which means the contextMenuEvent() handler is called. Other values
6848 are Qt::NoContextMenu, Qt::PreventContextMenu,
6849 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6850 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6853 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6856 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6858 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6861 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6863 data->context_menu_policy = (uint) policy;
6867 \property QWidget::focusPolicy
6868 \brief the way the widget accepts keyboard focus
6870 The policy is Qt::TabFocus if the widget accepts keyboard
6871 focus by tabbing, Qt::ClickFocus if the widget accepts
6872 focus by clicking, Qt::StrongFocus if it accepts both, and
6873 Qt::NoFocus (the default) if it does not accept focus at
6876 You must enable keyboard focus for a widget if it processes
6877 keyboard events. This is normally done from the widget's
6878 constructor. For instance, the QLineEdit constructor calls
6879 setFocusPolicy(Qt::StrongFocus).
6881 If the widget has a focus proxy, then the focus policy will
6882 be propagated to it.
6884 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6888 Qt::FocusPolicy QWidget::focusPolicy() const
6890 return (Qt::FocusPolicy)data->focus_policy;
6893 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6895 data->focus_policy = (uint) policy;
6897 if (d->extra && d->extra->focus_proxy)
6898 d->extra->focus_proxy->setFocusPolicy(policy);
6902 \property QWidget::updatesEnabled
6903 \brief whether updates are enabled
6905 An updates enabled widget receives paint events and has a system
6906 background; a disabled widget does not. This also implies that
6907 calling update() and repaint() has no effect if updates are
6910 By default, this property is true.
6912 setUpdatesEnabled() is normally used to disable updates for a
6913 short period of time, for instance to avoid screen flicker during
6914 large changes. In Qt, widgets normally do not generate screen
6915 flicker, but on X11 the server might erase regions on the screen
6916 when widgets get hidden before they can be replaced by other
6917 widgets. Disabling updates solves this.
6920 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6922 Disabling a widget implicitly disables all its children. Enabling a widget
6923 enables all child widgets \e except top-level widgets or those that
6924 have been explicitly disabled. Re-enabling updates implicitly calls
6925 update() on the widget.
6929 void QWidget::setUpdatesEnabled(bool enable)
6932 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6933 d->setUpdatesEnabled_helper(enable);
6936 /*! \fn void QWidget::show()
6938 Shows the widget and its child widgets. This function is
6939 equivalent to setVisible(true).
6941 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6942 showNormal(), isVisible()
6948 Makes the widget visible in the isVisible() meaning of the word.
6949 It is only called for toplevels or widgets with visible parents.
6951 void QWidgetPrivate::show_recursive()
6954 // polish if necessary
6956 if (!q->testAttribute(Qt::WA_WState_Created))
6957 createRecursively();
6958 q->ensurePolished();
6960 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6961 q->parentWidget()->d_func()->layout->activate();
6962 // activate our layout before we and our children become visible
6969 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6973 disableUpdates = disableUpdates && q->updatesEnabled();
6975 q->setAttribute(Qt::WA_UpdatesDisabled);
6977 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6978 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6979 QApplication::sendEvent(q, &e);
6980 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6983 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6984 QResizeEvent e(data.crect.size(), QSize());
6985 QApplication::sendEvent(q, &e);
6986 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6990 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6995 for (int i = 0; i < children.size(); ++i) {
6996 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6997 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
7001 void QWidgetPrivate::activateChildLayoutsRecursively()
7003 sendPendingMoveAndResizeEvents(false, true);
7005 for (int i = 0; i < children.size(); ++i) {
7006 QWidget *child = qobject_cast<QWidget *>(children.at(i));
7007 if (!child || child->isHidden() || child->isWindow())
7010 child->ensurePolished();
7012 // Activate child's layout
7013 QWidgetPrivate *childPrivate = child->d_func();
7014 if (childPrivate->layout)
7015 childPrivate->layout->activate();
7017 // Pretend we're visible.
7018 const bool wasVisible = child->isVisible();
7020 child->setAttribute(Qt::WA_WState_Visible);
7022 // Do the same for all my children.
7023 childPrivate->activateChildLayoutsRecursively();
7025 // We're not cheating anymore.
7027 child->setAttribute(Qt::WA_WState_Visible, false);
7031 void QWidgetPrivate::show_helper()
7034 data.in_show = true; // qws optimization
7035 // make sure we receive pending move and resize events
7036 sendPendingMoveAndResizeEvents();
7038 // become visible before showing all children
7039 q->setAttribute(Qt::WA_WState_Visible);
7041 // finally show all children recursively
7042 showChildren(false);
7046 // popup handling: new popups and tools need to be raised, and
7047 // existing popups must be closed. Also propagate the current
7048 // windows's KeyboardFocusChange status.
7049 if (q->isWindow()) {
7050 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7052 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7053 q->setAttribute(Qt::WA_KeyboardFocusChange);
7055 while (QApplication::activePopupWidget()) {
7056 if (!QApplication::activePopupWidget()->close())
7062 // Automatic embedding of child windows of widgets already embedded into
7063 // QGraphicsProxyWidget when they are shown the first time.
7064 bool isEmbedded = false;
7065 #ifndef QT_NO_GRAPHICSVIEW
7066 if (q->isWindow()) {
7067 isEmbedded = q->graphicsProxyWidget() ? true : false;
7068 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7069 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7070 if (ancestorProxy) {
7072 ancestorProxy->d_func()->embedSubWindow(q);
7077 Q_UNUSED(isEmbedded);
7080 // On Windows, show the popup now so that our own focus handling
7081 // stores the correct old focus widget even if it's stolen in the
7083 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7084 if (!isEmbedded && q->windowType() == Qt::Popup)
7085 qApp->d_func()->openPopup(q);
7088 // send the show event before showing the window
7089 QShowEvent showEvent;
7090 QApplication::sendEvent(q, &showEvent);
7094 if (!isEmbedded && q->windowType() == Qt::Popup)
7095 qApp->d_func()->openPopup(q);
7097 #ifndef QT_NO_ACCESSIBILITY
7098 if (q->windowType() != Qt::ToolTip) { // Tooltips are read aloud twice in MS narrator.
7099 QAccessibleEvent event(q, QAccessible::ObjectShow);
7100 QAccessible::updateAccessibility(&event);
7104 if (QApplicationPrivate::hidden_focus_widget == q) {
7105 QApplicationPrivate::hidden_focus_widget = 0;
7106 q->setFocus(Qt::OtherFocusReason);
7109 // Process events when showing a Qt::SplashScreen widget before the event loop
7110 // is spinnning; otherwise it might not show up on particular platforms.
7111 // This makes QSplashScreen behave the same on all platforms.
7112 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7113 QApplication::processEvents();
7115 data.in_show = false; // reset qws optimization
7118 /*! \fn void QWidget::hide()
7120 Hides the widget. This function is equivalent to
7124 \note If you are working with QDialog or its subclasses and you invoke
7125 the show() function after this function, the dialog will be displayed in
7126 its original position.
7128 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7133 void QWidgetPrivate::hide_helper()
7137 bool isEmbedded = false;
7138 #if !defined QT_NO_GRAPHICSVIEW
7139 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7141 Q_UNUSED(isEmbedded);
7144 if (!isEmbedded && (q->windowType() == Qt::Popup))
7145 qApp->d_func()->closePopup(q);
7147 #if defined(Q_WS_WIN)
7148 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7149 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7150 q->parentWidget()->activateWindow(); // Activate parent
7153 q->setAttribute(Qt::WA_Mapped, false);
7156 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7159 q->setAttribute(Qt::WA_WState_Visible, false);
7163 QHideEvent hideEvent;
7164 QApplication::sendEvent(q, &hideEvent);
7165 hideChildren(false);
7167 // next bit tries to move the focus if the focus widget is now
7170 qApp->d_func()->sendSyntheticEnterLeave(q);
7171 QWidget *fw = QApplication::focusWidget();
7172 while (fw && !fw->isWindow()) {
7174 q->focusNextPrevChild(true);
7177 fw = fw->parentWidget();
7181 if (QWidgetBackingStore *bs = maybeBackingStore())
7182 bs->removeDirtyWidget(q);
7184 #ifndef QT_NO_ACCESSIBILITY
7186 QAccessibleEvent event(q, QAccessible::ObjectHide);
7187 QAccessible::updateAccessibility(&event);
7193 \fn bool QWidget::isHidden() const
7195 Returns true if the widget is hidden, otherwise returns false.
7197 A hidden widget will only become visible when show() is called on
7198 it. It will not be automatically shown when the parent is shown.
7200 To check visibility, use !isVisible() instead (notice the exclamation mark).
7202 isHidden() implies !isVisible(), but a widget can be not visible
7203 and not hidden at the same time. This is the case for widgets that are children of
7204 widgets that are not visible.
7207 Widgets are hidden if:
7209 \li they were created as independent windows,
7210 \li they were created as children of visible widgets,
7211 \li hide() or setVisible(false) was called.
7216 void QWidget::setVisible(bool visible)
7218 if (visible) { // show
7219 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7224 // Designer uses a trick to make grabWidget work without showing
7225 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7226 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7227 parentWidget()->window()->d_func()->createRecursively();
7229 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7230 //but not children of non-visible parents
7231 QWidget *pw = parentWidget();
7232 if (!testAttribute(Qt::WA_WState_Created)
7233 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7237 #if defined(Q_WS_X11)
7238 if (windowType() == Qt::Window)
7239 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7242 bool wasResized = testAttribute(Qt::WA_Resized);
7243 Qt::WindowStates initialWindowState = windowState();
7245 // polish if necessary
7248 // remember that show was called explicitly
7249 setAttribute(Qt::WA_WState_ExplicitShowHide);
7250 // whether we need to inform the parent widget immediately
7251 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7252 // we are no longer hidden
7253 setAttribute(Qt::WA_WState_Hidden, false);
7255 if (needUpdateGeometry)
7256 d->updateGeometry_helper(true);
7258 // activate our layout before we and our children become visible
7260 d->layout->activate();
7263 QWidget *parent = parentWidget();
7264 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7265 parent->d_func()->layout->activate();
7266 if (parent->isWindow())
7268 parent = parent->parentWidget();
7271 parent->d_func()->setDirtyOpaqueRegion();
7274 // adjust size if necessary
7276 && (isWindow() || !parentWidget()->d_func()->layout)) {
7279 if (windowState() != initialWindowState)
7280 setWindowState(initialWindowState);
7284 setAttribute(Qt::WA_Resized, false);
7287 setAttribute(Qt::WA_KeyboardFocusChange, false);
7289 if (isWindow() || parentWidget()->isVisible()) {
7292 qApp->d_func()->sendSyntheticEnterLeave(this);
7295 QEvent showToParentEvent(QEvent::ShowToParent);
7296 QApplication::sendEvent(this, &showToParentEvent);
7298 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7300 #if defined(Q_WS_WIN)
7301 // reset WS_DISABLED style in a Blocked window
7302 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7303 && QApplicationPrivate::isBlockedByModal(this))
7305 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7306 dwStyle &= ~WS_DISABLED;
7307 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7310 if (QApplicationPrivate::hidden_focus_widget == this)
7311 QApplicationPrivate::hidden_focus_widget = 0;
7315 // hw: The test on getOpaqueRegion() needs to be more intelligent
7316 // currently it doesn't work if the widget is hidden (the region will
7317 // be clipped). The real check should be testing the cached region
7318 // (and dirty flag) directly.
7319 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7320 parentWidget()->d_func()->setDirtyOpaqueRegion();
7322 setAttribute(Qt::WA_WState_Hidden);
7323 setAttribute(Qt::WA_WState_ExplicitShowHide);
7324 if (testAttribute(Qt::WA_WState_Created))
7327 // invalidate layout similar to updateGeometry()
7328 if (!isWindow() && parentWidget()) {
7329 if (parentWidget()->d_func()->layout)
7330 parentWidget()->d_func()->layout->invalidate();
7331 else if (parentWidget()->isVisible())
7332 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7335 QEvent hideToParentEvent(QEvent::HideToParent);
7336 QApplication::sendEvent(this, &hideToParentEvent);
7340 /*!\fn void QWidget::setHidden(bool hidden)
7342 Convenience function, equivalent to setVisible(!\a hidden).
7346 void QWidgetPrivate::_q_showIfNotHidden()
7349 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7350 q->setVisible(true);
7353 void QWidgetPrivate::showChildren(bool spontaneous)
7355 QList<QObject*> childList = children;
7356 for (int i = 0; i < childList.size(); ++i) {
7357 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7359 || widget->isWindow()
7360 || widget->testAttribute(Qt::WA_WState_Hidden))
7363 widget->setAttribute(Qt::WA_Mapped);
7364 widget->d_func()->showChildren(true);
7366 QApplication::sendSpontaneousEvent(widget, &e);
7368 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7369 widget->d_func()->show_recursive();
7376 void QWidgetPrivate::hideChildren(bool spontaneous)
7378 QList<QObject*> childList = children;
7379 for (int i = 0; i < childList.size(); ++i) {
7380 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7381 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7384 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7385 // When hiding a widget we need to make sure that no mouse_down events are active, because
7386 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7387 // The solution is simple, before going through with this we check if there are any mouse_down events in
7388 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7389 // then we continue.
7390 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7391 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7392 // mouse release event. There are two ways to interpret this:
7393 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7394 // might be waiting for a release event that will never arrive.
7395 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7396 // supposed to trigger because it is not visible.
7397 if(widget == qt_button_down)
7401 widget->setAttribute(Qt::WA_Mapped, false);
7403 widget->setAttribute(Qt::WA_WState_Visible, false);
7404 widget->d_func()->hideChildren(spontaneous);
7407 QApplication::sendSpontaneousEvent(widget, &e);
7409 QApplication::sendEvent(widget, &e);
7410 if (widget->internalWinId()
7411 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7412 // hide_sys() on an ancestor won't have any affect on this
7413 // widget, so it needs an explicit hide_sys() of its own
7414 widget->d_func()->hide_sys();
7417 qApp->d_func()->sendSyntheticEnterLeave(widget);
7418 #ifndef QT_NO_ACCESSIBILITY
7420 QAccessibleEvent event(widget, QAccessible::ObjectHide);
7421 QAccessible::updateAccessibility(&event);
7427 bool QWidgetPrivate::close_helper(CloseMode mode)
7429 if (data.is_closing)
7433 data.is_closing = 1;
7435 QPointer<QWidget> that = q;
7436 QPointer<QWidget> parentWidget = q->parentWidget();
7438 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7439 if (mode != CloseNoEvent) {
7441 if (mode == CloseWithSpontaneousEvent)
7442 QApplication::sendSpontaneousEvent(q, &e);
7444 QApplication::sendEvent(q, &e);
7445 if (!that.isNull() && !e.isAccepted()) {
7446 data.is_closing = 0;
7451 if (!that.isNull() && !q->isHidden())
7454 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7455 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7458 /* if there is no non-withdrawn primary window left (except
7459 the ones without QuitOnClose), we emit the lastWindowClosed
7461 QWidgetList list = QApplication::topLevelWidgets();
7462 bool lastWindowClosed = true;
7463 for (int i = 0; i < list.size(); ++i) {
7464 QWidget *w = list.at(i);
7465 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7467 lastWindowClosed = false;
7470 if (lastWindowClosed) {
7471 QGuiApplicationPrivate::emitLastWindowClosed();
7472 QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7473 applicationPrivate->maybeQuit();
7478 if (!that.isNull()) {
7479 data.is_closing = 0;
7480 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7481 q->setAttribute(Qt::WA_DeleteOnClose, false);
7490 Closes this widget. Returns true if the widget was closed;
7491 otherwise returns false.
7493 First it sends the widget a QCloseEvent. The widget is \link
7494 hide() hidden\endlink if it \link QCloseEvent::accept()
7495 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7496 ignores\endlink the event, nothing happens. The default
7497 implementation of QWidget::closeEvent() accepts the close event.
7499 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7500 is also deleted. A close events is delivered to the widget no
7501 matter if the widget is visible or not.
7503 The \l QApplication::lastWindowClosed() signal is emitted when the
7504 last visible primary window (i.e. window with no parent) with the
7505 Qt::WA_QuitOnClose attribute set is closed. By default this
7506 attribute is set for all widgets except transient windows such as
7507 splash screens, tool windows, and popup menus.
7511 bool QWidget::close()
7513 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7517 \property QWidget::visible
7518 \brief whether the widget is visible
7520 Calling setVisible(true) or show() sets the widget to visible
7521 status if all its parent widgets up to the window are visible. If
7522 an ancestor is not visible, the widget won't become visible until
7523 all its ancestors are shown. If its size or position has changed,
7524 Qt guarantees that a widget gets move and resize events just
7525 before it is shown. If the widget has not been resized yet, Qt
7526 will adjust the widget's size to a useful default using
7529 Calling setVisible(false) or hide() hides a widget explicitly. An
7530 explicitly hidden widget will never become visible, even if all
7531 its ancestors become visible, unless you show it.
7533 A widget receives show and hide events when its visibility status
7534 changes. Between a hide and a show event, there is no need to
7535 waste CPU cycles preparing or displaying information to the user.
7536 A video application, for example, might simply stop generating new
7539 A widget that happens to be obscured by other windows on the
7540 screen is considered to be visible. The same applies to iconified
7541 windows and windows that exist on another virtual
7542 desktop (on platforms that support this concept). A widget
7543 receives spontaneous show and hide events when its mapping status
7544 is changed by the window system, e.g. a spontaneous hide event
7545 when the user minimizes the window, and a spontaneous show event
7546 when the window is restored again.
7548 You almost never have to reimplement the setVisible() function. If
7549 you need to change some settings before a widget is shown, use
7550 showEvent() instead. If you need to do some delayed initialization
7551 use the Polish event delivered to the event() function.
7553 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7554 showEvent(), hideEvent()
7559 Returns true if this widget would become visible if \a ancestor is
7560 shown; otherwise returns false.
7562 The true case occurs if neither the widget itself nor any parent
7563 up to but excluding \a ancestor has been explicitly hidden.
7565 This function will still return true if the widget is obscured by
7566 other windows on the screen, but could be physically visible if it
7567 or they were to be moved.
7569 isVisibleTo(0) is identical to isVisible().
7571 \sa show() hide() isVisible()
7574 bool QWidget::isVisibleTo(QWidget* ancestor) const
7578 const QWidget * w = this;
7579 while (!w->isHidden()
7581 && w->parentWidget()
7582 && w->parentWidget() != ancestor)
7583 w = w->parentWidget();
7584 return !w->isHidden();
7589 Returns the unobscured region where paint events can occur.
7591 For visible widgets, this is an approximation of the area not
7592 covered by other widgets; otherwise, this is an empty region.
7594 The repaint() function calls this function if necessary, so in
7595 general you do not need to call it.
7598 QRegion QWidget::visibleRegion() const
7602 QRect clipRect = d->clipRect();
7603 if (clipRect.isEmpty())
7605 QRegion r(clipRect);
7606 d->subtractOpaqueChildren(r, clipRect);
7607 d->subtractOpaqueSiblings(r);
7612 QSize QWidgetPrivate::adjustedSize() const
7616 QSize s = q->sizeHint();
7618 if (q->isWindow()) {
7619 Qt::Orientations exp;
7621 if (layout->hasHeightForWidth())
7622 s.setHeight(layout->totalHeightForWidth(s.width()));
7623 exp = layout->expandingDirections();
7626 if (q->sizePolicy().hasHeightForWidth())
7627 s.setHeight(q->heightForWidth(s.width()));
7628 exp = q->sizePolicy().expandingDirections();
7630 if (exp & Qt::Horizontal)
7631 s.setWidth(qMax(s.width(), 200));
7632 if (exp & Qt::Vertical)
7633 s.setHeight(qMax(s.height(), 100));
7634 #if defined(Q_WS_X11)
7635 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7637 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7639 #if defined (Q_OS_WINCE)
7640 s.setWidth(qMin(s.width(), screen.width()));
7641 s.setHeight(qMin(s.height(), screen.height()));
7643 s.setWidth(qMin(s.width(), screen.width()*2/3));
7644 s.setHeight(qMin(s.height(), screen.height()*2/3));
7646 if (QTLWExtra *extra = maybeTopData())
7647 extra->sizeAdjusted = true;
7651 QRect r = q->childrenRect(); // get children rectangle
7654 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7661 Adjusts the size of the widget to fit its contents.
7663 This function uses sizeHint() if it is valid, i.e., the size hint's width
7664 and height are \>= 0. Otherwise, it sets the size to the children
7665 rectangle that covers all child widgets (the union of all child widget
7668 For windows, the screen size is also taken into account. If the sizeHint()
7669 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7670 {expanding}, the window will be at least (200, 100). The maximum size of
7671 a window is 2/3 of the screen's width and height.
7673 \sa sizeHint(), childrenRect()
7676 void QWidget::adjustSize()
7680 QSize s = d->adjustedSize();
7683 d->layout->activate();
7691 \property QWidget::sizeHint
7692 \brief the recommended size for the widget
7694 If the value of this property is an invalid size, no size is
7697 The default implementation of sizeHint() returns an invalid size
7698 if there is no layout for this widget, and returns the layout's
7699 preferred size otherwise.
7701 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7702 setMinimumSize(), updateGeometry()
7705 QSize QWidget::sizeHint() const
7709 return d->layout->totalSizeHint();
7710 return QSize(-1, -1);
7714 \property QWidget::minimumSizeHint
7715 \brief the recommended minimum size for the widget
7717 If the value of this property is an invalid size, no minimum size
7720 The default implementation of minimumSizeHint() returns an invalid
7721 size if there is no layout for this widget, and returns the
7722 layout's minimum size otherwise. Most built-in widgets reimplement
7725 \l QLayout will never resize a widget to a size smaller than the
7726 minimum size hint unless minimumSize() is set or the size policy is
7727 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7728 size hint will be ignored.
7730 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7732 QSize QWidget::minimumSizeHint() const
7736 return d->layout->totalMinimumSize();
7737 return QSize(-1, -1);
7742 \fn QWidget *QWidget::parentWidget() const
7744 Returns the parent of this widget, or 0 if it does not have any
7750 Returns true if this widget is a parent, (or grandparent and so on
7751 to any level), of the given \a child, and both widgets are within
7752 the same window; otherwise returns false.
7755 bool QWidget::isAncestorOf(const QWidget *child) const
7760 if (child->isWindow())
7762 child = child->parentWidget();
7767 #if defined(Q_WS_WIN)
7768 inline void setDisabledStyle(QWidget *w, bool setStyle)
7770 // set/reset WS_DISABLED style.
7771 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7772 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7773 LONG newStyle = dwStyle;
7775 newStyle |= WS_DISABLED;
7777 newStyle &= ~WS_DISABLED;
7778 if (newStyle != dwStyle) {
7779 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7780 // we might need to repaint in some situations (eg. menu)
7787 /*****************************************************************************
7788 QWidget event handling
7789 *****************************************************************************/
7792 This is the main event handler; it handles event \a event. You can
7793 reimplement this function in a subclass, but we recommend using
7794 one of the specialized event handlers instead.
7796 Key press and release events are treated differently from other
7797 events. event() checks for Tab and Shift+Tab and tries to move the
7798 focus appropriately. If there is no widget to move the focus to
7799 (or the key press is not Tab or Shift+Tab), event() calls
7802 Mouse and tablet event handling is also slightly special: only
7803 when the widget is \l enabled, event() will call the specialized
7804 handlers such as mousePressEvent(); otherwise it will discard the
7807 This function returns true if the event was recognized, otherwise
7808 it returns false. If the recognized event was accepted (see \l
7809 QEvent::accepted), any further processing such as event
7810 propagation to the parent widget stops.
7812 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7813 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7814 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7815 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7816 QObject::event(), QObject::timerEvent()
7819 bool QWidget::event(QEvent *event)
7823 // ignore mouse events when disabled
7825 switch(event->type()) {
7826 case QEvent::TabletPress:
7827 case QEvent::TabletRelease:
7828 case QEvent::TabletMove:
7829 case QEvent::MouseButtonPress:
7830 case QEvent::MouseButtonRelease:
7831 case QEvent::MouseButtonDblClick:
7832 case QEvent::MouseMove:
7833 case QEvent::TouchBegin:
7834 case QEvent::TouchUpdate:
7835 case QEvent::TouchEnd:
7836 case QEvent::TouchCancel:
7837 case QEvent::ContextMenu:
7838 #ifndef QT_NO_WHEELEVENT
7846 switch (event->type()) {
7847 case QEvent::MouseMove:
7848 mouseMoveEvent((QMouseEvent*)event);
7851 case QEvent::MouseButtonPress:
7852 mousePressEvent((QMouseEvent*)event);
7855 case QEvent::MouseButtonRelease:
7856 mouseReleaseEvent((QMouseEvent*)event);
7859 case QEvent::MouseButtonDblClick:
7860 mouseDoubleClickEvent((QMouseEvent*)event);
7862 #ifndef QT_NO_WHEELEVENT
7864 wheelEvent((QWheelEvent*)event);
7867 #ifndef QT_NO_TABLETEVENT
7868 case QEvent::TabletMove:
7869 case QEvent::TabletPress:
7870 case QEvent::TabletRelease:
7871 tabletEvent((QTabletEvent*)event);
7874 case QEvent::KeyPress: {
7875 QKeyEvent *k = (QKeyEvent *)event;
7877 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7878 if (k->key() == Qt::Key_Backtab
7879 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7880 res = focusNextPrevChild(false);
7881 else if (k->key() == Qt::Key_Tab)
7882 res = focusNextPrevChild(true);
7887 #ifdef QT_KEYPAD_NAVIGATION
7888 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7889 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7890 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7891 if (k->key() == Qt::Key_Up)
7892 res = focusNextPrevChild(false);
7893 else if (k->key() == Qt::Key_Down)
7894 res = focusNextPrevChild(true);
7895 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7896 if (k->key() == Qt::Key_Up)
7897 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7898 else if (k->key() == Qt::Key_Right)
7899 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7900 else if (k->key() == Qt::Key_Down)
7901 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7902 else if (k->key() == Qt::Key_Left)
7903 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7911 #ifndef QT_NO_WHATSTHIS
7912 if (!k->isAccepted()
7913 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7914 && d->whatsThis.size()) {
7915 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7922 case QEvent::KeyRelease:
7923 keyReleaseEvent((QKeyEvent*)event);
7925 case QEvent::ShortcutOverride:
7928 case QEvent::InputMethod:
7929 inputMethodEvent((QInputMethodEvent *) event);
7932 case QEvent::InputMethodQuery:
7933 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7934 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7935 Qt::InputMethodQueries queries = query->queries();
7936 for (uint i = 0; i < 32; ++i) {
7937 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7939 QVariant v = inputMethodQuery(q);
7940 if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7941 v = QVariant(true); // special case for Qt4 compatibility
7942 query->setValue(q, v);
7949 case QEvent::PolishRequest:
7953 case QEvent::Polish: {
7954 style()->polish(this);
7955 setAttribute(Qt::WA_WState_Polished);
7956 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7958 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7959 d->resolvePalette();
7963 case QEvent::ApplicationWindowIconChange:
7964 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7965 d->setWindowIcon_sys();
7966 d->setWindowIcon_helper();
7969 case QEvent::FocusIn:
7970 #ifdef QT_SOFTKEYS_ENABLED
7971 QSoftKeyManager::updateSoftKeys();
7973 focusInEvent((QFocusEvent*)event);
7974 d->updateWidgetTransform();
7977 case QEvent::FocusOut:
7978 focusOutEvent((QFocusEvent*)event);
7982 #ifndef QT_NO_STATUSTIP
7983 if (d->statusTip.size()) {
7984 QStatusTipEvent tip(d->statusTip);
7985 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7992 #ifndef QT_NO_STATUSTIP
7993 if (d->statusTip.size()) {
7995 QStatusTipEvent tip(empty);
7996 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8002 case QEvent::HoverEnter:
8003 case QEvent::HoverLeave:
8008 // At this point the event has to be delivered, regardless
8009 // whether the widget isVisible() or not because it
8010 // already went through the filters
8011 paintEvent((QPaintEvent*)event);
8015 moveEvent((QMoveEvent*)event);
8016 d->updateWidgetTransform();
8019 case QEvent::Resize:
8020 resizeEvent((QResizeEvent*)event);
8021 d->updateWidgetTransform();
8025 closeEvent((QCloseEvent *)event);
8028 #ifndef QT_NO_CONTEXTMENU
8029 case QEvent::ContextMenu:
8030 switch (data->context_menu_policy) {
8031 case Qt::PreventContextMenu:
8033 case Qt::DefaultContextMenu:
8034 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8036 case Qt::CustomContextMenu:
8037 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8040 case Qt::ActionsContextMenu:
8041 if (d->actions.count()) {
8042 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8053 #endif // QT_NO_CONTEXTMENU
8055 #ifndef QT_NO_DRAGANDDROP
8057 dropEvent((QDropEvent*) event);
8060 case QEvent::DragEnter:
8061 dragEnterEvent((QDragEnterEvent*) event);
8064 case QEvent::DragMove:
8065 dragMoveEvent((QDragMoveEvent*) event);
8068 case QEvent::DragLeave:
8069 dragLeaveEvent((QDragLeaveEvent*) event);
8074 showEvent((QShowEvent*) event);
8078 hideEvent((QHideEvent*) event);
8081 case QEvent::ShowWindowRequest:
8086 case QEvent::ApplicationFontChange:
8089 case QEvent::ApplicationPaletteChange:
8090 if (!(windowType() == Qt::Desktop))
8091 d->resolvePalette();
8094 case QEvent::ToolBarChange:
8095 case QEvent::ActivationChange:
8096 case QEvent::EnabledChange:
8097 case QEvent::FontChange:
8098 case QEvent::StyleChange:
8099 case QEvent::PaletteChange:
8100 case QEvent::WindowTitleChange:
8101 case QEvent::IconTextChange:
8102 case QEvent::ModifiedChange:
8103 case QEvent::MouseTrackingChange:
8104 case QEvent::ParentChange:
8105 case QEvent::WindowStateChange:
8106 case QEvent::LocaleChange:
8107 case QEvent::MacSizeChange:
8108 case QEvent::ContentsRectChange:
8109 case QEvent::ThemeChange:
8113 case QEvent::WindowActivate:
8114 case QEvent::WindowDeactivate: {
8115 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8117 QList<QObject*> childList = d->children;
8118 for (int i = 0; i < childList.size(); ++i) {
8119 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8120 if (w && w->isVisible() && !w->isWindow())
8121 QApplication::sendEvent(w, event);
8124 #ifdef QT_SOFTKEYS_ENABLED
8126 QSoftKeyManager::updateSoftKeys();
8131 case QEvent::LanguageChange:
8134 QList<QObject*> childList = d->children;
8135 for (int i = 0; i < childList.size(); ++i) {
8136 QObject *o = childList.at(i);
8138 QApplication::sendEvent(o, event);
8144 case QEvent::ApplicationLayoutDirectionChange:
8145 d->resolveLayoutDirection();
8148 case QEvent::LayoutDirectionChange:
8150 d->layout->invalidate();
8154 case QEvent::UpdateRequest:
8155 d->syncBackingStore();
8157 case QEvent::UpdateLater:
8158 update(static_cast<QUpdateLaterEvent*>(event)->region());
8161 case QEvent::WindowBlocked:
8162 case QEvent::WindowUnblocked:
8164 QList<QObject*> childList = d->children;
8165 for (int i = 0; i < childList.size(); ++i) {
8166 QObject *o = childList.at(i);
8167 if (o && o != QApplication::activeModalWidget()) {
8168 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8169 // do not forward the event to child windows,
8170 // QApplication does this for us
8173 QApplication::sendEvent(o, event);
8176 #if defined(Q_WS_WIN)
8177 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8181 #ifndef QT_NO_TOOLTIP
8182 case QEvent::ToolTip:
8183 if (!d->toolTip.isEmpty())
8184 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8189 #ifndef QT_NO_WHATSTHIS
8190 case QEvent::WhatsThis:
8191 if (d->whatsThis.size())
8192 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8196 case QEvent::QueryWhatsThis:
8197 if (d->whatsThis.isEmpty())
8201 case QEvent::EmbeddingControl:
8202 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8203 data->fstrut_dirty = false;
8204 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8205 d->topData()->embedded = 1;
8208 #ifndef QT_NO_ACTION
8209 case QEvent::ActionAdded:
8210 case QEvent::ActionRemoved:
8211 case QEvent::ActionChanged:
8212 #ifdef QT_SOFTKEYS_ENABLED
8213 QSoftKeyManager::updateSoftKeys();
8215 actionEvent((QActionEvent*)event);
8219 case QEvent::KeyboardLayoutChange:
8223 // inform children of the change
8224 QList<QObject*> childList = d->children;
8225 for (int i = 0; i < childList.size(); ++i) {
8226 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8227 if (w && w->isVisible() && !w->isWindow())
8228 QApplication::sendEvent(w, event);
8233 case QEvent::MacGLWindowChange:
8234 d->needWindowChange = false;
8237 case QEvent::TouchBegin:
8238 case QEvent::TouchUpdate:
8239 case QEvent::TouchEnd:
8240 case QEvent::TouchCancel:
8245 #ifndef QT_NO_GESTURES
8246 case QEvent::Gesture:
8250 #ifndef QT_NO_PROPERTIES
8251 case QEvent::DynamicPropertyChange: {
8252 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8253 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8254 uint value = property(propName.constData()).toUInt();
8257 const char axis = propName.at(12);
8259 d->extra->customDpiX = value;
8260 else if (axis == 'Y')
8261 d->extra->customDpiY = value;
8262 d->updateFont(d->data.fnt);
8268 return QObject::event(event);
8274 This event handler can be reimplemented to handle state changes.
8276 The state being changed in this event can be retrieved through the \a event
8279 Change events include: QEvent::ToolBarChange,
8280 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8281 QEvent::StyleChange, QEvent::PaletteChange,
8282 QEvent::WindowTitleChange, QEvent::IconTextChange,
8283 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8284 QEvent::ParentChange, QEvent::WindowStateChange,
8285 QEvent::LanguageChange, QEvent::LocaleChange,
8286 QEvent::LayoutDirectionChange.
8289 void QWidget::changeEvent(QEvent * event)
8291 switch(event->type()) {
8292 case QEvent::EnabledChange: {
8294 #ifndef QT_NO_ACCESSIBILITY
8295 QAccessible::State s;
8297 QAccessibleStateChangeEvent event(this, s);
8298 QAccessible::updateAccessibility(&event);
8303 case QEvent::FontChange:
8304 case QEvent::StyleChange: {
8309 d->layout->invalidate();
8313 case QEvent::PaletteChange:
8317 case QEvent::ThemeChange:
8318 if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8319 && qApp && !QApplication::closingDown()) {
8320 if (testAttribute(Qt::WA_WState_Polished))
8321 QApplication::style()->unpolish(this);
8322 if (testAttribute(Qt::WA_WState_Polished))
8323 QApplication::style()->polish(this);
8324 QEvent styleChangedEvent(QEvent::StyleChange);
8325 QCoreApplication::sendEvent(this, &styleChangedEvent);
8332 case QEvent::MacSizeChange:
8335 case QEvent::ToolTipChange:
8336 case QEvent::MouseTrackingChange:
8337 qt_mac_update_mouseTracking(this);
8347 This event handler, for event \a event, can be reimplemented in a
8348 subclass to receive mouse move events for the widget.
8350 If mouse tracking is switched off, mouse move events only occur if
8351 a mouse button is pressed while the mouse is being moved. If mouse
8352 tracking is switched on, mouse move events occur even if no mouse
8355 QMouseEvent::pos() reports the position of the mouse cursor,
8356 relative to this widget. For press and release events, the
8357 position is usually the same as the position of the last mouse
8358 move event, but it might be different if the user's hand shakes.
8359 This is a feature of the underlying window system, not Qt.
8361 If you want to show a tooltip immediately, while the mouse is
8362 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8363 and show them as a tooltip), you must first enable mouse tracking
8364 as described above. Then, to ensure that the tooltip is updated
8365 immediately, you must call QToolTip::showText() instead of
8366 setToolTip() in your implementation of mouseMoveEvent().
8368 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8369 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8372 void QWidget::mouseMoveEvent(QMouseEvent *event)
8378 This event handler, for event \a event, can be reimplemented in a
8379 subclass to receive mouse press events for the widget.
8381 If you create new widgets in the mousePressEvent() the
8382 mouseReleaseEvent() may not end up where you expect, depending on
8383 the underlying window system (or X11 window manager), the widgets'
8384 location and maybe more.
8386 The default implementation implements the closing of popup widgets
8387 when you click outside the window. For other widget types it does
8390 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8391 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8394 void QWidget::mousePressEvent(QMouseEvent *event)
8397 if ((windowType() == Qt::Popup)) {
8400 while ((w = QApplication::activePopupWidget()) && w != this){
8402 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8403 w->hide(); // hide at least
8405 if (!rect().contains(event->pos())){
8412 This event handler, for event \a event, can be reimplemented in a
8413 subclass to receive mouse release events for the widget.
8415 \sa mousePressEvent(), mouseDoubleClickEvent(),
8416 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8419 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8425 This event handler, for event \a event, can be reimplemented in a
8426 subclass to receive mouse double click events for the widget.
8428 The default implementation generates a normal mouse press event.
8430 \note The widget will also receive mouse press and mouse release
8431 events in addition to the double click event. It is up to the
8432 developer to ensure that the application interprets these events
8435 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8436 event(), QMouseEvent
8439 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8444 #ifndef QT_NO_WHEELEVENT
8446 This event handler, for event \a event, can be reimplemented in a
8447 subclass to receive wheel events for the widget.
8449 If you reimplement this handler, it is very important that you
8450 \link QWheelEvent ignore()\endlink the event if you do not handle
8451 it, so that the widget's parent can interpret it.
8453 The default implementation ignores the event.
8455 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8459 void QWidget::wheelEvent(QWheelEvent *event)
8463 #endif // QT_NO_WHEELEVENT
8465 #ifndef QT_NO_TABLETEVENT
8467 This event handler, for event \a event, can be reimplemented in a
8468 subclass to receive tablet events for the widget.
8470 If you reimplement this handler, it is very important that you
8471 \link QTabletEvent ignore()\endlink the event if you do not handle
8472 it, so that the widget's parent can interpret it.
8474 The default implementation ignores the event.
8476 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8480 void QWidget::tabletEvent(QTabletEvent *event)
8484 #endif // QT_NO_TABLETEVENT
8487 This event handler, for event \a event, can be reimplemented in a
8488 subclass to receive key press events for the widget.
8490 A widget must call setFocusPolicy() to accept focus initially and
8491 have focus in order to receive a key press event.
8493 If you reimplement this handler, it is very important that you
8494 call the base class implementation if you do not act upon the key.
8496 The default implementation closes popup widgets if the user
8497 presses Esc. Otherwise the event is ignored, so that the widget's
8498 parent can interpret it.
8500 Note that QKeyEvent starts with isAccepted() == true, so you do not
8501 need to call QKeyEvent::accept() - just do not call the base class
8502 implementation if you act upon the key.
8504 \sa keyReleaseEvent(), setFocusPolicy(),
8505 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8508 void QWidget::keyPressEvent(QKeyEvent *event)
8510 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8519 This event handler, for event \a event, can be reimplemented in a
8520 subclass to receive key release events for the widget.
8522 A widget must \link setFocusPolicy() accept focus\endlink
8523 initially and \link hasFocus() have focus\endlink in order to
8524 receive a key release event.
8526 If you reimplement this handler, it is very important that you
8527 call the base class implementation if you do not act upon the key.
8529 The default implementation ignores the event, so that the widget's
8530 parent can interpret it.
8532 Note that QKeyEvent starts with isAccepted() == true, so you do not
8533 need to call QKeyEvent::accept() - just do not call the base class
8534 implementation if you act upon the key.
8536 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8537 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8540 void QWidget::keyReleaseEvent(QKeyEvent *event)
8546 \fn void QWidget::focusInEvent(QFocusEvent *event)
8548 This event handler can be reimplemented in a subclass to receive
8549 keyboard focus events (focus received) for the widget. The event
8550 is passed in the \a event parameter
8552 A widget normally must setFocusPolicy() to something other than
8553 Qt::NoFocus in order to receive focus events. (Note that the
8554 application programmer can call setFocus() on any widget, even
8555 those that do not normally accept focus.)
8557 The default implementation updates the widget (except for windows
8558 that do not specify a focusPolicy()).
8560 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8561 keyReleaseEvent(), event(), QFocusEvent
8564 void QWidget::focusInEvent(QFocusEvent *)
8566 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8572 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8574 This event handler can be reimplemented in a subclass to receive
8575 keyboard focus events (focus lost) for the widget. The events is
8576 passed in the \a event parameter.
8578 A widget normally must setFocusPolicy() to something other than
8579 Qt::NoFocus in order to receive focus events. (Note that the
8580 application programmer can call setFocus() on any widget, even
8581 those that do not normally accept focus.)
8583 The default implementation updates the widget (except for windows
8584 that do not specify a focusPolicy()).
8586 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8587 keyReleaseEvent(), event(), QFocusEvent
8590 void QWidget::focusOutEvent(QFocusEvent *)
8592 if (focusPolicy() != Qt::NoFocus || !isWindow())
8597 \fn void QWidget::enterEvent(QEvent *event)
8599 This event handler can be reimplemented in a subclass to receive
8600 widget enter events which are passed in the \a event parameter.
8602 An event is sent to the widget when the mouse cursor enters the
8605 \sa leaveEvent(), mouseMoveEvent(), event()
8608 void QWidget::enterEvent(QEvent *)
8613 \fn void QWidget::leaveEvent(QEvent *event)
8615 This event handler can be reimplemented in a subclass to receive
8616 widget leave events which are passed in the \a event parameter.
8618 A leave event is sent to the widget when the mouse cursor leaves
8621 \sa enterEvent(), mouseMoveEvent(), event()
8624 void QWidget::leaveEvent(QEvent *)
8629 \fn void QWidget::paintEvent(QPaintEvent *event)
8631 This event handler can be reimplemented in a subclass to receive paint
8632 events passed in \a event.
8634 A paint event is a request to repaint all or part of a widget. It can
8635 happen for one of the following reasons:
8638 \li repaint() or update() was invoked,
8639 \li the widget was obscured and has now been uncovered, or
8640 \li many other reasons.
8643 Many widgets can simply repaint their entire surface when asked to, but
8644 some slow widgets need to optimize by painting only the requested region:
8645 QPaintEvent::region(). This speed optimization does not change the result,
8646 as painting is clipped to that region during event processing. QListView
8647 and QTableView do this, for example.
8649 Qt also tries to speed up painting by merging multiple paint events into
8650 one. When update() is called several times or the window system sends
8651 several paint events, Qt merges these events into one event with a larger
8652 region (see QRegion::united()). The repaint() function does not permit this
8653 optimization, so we suggest using update() whenever possible.
8655 When the paint event occurs, the update region has normally been erased, so
8656 you are painting on the widget's background.
8658 The background can be set using setBackgroundRole() and setPalette().
8660 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8661 is no need to write double-buffering code in paintEvent() to avoid flicker.
8663 \b{Note for the X11 platform}: It is possible to toggle global double
8664 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8666 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8668 \note Generally, you should refrain from calling update() or repaint()
8669 \b{inside} a paintEvent(). For example, calling update() or repaint() on
8670 children inside a paintevent() results in undefined behavior; the child may
8671 or may not get a paint event.
8673 \warning If you are using a custom paint engine without Qt's backingstore,
8674 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8675 never be called; the backingstore will be used instead.
8677 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8678 {Analog Clock Example}
8681 void QWidget::paintEvent(QPaintEvent *)
8687 \fn void QWidget::moveEvent(QMoveEvent *event)
8689 This event handler can be reimplemented in a subclass to receive
8690 widget move events which are passed in the \a event parameter.
8691 When the widget receives this event, it is already at the new
8694 The old position is accessible through QMoveEvent::oldPos().
8696 \sa resizeEvent(), event(), move(), QMoveEvent
8699 void QWidget::moveEvent(QMoveEvent *)
8705 This event handler can be reimplemented in a subclass to receive
8706 widget resize events which are passed in the \a event parameter.
8707 When resizeEvent() is called, the widget already has its new
8708 geometry. The old size is accessible through
8709 QResizeEvent::oldSize().
8711 The widget will be erased and receive a paint event immediately
8712 after processing the resize event. No drawing need be (or should
8713 be) done inside this handler.
8716 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8720 void QWidget::resizeEvent(QResizeEvent * /* event */)
8724 #ifndef QT_NO_ACTION
8726 \fn void QWidget::actionEvent(QActionEvent *event)
8728 This event handler is called with the given \a event whenever the
8729 widget's actions are changed.
8731 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8733 void QWidget::actionEvent(QActionEvent *)
8740 This event handler is called with the given \a event when Qt receives a window
8741 close request for a top-level widget from the window system.
8743 By default, the event is accepted and the widget is closed. You can reimplement
8744 this function to change the way the widget responds to window close requests.
8745 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8748 Main window applications typically use reimplementations of this function to check
8749 whether the user's work has been saved and ask for permission before closing.
8750 For example, the \l{Application Example} uses a helper function to determine whether
8751 or not to close the window:
8753 \snippet mainwindows/application/mainwindow.cpp 3
8754 \snippet mainwindows/application/mainwindow.cpp 4
8756 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8759 void QWidget::closeEvent(QCloseEvent *event)
8764 #ifndef QT_NO_CONTEXTMENU
8766 This event handler, for event \a event, can be reimplemented in a
8767 subclass to receive widget context menu events.
8769 The handler is called when the widget's \l contextMenuPolicy is
8770 Qt::DefaultContextMenu.
8772 The default implementation ignores the context event.
8773 See the \l QContextMenuEvent documentation for more details.
8775 \sa event(), QContextMenuEvent customContextMenuRequested()
8778 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8782 #endif // QT_NO_CONTEXTMENU
8786 This event handler, for event \a event, can be reimplemented in a
8787 subclass to receive Input Method composition events. This handler
8788 is called when the state of the input method changes.
8790 Note that when creating custom text editing widgets, the
8791 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8792 (using the setAttribute() function) in order to receive input
8795 The default implementation calls event->ignore(), which rejects the
8796 Input Method event. See the \l QInputMethodEvent documentation for more
8799 \sa event(), QInputMethodEvent
8801 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8807 This method is only relevant for input widgets. It is used by the
8808 input method to query a set of properties of the widget to be
8809 able to support complex input method operations as support for
8810 surrounding text and reconversions.
8812 \a query specifies which property is queried.
8814 \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8816 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8819 case Qt::ImCursorRectangle:
8820 return QRect(width()/2, 0, 1, height());
8823 case Qt::ImAnchorPosition:
8825 return inputMethodQuery(Qt::ImCursorPosition);
8827 return (int)inputMethodHints();
8834 \property QWidget::inputMethodHints
8835 \brief What input method specific hints the widget has.
8837 This is only relevant for input widgets. It is used by
8838 the input method to retrieve hints as to how the input method
8839 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8840 is set, the input method may change its visual components to reflect
8841 that only numbers can be entered.
8843 \note The flags are only hints, so the particular input method
8844 implementation is free to ignore them. If you want to be
8845 sure that a certain type of characters are entered,
8846 you should also set a QValidator on the widget.
8848 The default value is Qt::ImhNone.
8852 \sa inputMethodQuery()
8854 Qt::InputMethodHints QWidget::inputMethodHints() const
8857 const QWidgetPrivate *priv = d_func();
8858 while (priv->inheritsInputMethodHints) {
8859 priv = priv->q_func()->parentWidget()->d_func();
8862 return priv->imHints;
8868 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8873 qApp->inputMethod()->update(Qt::ImHints);
8878 #ifndef QT_NO_DRAGANDDROP
8881 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8883 This event handler is called when a drag is in progress and the
8884 mouse enters this widget. The event is passed in the \a event parameter.
8886 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8889 See the \link dnd.html Drag-and-drop documentation\endlink for an
8890 overview of how to provide drag-and-drop in your application.
8892 \sa QDrag, QDragEnterEvent
8894 void QWidget::dragEnterEvent(QDragEnterEvent *)
8899 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8901 This event handler is called if a drag is in progress, and when
8902 any of the following conditions occur: the cursor enters this widget,
8903 the cursor moves within this widget, or a modifier key is pressed on
8904 the keyboard while this widget has the focus. The event is passed
8905 in the \a event parameter.
8907 See the \link dnd.html Drag-and-drop documentation\endlink for an
8908 overview of how to provide drag-and-drop in your application.
8910 \sa QDrag, QDragMoveEvent
8912 void QWidget::dragMoveEvent(QDragMoveEvent *)
8917 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8919 This event handler is called when a drag is in progress and the
8920 mouse leaves this widget. The event is passed in the \a event
8923 See the \link dnd.html Drag-and-drop documentation\endlink for an
8924 overview of how to provide drag-and-drop in your application.
8926 \sa QDrag, QDragLeaveEvent
8928 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8933 \fn void QWidget::dropEvent(QDropEvent *event)
8935 This event handler is called when the drag is dropped on this
8936 widget. The event is passed in the \a event parameter.
8938 See the \link dnd.html Drag-and-drop documentation\endlink for an
8939 overview of how to provide drag-and-drop in your application.
8941 \sa QDrag, QDropEvent
8943 void QWidget::dropEvent(QDropEvent *)
8947 #endif // QT_NO_DRAGANDDROP
8950 \fn void QWidget::showEvent(QShowEvent *event)
8952 This event handler can be reimplemented in a subclass to receive
8953 widget show events which are passed in the \a event parameter.
8955 Non-spontaneous show events are sent to widgets immediately
8956 before they are shown. The spontaneous show events of windows are
8957 delivered afterwards.
8959 Note: A widget receives spontaneous show and hide events when its
8960 mapping status is changed by the window system, e.g. a spontaneous
8961 hide event when the user minimizes the window, and a spontaneous
8962 show event when the window is restored again. After receiving a
8963 spontaneous hide event, a widget is still considered visible in
8964 the sense of isVisible().
8966 \sa visible, event(), QShowEvent
8968 void QWidget::showEvent(QShowEvent *)
8973 \fn void QWidget::hideEvent(QHideEvent *event)
8975 This event handler can be reimplemented in a subclass to receive
8976 widget hide events. The event is passed in the \a event parameter.
8978 Hide events are sent to widgets immediately after they have been
8981 Note: A widget receives spontaneous show and hide events when its
8982 mapping status is changed by the window system, e.g. a spontaneous
8983 hide event when the user minimizes the window, and a spontaneous
8984 show event when the window is restored again. After receiving a
8985 spontaneous hide event, a widget is still considered visible in
8986 the sense of isVisible().
8988 \sa visible, event(), QHideEvent
8990 void QWidget::hideEvent(QHideEvent *)
8995 This special event handler can be reimplemented in a subclass to
8996 receive native platform events identified by \a eventType
8997 which are passed in the \a message parameter.
8999 In your reimplementation of this function, if you want to stop the
9000 event being handled by Qt, return true and set \a result.
9001 If you return false, this native event is passed back to Qt,
9002 which translates the event into a Qt event and sends it to the widget.
9004 \note Events are only delivered to this event handler if the widget is
9005 has a native Window handle.
9007 \note This function superseedes the event filter functions
9008 x11Event(), winEvent() and macEvent() of Qt 4.
9011 \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
9012 \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
9016 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
9018 Q_UNUSED(eventType);
9025 Ensures that the widget has been polished by QStyle (i.e., has a
9026 proper font and palette).
9028 QWidget calls this function after it has been fully constructed
9029 but before it is shown the very first time. You can call this
9030 function if you want to ensure that the widget is polished before
9031 doing an operation, e.g., the correct font size might be needed in
9032 the widget's sizeHint() reimplementation. Note that this function
9033 \e is called from the default implementation of sizeHint().
9035 Polishing is useful for final initialization that must happen after
9036 all constructors (from base classes as well as from subclasses)
9039 If you need to change some settings when a widget is polished,
9040 reimplement event() and handle the QEvent::Polish event type.
9042 \b{Note:} The function is declared const so that it can be called from
9043 other const functions (e.g., sizeHint()).
9047 void QWidget::ensurePolished() const
9051 const QMetaObject *m = metaObject();
9052 if (m == d->polished)
9056 QEvent e(QEvent::Polish);
9057 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9059 // polish children after 'this'
9060 QList<QObject*> children = d->children;
9061 for (int i = 0; i < children.size(); ++i) {
9062 QObject *o = children.at(i);
9063 if(!o->isWidgetType())
9065 if (QWidget *w = qobject_cast<QWidget *>(o))
9066 w->ensurePolished();
9069 if (d->parent && d->sendChildEvents) {
9070 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9071 QCoreApplication::sendEvent(d->parent, &e);
9073 if (d->extra && d->extra->topextra && d->extra->topextra->window
9074 && d->extra->topextra->window->objectName().isEmpty()) {
9075 QString on = objectName();
9077 on = QString::fromUtf8(metaObject()->className());
9078 on += QStringLiteral("Class");
9080 on += QStringLiteral("Window");
9081 d->extra->topextra->window->setObjectName(on);
9086 Returns the mask currently set on a widget. If no mask is set the
9087 return value will be an empty region.
9089 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9091 QRegion QWidget::mask() const
9094 return d->extra ? d->extra->mask : QRegion();
9098 Returns the layout manager that is installed on this widget, or 0
9099 if no layout manager is installed.
9101 The layout manager sets the geometry of the widget's children
9102 that have been added to the layout.
9104 \sa setLayout(), sizePolicy(), {Layout Management}
9106 QLayout *QWidget::layout() const
9108 return d_func()->layout;
9113 \fn void QWidget::setLayout(QLayout *layout)
9115 Sets the layout manager for this widget to \a layout.
9117 If there already is a layout manager installed on this widget,
9118 QWidget won't let you install another. You must first delete the
9119 existing layout manager (returned by layout()) before you can
9120 call setLayout() with the new layout.
9122 If \a layout is the layout manger on a different widget, setLayout()
9123 will reparent the layout and make it the layout manager for this widget.
9127 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9129 An alternative to calling this function is to pass this widget to
9130 the layout's constructor.
9132 The QWidget will take ownership of \a layout.
9134 \sa layout(), {Layout Management}
9137 void QWidget::setLayout(QLayout *l)
9140 qWarning("QWidget::setLayout: Cannot set layout to 0");
9145 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9146 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9147 objectName().toLocal8Bit().data());
9151 QObject *oldParent = l->parent();
9152 if (oldParent && oldParent != this) {
9153 if (oldParent->isWidgetType()) {
9154 // Steal the layout off a widget parent. Takes effect when
9155 // morphing laid-out container widgets in Designer.
9156 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9157 oldParentWidget->takeLayout();
9159 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9160 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9161 objectName().toLocal8Bit().data());
9167 l->d_func()->topLevel = true;
9169 if (oldParent != this) {
9171 l->d_func()->reparentChildWidgets(this);
9175 if (isWindow() && d->maybeTopData())
9176 d->topData()->sizeAdjusted = false;
9180 \fn QLayout *QWidget::takeLayout()
9182 Remove the layout from the widget.
9186 QLayout *QWidget::takeLayout()
9189 QLayout *l = layout();
9198 \property QWidget::sizePolicy
9199 \brief the default layout behavior of the widget
9201 If there is a QLayout that manages this widget's children, the
9202 size policy specified by that layout is used. If there is no such
9203 QLayout, the result of this function is used.
9205 The default policy is Preferred/Preferred, which means that the
9206 widget can be freely resized, but prefers to be the size
9207 sizeHint() returns. Button-like widgets set the size policy to
9208 specify that they may stretch horizontally, but are fixed
9209 vertically. The same applies to lineedit controls (such as
9210 QLineEdit, QSpinBox or an editable QComboBox) and other
9211 horizontally orientated widgets (such as QProgressBar).
9212 QToolButton's are normally square, so they allow growth in both
9213 directions. Widgets that support different directions (such as
9214 QSlider, QScrollBar or QHeader) specify stretching in the
9215 respective direction only. Widgets that can provide scroll bars
9216 (usually subclasses of QScrollArea) tend to specify that they can
9217 use additional space, and that they can make do with less than
9220 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9222 QSizePolicy QWidget::sizePolicy() const
9225 return d->size_policy;
9228 void QWidget::setSizePolicy(QSizePolicy policy)
9231 setAttribute(Qt::WA_WState_OwnSizePolicy);
9232 if (policy == d->size_policy)
9234 d->size_policy = policy;
9236 #ifndef QT_NO_GRAPHICSVIEW
9237 if (QWExtra *extra = d->extra) {
9238 if (extra->proxyWidget)
9239 extra->proxyWidget->setSizePolicy(policy);
9245 if (isWindow() && d->maybeTopData())
9246 d->topData()->sizeAdjusted = false;
9250 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9253 Sets the size policy of the widget to \a horizontal and \a
9254 vertical, with standard stretch and no height-for-width.
9256 \sa QSizePolicy::QSizePolicy()
9260 Returns the preferred height for this widget, given the width \a w.
9262 If this widget has a layout, the default implementation returns
9263 the layout's preferred height. if there is no layout, the default
9264 implementation returns -1 indicating that the preferred height
9265 does not depend on the width.
9268 int QWidget::heightForWidth(int w) const
9270 if (layout() && layout()->hasHeightForWidth())
9271 return layout()->totalHeightForWidth(w);
9279 Returns true if the widget's preferred height depends on its width; otherwise returns false.
9281 bool QWidget::hasHeightForWidth() const
9284 return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9288 \fn QWidget *QWidget::childAt(int x, int y) const
9290 Returns the visible child widget at the position (\a{x}, \a{y})
9291 in the widget's coordinate system. If there is no visible child
9292 widget at the specified position, the function returns 0.
9298 Returns the visible child widget at point \a p in the widget's own
9302 QWidget *QWidget::childAt(const QPoint &p) const
9304 return d_func()->childAt_helper(p, false);
9307 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9309 if (children.isEmpty())
9314 // Unified tool bars on the Mac require special handling since they live outside
9315 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9316 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9317 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9319 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9322 if (!pointInsideRectAndMask(p))
9324 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9327 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9330 Q_UNUSED(includeFrame);
9332 for (int i = children.size() - 1; i >= 0; --i) {
9333 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9334 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9335 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9339 // Map the point 'p' from parent coordinates to child coordinates.
9340 QPoint childPoint = p;
9342 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9343 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9344 // QWidget::mapFromParent won't do the trick.
9345 if (includeFrame && qobject_cast<QToolBar *>(child))
9346 childPoint = qt_mac_nativeMapFromParent(child, p);
9349 childPoint -= child->data->crect.topLeft();
9351 // Check if the point hits the child.
9352 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9355 // Do the same for the child's descendants.
9356 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9359 // We have found our target; namely the child at position 'p'.
9365 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9369 widgetItem->invalidateSizeCache();
9371 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9372 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9373 if (parent->d_func()->layout)
9374 parent->d_func()->layout->invalidate();
9375 else if (parent->isVisible())
9376 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9382 Notifies the layout system that this widget has changed and may
9383 need to change geometry.
9385 Call this function if the sizeHint() or sizePolicy() have changed.
9387 For explicitly hidden widgets, updateGeometry() is a no-op. The
9388 layout system will be notified as soon as the widget is shown.
9391 void QWidget::updateGeometry()
9394 d->updateGeometry_helper(false);
9397 /*! \property QWidget::windowFlags
9399 Window flags are a combination of a type (e.g. Qt::Dialog) and
9400 zero or more hints to the window system (e.g.
9401 Qt::FramelessWindowHint).
9403 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9404 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9405 0) on the desktop. If the widget is a window and becomes a
9406 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9407 relative to its parent widget.
9409 \note This function calls setParent() when changing the flags for
9410 a window, causing the widget to be hidden. You must call show() to make
9411 the widget visible again..
9413 \sa windowType(), {Window Flags Example}
9415 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9417 if (data->window_flags == flags)
9422 if ((data->window_flags | flags) & Qt::Window) {
9423 // the old type was a window and/or the new type is a window
9424 QPoint oldPos = pos();
9425 bool visible = isVisible();
9426 setParent(parentWidget(), flags);
9428 // if both types are windows or neither of them are, we restore
9430 if (!((data->window_flags ^ flags) & Qt::Window)
9431 && (visible || testAttribute(Qt::WA_Moved))) {
9434 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9435 d->adjustQuitOnCloseAttribute();
9437 data->window_flags = flags;
9442 Sets the window flags for the widget to \a flags,
9443 \e without telling the window system.
9445 \warning Do not call this function unless you really know what
9448 \sa setWindowFlags()
9450 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9452 data->window_flags = flags;
9456 \fn Qt::WindowType QWidget::windowType() const
9458 Returns the window type of this widget. This is identical to
9459 windowFlags() & Qt::WindowType_Mask.
9465 Sets the parent of the widget to \a parent, and resets the window
9466 flags. The widget is moved to position (0, 0) in its new parent.
9468 If the new parent widget is in a different window, the
9469 reparented widget and its children are appended to the end of the
9470 \l{setFocusPolicy()}{tab chain} of the new parent
9471 widget, in the same internal order as before. If one of the moved
9472 widgets had keyboard focus, setParent() calls clearFocus() for that
9475 If the new parent widget is in the same window as the
9476 old parent, setting the parent doesn't change the tab order or
9479 If the "new" parent widget is the old parent widget, this function
9482 \note The widget becomes invisible as part of changing its parent,
9483 even if it was previously visible. You must call show() to make the
9484 widget visible again.
9486 \warning It is very unlikely that you will ever need this
9487 function. If you have a widget that changes its content
9488 dynamically, it is far easier to use \l QStackedWidget.
9490 \sa setWindowFlags()
9492 void QWidget::setParent(QWidget *parent)
9494 if (parent == parentWidget())
9496 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9502 This function also takes widget flags, \a f as an argument.
9505 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9508 d->inSetParent = true;
9509 bool resized = testAttribute(Qt::WA_Resized);
9510 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9511 QWidget *oldtlw = window();
9513 QWidget *desktopWidget = 0;
9514 if (parent && parent->windowType() == Qt::Desktop)
9515 desktopWidget = parent;
9516 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9518 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC)
9519 if (newParent && parent && !desktopWidget) {
9520 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9522 // On Mac, toolbars inside the unified title bar will never overlap with
9523 // siblings in the content view. So we skip enforce native siblings in that case
9524 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9527 parent->d_func()->enforceNativeChildren();
9528 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9529 setAttribute(Qt::WA_NativeWindow);
9534 if (!testAttribute(Qt::WA_WState_Hidden)) {
9536 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9539 QEvent e(QEvent::ParentAboutToChange);
9540 QApplication::sendEvent(this, &e);
9543 if (newParent && isAncestorOf(focusWidget()))
9544 focusWidget()->clearFocus();
9546 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9547 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9549 d->setParent_sys(parent, f);
9551 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9552 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9553 if (oldBsTracker && oldBsTracker != bsTracker)
9554 oldBsTracker->unregisterWidgetSubtree(this);
9559 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9561 oldBs->removeDirtyWidget(this);
9562 // Move the widget and all its static children from
9563 // the old backing store to the new one.
9564 oldBs->moveStaticWidgets(this);
9567 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9570 d->reparentFocusWidgets(oldtlw);
9571 setAttribute(Qt::WA_Resized, resized);
9572 if (!testAttribute(Qt::WA_StyleSheet)
9573 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9575 d->resolvePalette();
9577 d->resolveLayoutDirection();
9580 // Note: GL widgets under WGL or EGL will always need a ParentChange
9581 // event to handle recreation/rebinding of the GL context, hence the
9582 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9585 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9586 || (f & Qt::MSWindowsOwnDC)
9589 // propagate enabled updates enabled state to non-windows
9591 if (!testAttribute(Qt::WA_ForceDisabled))
9592 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9593 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9594 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9598 // send and post remaining QObject events
9599 if (parent && d->sendChildEvents) {
9600 QChildEvent e(QEvent::ChildAdded, this);
9601 QApplication::sendEvent(parent, &e);
9604 //### already hidden above ---> must probably do something smart on the mac
9606 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9607 // if(!qt_mac_is_macdrawer(q)) //special case
9608 // q->setAttribute(Qt::WA_WState_Hidden);
9610 // q->setAttribute(Qt::WA_WState_Hidden);
9613 if (parent && d->sendChildEvents && d->polished) {
9614 QChildEvent e(QEvent::ChildPolished, this);
9615 QCoreApplication::sendEvent(parent, &e);
9618 QEvent e(QEvent::ParentChange);
9619 QApplication::sendEvent(this, &e);
9623 if (isWindow() || parentWidget()->isVisible())
9624 setAttribute(Qt::WA_WState_Hidden, true);
9625 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9626 setAttribute(Qt::WA_WState_Hidden, false);
9629 d->updateIsOpaque();
9631 #ifndef QT_NO_GRAPHICSVIEW
9632 // Embed the widget into a proxy if the parent is embedded.
9633 // ### Doesn't handle reparenting out of an embedded widget.
9634 if (oldtlw->graphicsProxyWidget()) {
9635 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9636 ancestorProxy->d_func()->unembedSubWindow(this);
9638 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9639 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9640 ancestorProxy->d_func()->embedSubWindow(this);
9644 d->inSetParent = false;
9648 Scrolls the widget including its children \a dx pixels to the
9649 right and \a dy downward. Both \a dx and \a dy may be negative.
9651 After scrolling, the widgets will receive paint events for
9652 the areas that need to be repainted. For widgets that Qt knows to
9653 be opaque, this is only the newly exposed parts.
9654 For example, if an opaque widget is scrolled 8 pixels to the left,
9655 only an 8-pixel wide stripe at the right edge needs updating.
9657 Since widgets propagate the contents of their parents by default,
9658 you need to set the \l autoFillBackground property, or use
9659 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9662 For widgets that use contents propagation, a scroll will cause an
9663 update of the entire scroll area.
9665 \sa {Transparency and Double Buffering}
9668 void QWidget::scroll(int dx, int dy)
9670 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9672 if (dx == 0 && dy == 0)
9675 #ifndef QT_NO_GRAPHICSVIEW
9676 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9677 // Graphics View maintains its own dirty region as a list of rects;
9678 // until we can connect item updates directly to the view, we must
9679 // separately add a translated dirty region.
9680 if (!d->dirty.isEmpty()) {
9681 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9682 proxy->update(rect);
9684 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9688 d->setDirtyOpaqueRegion();
9689 d->scroll_sys(dx, dy);
9695 This version only scrolls \a r and does not move the children of
9698 If \a r is empty or invalid, the result is undefined.
9702 void QWidget::scroll(int dx, int dy, const QRect &r)
9705 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9707 if (dx == 0 && dy == 0)
9710 #ifndef QT_NO_GRAPHICSVIEW
9711 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9712 // Graphics View maintains its own dirty region as a list of rects;
9713 // until we can connect item updates directly to the view, we must
9714 // separately add a translated dirty region.
9715 if (!d->dirty.isEmpty()) {
9716 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9717 proxy->update(rect);
9719 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9723 d->scroll_sys(dx, dy, r);
9727 Repaints the widget directly by calling paintEvent() immediately,
9728 unless updates are disabled or the widget is hidden.
9730 We suggest only using repaint() if you need an immediate repaint,
9731 for example during animation. In almost all circumstances update()
9732 is better, as it permits Qt to optimize for speed and minimize
9735 \warning If you call repaint() in a function which may itself be
9736 called from paintEvent(), you may get infinite recursion. The
9737 update() function never causes recursion.
9739 \sa update(), paintEvent(), setUpdatesEnabled()
9742 void QWidget::repaint()
9749 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9752 If \a w is negative, it is replaced with \c{width() - x}, and if
9753 \a h is negative, it is replaced width \c{height() - y}.
9755 void QWidget::repaint(int x, int y, int w, int h)
9757 if (x > data->crect.width() || y > data->crect.height())
9761 w = data->crect.width() - x;
9763 h = data->crect.height() - y;
9765 repaint(QRect(x, y, w, h));
9770 This version repaints a rectangle \a rect inside the widget.
9772 void QWidget::repaint(const QRect &rect)
9776 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9781 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9784 if (hasBackingStoreSupport()) {
9786 if (qt_widget_private(this)->isInUnifiedToolbar) {
9787 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9791 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9792 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9793 tlwExtra->inRepaint = true;
9794 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9795 tlwExtra->inRepaint = false;
9798 d->repaint_sys(rect);
9805 This version repaints a region \a rgn inside the widget.
9807 void QWidget::repaint(const QRegion &rgn)
9811 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9816 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9819 if (hasBackingStoreSupport()) {
9821 if (qt_widget_private(this)->isInUnifiedToolbar) {
9822 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9826 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9827 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9828 tlwExtra->inRepaint = true;
9829 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9830 tlwExtra->inRepaint = false;
9833 d->repaint_sys(rgn);
9838 Updates the widget unless updates are disabled or the widget is
9841 This function does not cause an immediate repaint; instead it
9842 schedules a paint event for processing when Qt returns to the main
9843 event loop. This permits Qt to optimize for more speed and less
9844 flicker than a call to repaint() does.
9846 Calling update() several times normally results in just one
9849 Qt normally erases the widget's area before the paintEvent() call.
9850 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9851 responsible for painting all its pixels with an opaque color.
9853 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9855 void QWidget::update()
9860 /*! \fn void QWidget::update(int x, int y, int w, int h)
9863 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9870 This version updates a rectangle \a rect inside the widget.
9872 void QWidget::update(const QRect &rect)
9874 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9877 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9878 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9882 if (hasBackingStoreSupport()) {
9884 if (qt_widget_private(this)->isInUnifiedToolbar) {
9885 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9889 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9890 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9891 tlwExtra->backingStoreTracker->markDirty(rect, this);
9893 d_func()->repaint_sys(rect);
9900 This version repaints a region \a rgn inside the widget.
9902 void QWidget::update(const QRegion &rgn)
9904 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9907 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9908 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9912 if (hasBackingStoreSupport()) {
9914 if (qt_widget_private(this)->isInUnifiedToolbar) {
9915 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9919 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9920 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9921 tlwExtra->backingStoreTracker->markDirty(rgn, this);
9923 d_func()->repaint_sys(rgn);
9931 This just sets the corresponding attribute bit to 1 or 0
9933 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9936 if (attribute < int(8*sizeof(uint))) {
9938 data->widget_attributes |= (1<<attribute);
9940 data->widget_attributes &= ~(1<<attribute);
9942 const int x = attribute - 8*sizeof(uint);
9943 const int int_off = x / (8*sizeof(uint));
9945 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9947 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9952 Sets the attribute \a attribute on this widget if \a on is true;
9953 otherwise clears the attribute.
9957 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9959 if (testAttribute(attribute) == on)
9963 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9964 "QWidget::setAttribute(WidgetAttribute, bool)",
9965 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9967 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
9968 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
9969 // see qwidget_win.cpp, ::paintEngine for details
9971 if (d->noPaintOnScreen)
9976 setAttribute_internal(attribute, on, data, d);
9978 switch (attribute) {
9980 #ifndef QT_NO_DRAGANDDROP
9981 case Qt::WA_AcceptDrops: {
9982 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9983 setAttribute(Qt::WA_DropSiteRegistered, true);
9984 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9985 setAttribute(Qt::WA_DropSiteRegistered, false);
9986 QEvent e(QEvent::AcceptDropsChange);
9987 QApplication::sendEvent(this, &e);
9990 case Qt::WA_DropSiteRegistered: {
9991 d->registerDropSite(on);
9992 for (int i = 0; i < d->children.size(); ++i) {
9993 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9994 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9995 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10001 case Qt::WA_NoChildEventsForParent:
10002 d->sendChildEvents = !on;
10004 case Qt::WA_NoChildEventsFromChildren:
10005 d->receiveChildEvents = !on;
10007 case Qt::WA_MacBrushedMetal:
10009 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10010 // fall through since changing the metal attribute affects the opaque size grip.
10011 case Qt::WA_MacOpaqueSizeGrip:
10012 d->macUpdateOpaqueSizeGrip();
10014 case Qt::WA_MacShowFocusRect:
10021 qt_mac_update_mouseTracking(this);
10024 case Qt::WA_MacAlwaysShowToolWindow:
10026 d->macUpdateHideOnSuspend();
10029 case Qt::WA_MacNormalSize:
10030 case Qt::WA_MacSmallSize:
10031 case Qt::WA_MacMiniSize:
10034 // We can only have one of these set at a time
10035 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10036 Qt::WA_MacMiniSize };
10037 for (int i = 0; i < 3; ++i) {
10038 if (MacSizes[i] != attribute)
10039 setAttribute_internal(MacSizes[i], false, data, d);
10041 d->macUpdateSizeAttribute();
10045 case Qt::WA_ShowModal:
10047 // reset modality type to NonModal when clearing WA_ShowModal
10048 data->window_modality = Qt::NonModal;
10049 } else if (data->window_modality == Qt::NonModal) {
10050 // determine the modality type if it hasn't been set prior
10051 // to setting WA_ShowModal. set the default to WindowModal
10052 // if we are the child of a group leader; otherwise use
10053 // ApplicationModal.
10054 QWidget *w = parentWidget();
10057 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10058 w = w->parentWidget();
10062 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10064 : Qt::ApplicationModal;
10065 // Some window managers do not allow us to enter modality after the
10066 // window is visible.The window must be hidden before changing the
10067 // windowModality property and then reshown.
10069 if (testAttribute(Qt::WA_WState_Created)) {
10070 // don't call setModal_sys() before create_sys()
10074 case Qt::WA_MouseTracking: {
10075 QEvent e(QEvent::MouseTrackingChange);
10076 QApplication::sendEvent(this, &e);
10078 case Qt::WA_NativeWindow: {
10079 d->createTLExtra();
10081 QWidget *focusWidget = d->effectiveFocusWidget();
10082 if (on && !internalWinId() && hasFocus()
10083 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10084 qApp->inputMethod()->commit();
10085 qApp->inputMethod()->update(Qt::ImEnabled);
10087 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10089 // On Mac, toolbars inside the unified title bar will never overlap with
10090 // siblings in the content view. So we skip enforce native siblings in that case
10091 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10094 parentWidget()->d_func()->enforceNativeChildren();
10095 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10097 if (isEnabled() && focusWidget->isEnabled()
10098 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10099 qApp->inputMethod()->update(Qt::ImEnabled);
10104 case Qt::WA_PaintOnScreen:
10105 d->updateIsOpaque();
10106 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10107 // Recreate the widget if it's already created as an alien widget and
10108 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10109 // So must their children.
10111 setAttribute(Qt::WA_NativeWindow);
10112 d->enforceNativeChildren();
10116 case Qt::WA_OpaquePaintEvent:
10117 d->updateIsOpaque();
10119 case Qt::WA_NoSystemBackground:
10120 d->updateIsOpaque();
10122 case Qt::WA_UpdatesDisabled:
10123 d->updateSystemBackground();
10125 case Qt::WA_TransparentForMouseEvents:
10127 d->macUpdateIgnoreMouseEvents();
10130 case Qt::WA_InputMethodEnabled: {
10132 if (qApp->focusObject() == this) {
10134 qApp->inputMethod()->commit();
10135 qApp->inputMethod()->update(Qt::ImEnabled);
10140 case Qt::WA_WindowPropagation:
10141 d->resolvePalette();
10143 d->resolveLocale();
10146 case Qt::WA_NoX11EventCompression:
10149 d->extra->compress_events = on;
10151 case Qt::WA_X11OpenGLOverlay:
10152 d->updateIsOpaque();
10154 case Qt::WA_X11DoNotAcceptFocus:
10155 if (testAttribute(Qt::WA_WState_Created))
10156 d->updateX11AcceptFocus();
10159 case Qt::WA_DontShowOnScreen: {
10160 if (on && isVisible()) {
10161 // Make sure we keep the current state and only hide the widget
10162 // from the desktop. show_sys will only update platform specific
10163 // attributes at this point.
10171 case Qt::WA_X11NetWmWindowTypeDesktop:
10172 case Qt::WA_X11NetWmWindowTypeDock:
10173 case Qt::WA_X11NetWmWindowTypeToolBar:
10174 case Qt::WA_X11NetWmWindowTypeMenu:
10175 case Qt::WA_X11NetWmWindowTypeUtility:
10176 case Qt::WA_X11NetWmWindowTypeSplash:
10177 case Qt::WA_X11NetWmWindowTypeDialog:
10178 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10179 case Qt::WA_X11NetWmWindowTypePopupMenu:
10180 case Qt::WA_X11NetWmWindowTypeToolTip:
10181 case Qt::WA_X11NetWmWindowTypeNotification:
10182 case Qt::WA_X11NetWmWindowTypeCombo:
10183 case Qt::WA_X11NetWmWindowTypeDND:
10184 if (testAttribute(Qt::WA_WState_Created))
10185 d->setNetWmWindowTypes();
10189 case Qt::WA_StaticContents:
10190 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10192 bs->addStaticWidget(this);
10194 bs->removeStaticWidget(this);
10197 case Qt::WA_TranslucentBackground:
10199 setAttribute(Qt::WA_NoSystemBackground);
10200 d->updateIsTranslucent();
10204 case Qt::WA_AcceptTouchEvents:
10205 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10207 d->registerTouchWindow();
10215 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10217 Returns true if attribute \a attribute is set on this widget;
10218 otherwise returns false.
10222 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10224 Q_D(const QWidget);
10225 const int x = attribute - 8*sizeof(uint);
10226 const int int_off = x / (8*sizeof(uint));
10227 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10231 \property QWidget::windowOpacity
10233 \brief The level of opacity for the window.
10235 The valid range of opacity is from 1.0 (completely opaque) to
10236 0.0 (completely transparent).
10238 By default the value of this property is 1.0.
10240 This feature is available on Embedded Linux, Mac OS X, Windows,
10241 and X11 platforms that support the Composite extension.
10243 This feature is not available on Windows CE.
10245 Note that under X11 you need to have a composite manager running,
10246 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10247 supported by the window manager you are using.
10249 \warning Changing this property from opaque to transparent might issue a
10250 paint event that needs to be processed before the window is displayed
10251 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10252 that semi-transparent windows update and resize significantly slower than
10257 qreal QWidget::windowOpacity() const
10259 Q_D(const QWidget);
10260 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10263 void QWidget::setWindowOpacity(qreal opacity)
10269 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10270 QTLWExtra *extra = d->topData();
10271 extra->opacity = uint(opacity * 255);
10272 setAttribute(Qt::WA_WState_WindowOpacitySet);
10274 if (!testAttribute(Qt::WA_WState_Created))
10277 #ifndef QT_NO_GRAPHICSVIEW
10278 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10279 // Avoid invalidating the cache if set.
10280 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10282 else if (QGraphicsScene *scene = proxy->scene())
10283 scene->update(proxy->sceneBoundingRect());
10288 d->setWindowOpacity_sys(opacity);
10292 \property QWidget::windowModified
10293 \brief whether the document shown in the window has unsaved changes
10295 A modified window is a window whose content has changed but has
10296 not been saved to disk. This flag will have different effects
10297 varied by the platform. On Mac OS X the close button will have a
10298 modified look; on other platforms, the window title will have an
10301 The window title must contain a "[*]" placeholder, which
10302 indicates where the '*' should appear. Normally, it should appear
10303 right after the file name (e.g., "document1.txt[*] - Text
10304 Editor"). If the window isn't modified, the placeholder is simply
10307 Note that if a widget is set as modified, all its ancestors will
10308 also be set as modified. However, if you call \c
10309 {setWindowModified(false)} on a widget, this will not propagate to
10310 its parent because other children of the parent might have been
10313 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10315 bool QWidget::isWindowModified() const
10317 return testAttribute(Qt::WA_WindowModified);
10320 void QWidget::setWindowModified(bool mod)
10323 setAttribute(Qt::WA_WindowModified, mod);
10326 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10327 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10329 d->setWindowTitle_helper(windowTitle());
10330 d->setWindowIconText_helper(windowIconText());
10332 d->setWindowModified_sys(mod);
10335 QEvent e(QEvent::ModifiedChange);
10336 QApplication::sendEvent(this, &e);
10339 #ifndef QT_NO_TOOLTIP
10341 \property QWidget::toolTip
10343 \brief the widget's tooltip
10345 Note that by default tooltips are only shown for widgets that are
10346 children of the active window. You can change this behavior by
10347 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10348 not on the widget with the tooltip.
10350 If you want to control a tooltip's behavior, you can intercept the
10351 event() function and catch the QEvent::ToolTip event (e.g., if you
10352 want to customize the area for which the tooltip should be shown).
10354 By default, this property contains an empty string.
10356 \sa QToolTip statusTip whatsThis
10358 void QWidget::setToolTip(const QString &s)
10363 QEvent event(QEvent::ToolTipChange);
10364 QApplication::sendEvent(this, &event);
10367 QString QWidget::toolTip() const
10369 Q_D(const QWidget);
10372 #endif // QT_NO_TOOLTIP
10375 #ifndef QT_NO_STATUSTIP
10377 \property QWidget::statusTip
10378 \brief the widget's status tip
10380 By default, this property contains an empty string.
10382 \sa toolTip whatsThis
10384 void QWidget::setStatusTip(const QString &s)
10390 QString QWidget::statusTip() const
10392 Q_D(const QWidget);
10393 return d->statusTip;
10395 #endif // QT_NO_STATUSTIP
10397 #ifndef QT_NO_WHATSTHIS
10399 \property QWidget::whatsThis
10401 \brief the widget's What's This help text.
10403 By default, this property contains an empty string.
10405 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10407 void QWidget::setWhatsThis(const QString &s)
10413 QString QWidget::whatsThis() const
10415 Q_D(const QWidget);
10416 return d->whatsThis;
10418 #endif // QT_NO_WHATSTHIS
10420 #ifndef QT_NO_ACCESSIBILITY
10422 \property QWidget::accessibleName
10424 \brief the widget's name as seen by assistive technologies
10426 This property is used by accessible clients to identify, find, or announce
10427 the widget for accessible clients.
10429 By default, this property contains an empty string.
10431 \sa QAccessibleInterface::text()
10433 void QWidget::setAccessibleName(const QString &name)
10436 d->accessibleName = name;
10437 QAccessibleEvent event(this, QAccessible::NameChanged);
10438 QAccessible::updateAccessibility(&event);
10441 QString QWidget::accessibleName() const
10443 Q_D(const QWidget);
10444 return d->accessibleName;
10448 \property QWidget::accessibleDescription
10450 \brief the widget's description as seen by assistive technologies
10452 By default, this property contains an empty string.
10454 \sa QAccessibleInterface::text()
10456 void QWidget::setAccessibleDescription(const QString &description)
10459 d->accessibleDescription = description;
10460 QAccessibleEvent event(this, QAccessible::DescriptionChanged);
10461 QAccessible::updateAccessibility(&event);
10464 QString QWidget::accessibleDescription() const
10466 Q_D(const QWidget);
10467 return d->accessibleDescription;
10469 #endif // QT_NO_ACCESSIBILITY
10471 #ifndef QT_NO_SHORTCUT
10473 Adds a shortcut to Qt's shortcut system that watches for the given
10474 \a key sequence in the given \a context. If the \a context is
10475 Qt::ApplicationShortcut, the shortcut applies to the application as a
10476 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10477 or to the window itself, Qt::WindowShortcut.
10479 If the same \a key sequence has been grabbed by several widgets,
10480 when the \a key sequence occurs a QEvent::Shortcut event is sent
10481 to all the widgets to which it applies in a non-deterministic
10482 order, but with the ``ambiguous'' flag set to true.
10484 \warning You should not normally need to use this function;
10485 instead create \l{QAction}s with the shortcut key sequences you
10486 require (if you also want equivalent menu options and toolbar
10487 buttons), or create \l{QShortcut}s if you just need key sequences.
10488 Both QAction and QShortcut handle all the event filtering for you,
10489 and provide signals which are triggered when the user triggers the
10490 key sequence, so are much easier to use than this low-level
10493 \sa releaseShortcut() setShortcutEnabled()
10495 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10500 setAttribute(Qt::WA_GrabbedShortcut);
10501 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10505 Removes the shortcut with the given \a id from Qt's shortcut
10506 system. The widget will no longer receive QEvent::Shortcut events
10507 for the shortcut's key sequence (unless it has other shortcuts
10508 with the same key sequence).
10510 \warning You should not normally need to use this function since
10511 Qt's shortcut system removes shortcuts automatically when their
10512 parent widget is destroyed. It is best to use QAction or
10513 QShortcut to handle shortcuts, since they are easier to use than
10514 this low-level function. Note also that this is an expensive
10517 \sa grabShortcut() setShortcutEnabled()
10519 void QWidget::releaseShortcut(int id)
10523 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10527 If \a enable is true, the shortcut with the given \a id is
10528 enabled; otherwise the shortcut is disabled.
10530 \warning You should not normally need to use this function since
10531 Qt's shortcut system enables/disables shortcuts automatically as
10532 widgets become hidden/visible and gain or lose focus. It is best
10533 to use QAction or QShortcut to handle shortcuts, since they are
10534 easier to use than this low-level function.
10536 \sa grabShortcut() releaseShortcut()
10538 void QWidget::setShortcutEnabled(int id, bool enable)
10542 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10548 If \a enable is true, auto repeat of the shortcut with the
10549 given \a id is enabled; otherwise it is disabled.
10551 \sa grabShortcut() releaseShortcut()
10553 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10557 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10559 #endif // QT_NO_SHORTCUT
10562 Updates the widget's micro focus.
10564 void QWidget::updateMicroFocus()
10566 // updating everything since this is currently called for any kind of state change
10567 qApp->inputMethod()->update(Qt::ImQueryAll);
10571 Raises this widget to the top of the parent widget's stack.
10573 After this call the widget will be visually in front of any
10574 overlapping sibling widgets.
10576 \note When using activateWindow(), you can call this function to
10577 ensure that the window is stacked on top.
10579 \sa lower(), stackUnder()
10582 void QWidget::raise()
10586 QWidget *p = parentWidget();
10587 const int parentChildCount = p->d_func()->children.size();
10588 if (parentChildCount < 2)
10590 const int from = p->d_func()->children.indexOf(this);
10591 Q_ASSERT(from >= 0);
10592 // Do nothing if the widget is already in correct stacking order _and_ created.
10593 if (from != parentChildCount -1)
10594 p->d_func()->children.move(from, parentChildCount - 1);
10595 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10597 else if (from == parentChildCount - 1)
10600 QRegion region(rect());
10601 d->subtractOpaqueSiblings(region);
10602 d->invalidateBuffer(region);
10604 if (testAttribute(Qt::WA_WState_Created))
10607 QEvent e(QEvent::ZOrderChange);
10608 QApplication::sendEvent(this, &e);
10612 Lowers the widget to the bottom of the parent widget's stack.
10614 After this call the widget will be visually behind (and therefore
10615 obscured by) any overlapping sibling widgets.
10617 \sa raise(), stackUnder()
10620 void QWidget::lower()
10624 QWidget *p = parentWidget();
10625 const int parentChildCount = p->d_func()->children.size();
10626 if (parentChildCount < 2)
10628 const int from = p->d_func()->children.indexOf(this);
10629 Q_ASSERT(from >= 0);
10630 // Do nothing if the widget is already in correct stacking order _and_ created.
10632 p->d_func()->children.move(from, 0);
10633 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10635 else if (from == 0)
10638 if (testAttribute(Qt::WA_WState_Created))
10641 QEvent e(QEvent::ZOrderChange);
10642 QApplication::sendEvent(this, &e);
10647 Places the widget under \a w in the parent widget's stack.
10649 To make this work, the widget itself and \a w must be siblings.
10651 \sa raise(), lower()
10653 void QWidget::stackUnder(QWidget* w)
10656 QWidget *p = parentWidget();
10657 if (!w || isWindow() || p != w->parentWidget() || this == w)
10660 int from = p->d_func()->children.indexOf(this);
10661 int to = p->d_func()->children.indexOf(w);
10662 Q_ASSERT(from >= 0);
10666 // Do nothing if the widget is already in correct stacking order _and_ created.
10668 p->d_func()->children.move(from, to);
10669 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10671 else if (from == to)
10674 if (testAttribute(Qt::WA_WState_Created))
10675 d->stackUnder_sys(w);
10677 QEvent e(QEvent::ZOrderChange);
10678 QApplication::sendEvent(this, &e);
10683 \fn bool QWidget::isTopLevel() const
10686 Use isWindow() instead.
10690 \fn bool QWidget::isRightToLeft() const
10695 \fn bool QWidget::isLeftToRight() const
10700 \macro QWIDGETSIZE_MAX
10703 Defines the maximum size for a QWidget object.
10705 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10706 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10708 \sa QWidget::setMaximumSize()
10712 \fn QWidget::setupUi(QWidget *widget)
10714 Sets up the user interface for the specified \a widget.
10716 \note This function is available with widgets that derive from user
10717 interface descriptions created using \l{uic}.
10719 \sa {Using a Designer UI File in Your Application}
10722 QRect QWidgetPrivate::frameStrut() const
10724 Q_Q(const QWidget);
10725 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10726 // x2 = x1 + w - 1, so w/h = 1
10727 return QRect(0, 0, 1, 1);
10730 if (data.fstrut_dirty
10732 // ### Fix properly for 4.3
10735 && q->testAttribute(Qt::WA_WState_Created))
10736 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10738 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10741 #ifdef QT_KEYPAD_NAVIGATION
10745 Changes the focus from the current focusWidget to a widget in
10748 Returns true, if there was a widget in that direction
10750 bool QWidgetPrivate::navigateToDirection(Direction direction)
10752 QWidget *targetWidget = widgetInNavigationDirection(direction);
10754 targetWidget->setFocus();
10755 return (targetWidget != 0);
10761 Searches for a widget that is positioned in the \a direction, starting
10762 from the current focusWidget.
10764 Returns the pointer to a found widget or 0, if there was no widget in
10767 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10769 const QWidget *sourceWidget = QApplication::focusWidget();
10772 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10773 const int sourceX =
10774 (direction == DirectionNorth || direction == DirectionSouth) ?
10775 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10776 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10777 const int sourceY =
10778 (direction == DirectionEast || direction == DirectionWest) ?
10779 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10780 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10781 const QPoint sourcePoint(sourceX, sourceY);
10782 const QPoint sourceCenter = sourceRect.center();
10783 const QWidget *sourceWindow = sourceWidget->window();
10785 QWidget *targetWidget = 0;
10786 int shortestDistance = INT_MAX;
10787 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10789 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10791 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10792 // but the owner of the proxy cannot.
10793 // Additionally, empty widgets should be ignored.
10794 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10797 // Only navigate to a target widget that...
10798 if ( targetCandidate != sourceWidget
10799 // ...takes the focus,
10800 && targetCandidate->focusPolicy() & Qt::TabFocus
10801 // ...is above if DirectionNorth,
10802 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10803 // ...is on the right if DirectionEast,
10804 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
10805 // ...is below if DirectionSouth,
10806 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
10807 // ...is on the left if DirectionWest,
10808 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
10810 && targetCandidate->isEnabled()
10812 && targetCandidate->isVisible()
10813 // ...is in the same window,
10814 && targetCandidate->window() == sourceWindow) {
10815 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10816 if (targetCandidateDistance < shortestDistance) {
10817 shortestDistance = targetCandidateDistance;
10818 targetWidget = targetCandidate;
10822 return targetWidget;
10828 Tells us if it there is currently a reachable widget by keypad navigation in
10829 a certain \a orientation.
10830 If no navigation is possible, occurring key events in that \a orientation may
10831 be used to interact with the value in the focused widget, even though it
10832 currently has not the editFocus.
10834 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10836 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10838 return orientation == Qt::Horizontal?
10839 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10840 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10841 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10842 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10847 Checks, if the \a widget is inside a QTabWidget. If is is inside
10848 one, left/right key events will be used to switch between tabs in keypad
10849 navigation. If there is no QTabWidget, the horizontal key events can be used
10851 interact with the value in the focused widget, even though it currently has
10854 \sa QWidget::hasEditFocus()
10856 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10858 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10859 if (qobject_cast<const QTabWidget*>(tabWidget))
10869 Sets the backing store to be the \a store specified.
10870 The QWidget will take ownership of the \a store.
10872 void QWidget::setBackingStore(QBackingStore *store)
10874 // ### createWinId() ??
10881 QTLWExtra *topData = d->topData();
10882 if (topData->backingStore == store)
10885 QBackingStore *oldStore = topData->backingStore;
10886 delete topData->backingStore;
10887 topData->backingStore = store;
10889 QWidgetBackingStore *bs = d->maybeBackingStore();
10893 if (isTopLevel()) {
10894 if (bs->store != oldStore && bs->store != store)
10903 Returns the QBackingStore this widget will be drawn into.
10905 QBackingStore *QWidget::backingStore() const
10907 Q_D(const QWidget);
10908 QTLWExtra *extra = d->maybeTopData();
10909 if (extra && extra->backingStore)
10910 return extra->backingStore;
10912 QWidgetBackingStore *bs = d->maybeBackingStore();
10914 return bs ? bs->store : 0;
10917 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10920 *left = (int)leftLayoutItemMargin;
10922 *top = (int)topLayoutItemMargin;
10924 *right = (int)rightLayoutItemMargin;
10926 *bottom = (int)bottomLayoutItemMargin;
10929 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10931 if (leftLayoutItemMargin == left
10932 && topLayoutItemMargin == top
10933 && rightLayoutItemMargin == right
10934 && bottomLayoutItemMargin == bottom)
10938 leftLayoutItemMargin = (signed char)left;
10939 topLayoutItemMargin = (signed char)top;
10940 rightLayoutItemMargin = (signed char)right;
10941 bottomLayoutItemMargin = (signed char)bottom;
10942 q->updateGeometry();
10945 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10948 QStyleOption myOpt;
10951 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
10955 QRect liRect = q->style()->subElementRect(element, opt, q);
10956 if (liRect.isValid()) {
10957 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10958 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10959 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10960 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10962 leftLayoutItemMargin = 0;
10963 topLayoutItemMargin = 0;
10964 rightLayoutItemMargin = 0;
10965 bottomLayoutItemMargin = 0;
10968 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10969 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10973 if (!q->parentWidget()) {
10974 Qt::WindowType type = q->windowType();
10975 if (type == Qt::Widget || type == Qt::SubWindow)
10977 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10978 q->setAttribute(Qt::WA_QuitOnClose, false);
10984 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10986 return widget->data;
10989 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10991 return widget->d_func();
10995 #ifndef QT_NO_GRAPHICSVIEW
10999 Returns the proxy widget for the corresponding embedded widget in a graphics
11000 view; otherwise returns 0.
11002 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11003 QGraphicsScene::addWidget()
11005 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11007 Q_D(const QWidget);
11009 return d->extra->proxyWidget;
11017 \typedef QWidgetList
11020 Synonym for QList<QWidget *>.
11023 #ifndef QT_NO_GESTURES
11025 Subscribes the widget to a given \a gesture with specific \a flags.
11027 \sa ungrabGesture(), QGestureEvent
11030 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11033 d->gestureContext.insert(gesture, flags);
11034 (void)QGestureManager::instance(); // create a gesture manager
11038 Unsubscribes the widget from a given \a gesture type
11040 \sa grabGesture(), QGestureEvent
11043 void QWidget::ungrabGesture(Qt::GestureType gesture)
11046 if (d->gestureContext.remove(gesture)) {
11047 if (QGestureManager *manager = QGestureManager::instance())
11048 manager->cleanupCachedGestures(this, gesture);
11051 #endif // QT_NO_GESTURES
11057 Platform dependent window identifier.
11061 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11063 Frees up window system resources. Destroys the widget window if \a
11064 destroyWindow is true.
11066 destroy() calls itself recursively for all the child widgets,
11067 passing \a destroySubWindows for the \a destroyWindow parameter.
11068 To have more control over destruction of subwidgets, destroy
11069 subwidgets selectively first.
11071 This function is usually called from the QWidget destructor.
11075 \fn QPaintEngine *QWidget::paintEngine() const
11077 Returns the widget's paint engine.
11079 Note that this function should not be called explicitly by the
11080 user, since it's meant for reimplementation purposes only. The
11081 function is called by Qt internally, and the default
11082 implementation may not always return a valid pointer.
11086 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11088 Translates the widget coordinate \a pos to global screen
11089 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11090 the global coordinates of the top-left pixel of the widget.
11092 \sa mapFromGlobal() mapTo() mapToParent()
11096 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11098 Translates the global screen coordinate \a pos to widget
11101 \sa mapToGlobal() mapFrom() mapFromParent()
11105 \fn void QWidget::grabMouse()
11107 Grabs the mouse input.
11109 This widget receives all mouse events until releaseMouse() is
11110 called; other widgets get no mouse events at all. Keyboard
11111 events are not affected. Use grabKeyboard() if you want to grab
11114 \warning Bugs in mouse-grabbing applications very often lock the
11115 terminal. Use this function with extreme caution, and consider
11116 using the \c -nograb command line option while debugging.
11118 It is almost never necessary to grab the mouse when using Qt, as
11119 Qt grabs and releases it sensibly. In particular, Qt grabs the
11120 mouse when a mouse button is pressed and keeps it until the last
11121 button is released.
11123 \note Only visible widgets can grab mouse input. If isVisible()
11124 returns false for a widget, that widget cannot call grabMouse().
11126 \note \b{(Mac OS X developers)} For \e Cocoa, calling
11127 grabMouse() on a widget only works when the mouse is inside the
11128 frame of that widget. For \e Carbon, it works outside the widget's
11129 frame as well, like for Windows and X11.
11131 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11135 \fn void QWidget::grabMouse(const QCursor &cursor)
11136 \overload grabMouse()
11138 Grabs the mouse input and changes the cursor shape.
11140 The cursor will assume shape \a cursor (for as long as the mouse
11141 focus is grabbed) and this widget will be the only one to receive
11142 mouse events until releaseMouse() is called().
11144 \warning Grabbing the mouse might lock the terminal.
11146 \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11148 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11152 \fn void QWidget::releaseMouse()
11154 Releases the mouse grab.
11156 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11160 \fn void QWidget::grabKeyboard()
11162 Grabs the keyboard input.
11164 This widget receives all keyboard events until releaseKeyboard()
11165 is called; other widgets get no keyboard events at all. Mouse
11166 events are not affected. Use grabMouse() if you want to grab that.
11168 The focus widget is not affected, except that it doesn't receive
11169 any keyboard events. setFocus() moves the focus as usual, but the
11170 new focus widget receives keyboard events only after
11171 releaseKeyboard() is called.
11173 If a different widget is currently grabbing keyboard input, that
11174 widget's grab is released first.
11176 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11180 \fn void QWidget::releaseKeyboard()
11182 Releases the keyboard grab.
11184 \sa grabKeyboard(), grabMouse(), releaseMouse()
11188 \fn QWidget *QWidget::mouseGrabber()
11190 Returns the widget that is currently grabbing the mouse input.
11192 If no widget in this application is currently grabbing the mouse,
11195 \sa grabMouse(), keyboardGrabber()
11199 \fn QWidget *QWidget::keyboardGrabber()
11201 Returns the widget that is currently grabbing the keyboard input.
11203 If no widget in this application is currently grabbing the
11204 keyboard, 0 is returned.
11206 \sa grabMouse(), mouseGrabber()
11210 \fn void QWidget::activateWindow()
11212 Sets the top-level widget containing this widget to be the active
11215 An active window is a visible top-level window that has the
11216 keyboard input focus.
11218 This function performs the same operation as clicking the mouse on
11219 the title bar of a top-level window. On X11, the result depends on
11220 the Window Manager. If you want to ensure that the window is
11221 stacked on top as well you should also call raise(). Note that the
11222 window must be visible, otherwise activateWindow() has no effect.
11224 On Windows, if you are calling this when the application is not
11225 currently the active one then it will not make it the active
11226 window. It will change the color of the taskbar entry to indicate
11227 that the window has changed in some way. This is because Microsoft
11228 does not allow an application to interrupt what the user is currently
11229 doing in another application.
11231 \sa isActiveWindow(), window(), show()
11235 \fn int QWidget::metric(PaintDeviceMetric m) const
11237 Internal implementation of the virtual QPaintDevice::metric()
11240 \a m is the metric to get.
11243 void QWidget::init(QPainter *painter) const
11245 const QPalette &pal = palette();
11246 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11247 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11248 QFont f(font(), const_cast<QWidget *>(this));
11249 painter->d_func()->state->deviceFont = f;
11250 painter->d_func()->state->font = f;
11253 QPaintDevice *QWidget::redirected(QPoint *offset) const
11255 return d_func()->redirected(offset);
11258 QPainter *QWidget::sharedPainter() const
11260 // Someone sent a paint event directly to the widget
11261 if (!d_func()->redirectDev)
11264 QPainter *sp = d_func()->sharedPainter();
11265 if (!sp || !sp->isActive())
11268 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11275 \fn void QWidget::setMask(const QRegion ®ion)
11278 Causes only the parts of the widget which overlap \a region to be
11279 visible. If the region includes pixels outside the rect() of the
11280 widget, window system controls in that area may or may not be
11281 visible, depending on the platform.
11283 Note that this effect can be slow if the region is particularly
11288 void QWidget::setMask(const QRegion &newMask)
11293 if (newMask == d->extra->mask)
11296 #ifndef QT_NO_BACKINGSTORE
11297 const QRegion oldMask(d->extra->mask);
11300 d->extra->mask = newMask;
11301 d->extra->hasMask = !newMask.isEmpty();
11304 if (!testAttribute(Qt::WA_WState_Created))
11308 d->setMask_sys(newMask);
11310 #ifndef QT_NO_BACKINGSTORE
11314 if (!d->extra->hasMask) {
11315 // Mask was cleared; update newly exposed area.
11316 QRegion expose(rect());
11318 if (!expose.isEmpty()) {
11319 d->setDirtyOpaqueRegion();
11326 // Update newly exposed area on the parent widget.
11327 QRegion parentExpose(rect());
11328 parentExpose -= newMask;
11329 if (!parentExpose.isEmpty()) {
11330 d->setDirtyOpaqueRegion();
11331 parentExpose.translate(data->crect.topLeft());
11332 parentWidget()->update(parentExpose);
11335 // Update newly exposed area on this widget
11336 if (!oldMask.isEmpty())
11337 update(newMask - oldMask);
11343 \fn void QWidget::setMask(const QBitmap &bitmap)
11345 Causes only the pixels of the widget for which \a bitmap has a
11346 corresponding 1 bit to be visible. If the region includes pixels
11347 outside the rect() of the widget, window system controls in that
11348 area may or may not be visible, depending on the platform.
11350 Note that this effect can be slow if the region is particularly
11353 The following code shows how an image with an alpha channel can be
11354 used to generate a mask for a widget:
11356 \snippet doc/src/snippets/widget-mask/main.cpp 0
11358 The label shown by this code is masked using the image it contains,
11359 giving the appearance that an irregularly-shaped image is being drawn
11360 directly onto the screen.
11362 Masked widgets receive mouse events only on their visible
11365 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11367 void QWidget::setMask(const QBitmap &bitmap)
11369 setMask(QRegion(bitmap));
11373 \fn void QWidget::clearMask()
11375 Removes any mask set by setMask().
11379 void QWidget::clearMask()
11381 setMask(QRegion());
11384 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11385 Returns the X11 Picture handle of the widget for XRender
11386 support. Use of this function is not portable. This function will
11387 return 0 if XRender support is not compiled into Qt, if the
11388 XRender extension is not supported on the X11 display, or if the
11389 handle could not be created.
11393 void QWidgetPrivate::syncUnifiedMode() {
11394 // The whole purpose of this method is to keep the unifiedToolbar in sync.
11395 // That means making sure we either exchange the drawing methods or we let
11396 // the toolbar know that it does not require to draw the baseline.
11398 // This function makes sense only if this is a top level
11401 OSWindowRef window = qt_mac_window_for(q);
11402 if(changeMethods) {
11403 // Ok, we are in documentMode.
11404 if(originalDrawMethod)
11405 qt_mac_replaceDrawRect(window, this);
11407 if(!originalDrawMethod)
11408 qt_mac_replaceDrawRectOriginal(window, this);
11416 #include "moc_qwidget.cpp"