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 fillRegion(painter, rgn, bg);
2143 if (q->autoFillBackground())
2144 fillRegion(painter, rgn, autoFillBrush);
2146 if (q->testAttribute(Qt::WA_StyledBackground)) {
2147 painter->setClipRegion(rgn);
2150 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2153 #ifndef QT_NO_SCROLLAREA
2154 if (resetBrushOrigin)
2155 painter->setBrushOrigin(oldBrushOrigin);
2156 #endif // QT_NO_SCROLLAREA
2161 This function is called when a widget is hidden or destroyed.
2162 It resets some application global pointers that should only refer active,
2167 extern QPointer<QWidget> qt_button_down;
2169 extern QWidget *qt_button_down;
2172 void QWidgetPrivate::deactivateWidgetCleanup()
2175 // If this was the active application window, reset it
2176 if (QApplication::activeWindow() == q)
2177 QApplication::setActiveWindow(0);
2178 // If the is the active mouse press widget, reset it
2179 if (q == qt_button_down)
2185 Returns a pointer to the widget with window identifer/handle \a
2188 The window identifier type depends on the underlying window
2189 system, see \c qwindowdefs.h for the actual definition. If there
2190 is no widget with this identifier, 0 is returned.
2193 QWidget *QWidget::find(WId id)
2195 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2201 \fn WId QWidget::internalWinId() const
2203 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2208 \fn WId QWidget::winId() const
2210 Returns the window system identifier of the widget.
2212 Portable in principle, but if you use it you are probably about to
2213 do something non-portable. Be careful.
2215 If a widget is non-native (alien) and winId() is invoked on it, that widget
2216 will be provided a native handle.
2218 On Mac OS X, the type returned depends on which framework Qt was linked
2219 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2220 is using Cocoa, {WId} is a pointer to an NSView.
2222 This value may change at run-time. An event with type QEvent::WinIdChange
2223 will be sent to the widget following a change in window system identifier.
2227 WId QWidget::winId() const
2229 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2231 qDebug() << "QWidget::winId: creating native window for" << this;
2233 QWidget *that = const_cast<QWidget*>(this);
2234 that->setAttribute(Qt::WA_NativeWindow);
2235 that->d_func()->createWinId();
2236 return that->data->winid;
2242 void QWidgetPrivate::createWinId(WId winid)
2247 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2249 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2250 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2251 if (!q->isWindow()) {
2252 QWidget *parent = q->parentWidget();
2253 QWidgetPrivate *pd = parent->d_func();
2254 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2255 parent->setAttribute(Qt::WA_NativeWindow);
2256 if (!parent->internalWinId()) {
2260 for (int i = 0; i < pd->children.size(); ++i) {
2261 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2262 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2263 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2268 // if the window has already been created, we
2269 // need to raise it to its proper stacking position
2284 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2288 void QWidget::createWinId()
2292 qDebug() << "QWidget::createWinId" << this;
2294 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2301 Returns the effective window system identifier of the widget, i.e. the
2302 native parent's window system identifier.
2304 If the widget is native, this function returns the native widget ID.
2305 Otherwise, the window ID of the first native parent widget, i.e., the
2306 top-level widget that contains this widget, is returned.
2308 \note We recommend that you do not store this value as it is likely to
2311 \sa nativeParentWidget()
2313 WId QWidget::effectiveWinId() const
2315 WId id = internalWinId();
2316 if (id || !testAttribute(Qt::WA_WState_Created))
2318 QWidget *realParent = nativeParentWidget();
2319 if (!realParent && d_func()->inSetParent) {
2320 // In transitional state. This is really just a workaround. The real problem
2321 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2322 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2323 // attribute to false. The correct way is to do it the other way around, and
2324 // in that case the Qt::WA_WState_Created logic above will kick in and
2325 // return 0 whenever the widget is in a transitional state. However, changing
2326 // the original logic for all platforms is far more intrusive and might
2327 // break existing applications.
2328 // Note: The widget can only be in a transitional state when changing its
2329 // parent -- everything else is an internal error -- hence explicitly checking
2330 // against 'inSetParent' rather than doing an unconditional return whenever
2331 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2334 // This widget *must* have a native parent widget.
2335 Q_ASSERT(realParent);
2336 Q_ASSERT(realParent->internalWinId());
2337 return realParent->internalWinId();
2340 #ifndef QT_NO_STYLE_STYLESHEET
2343 \property QWidget::styleSheet
2344 \brief the widget's style sheet
2347 The style sheet contains a textual description of customizations to the
2348 widget's style, as described in the \l{Qt Style Sheets} document.
2350 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2352 \warning Qt style sheets are currently not supported for custom QStyle
2353 subclasses. We plan to address this in some future release.
2355 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2357 QString QWidget::styleSheet() const
2362 return d->extra->styleSheet;
2365 void QWidget::setStyleSheet(const QString& styleSheet)
2370 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2371 d->extra->styleSheet = styleSheet;
2372 if (styleSheet.isEmpty()) { // stylesheet removed
2380 if (proxy) { // style sheet update
2381 proxy->repolish(this);
2385 if (testAttribute(Qt::WA_SetStyle)) {
2386 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2388 d->setStyle_helper(new QStyleSheetStyle(0), true);
2392 #endif // QT_NO_STYLE_STYLESHEET
2395 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2398 QStyle *QWidget::style() const
2402 if (d->extra && d->extra->style)
2403 return d->extra->style;
2404 return QApplication::style();
2408 Sets the widget's GUI style to \a style. The ownership of the style
2409 object is not transferred.
2411 If no style is set, the widget uses the application's style,
2412 QApplication::style() instead.
2414 Setting a widget's style has no effect on existing or future child
2417 \warning This function is particularly useful for demonstration
2418 purposes, where you want to show Qt's styling capabilities. Real
2419 applications should avoid it and use one consistent GUI style
2422 \warning Qt style sheets are currently not supported for custom QStyle
2423 subclasses. We plan to address this in some future release.
2425 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2428 void QWidget::setStyle(QStyle *style)
2431 setAttribute(Qt::WA_SetStyle, style != 0);
2433 #ifndef QT_NO_STYLE_STYLESHEET
2434 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2435 //if for some reason someone try to set a QStyleSheetStyle, ref it
2436 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2438 d->setStyle_helper(style, false);
2439 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2440 // if we have an application stylesheet or have a proxy already, propagate
2441 d->setStyle_helper(new QStyleSheetStyle(style), true);
2444 d->setStyle_helper(style, false);
2447 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2454 QStyle *oldStyle = q->style();
2455 #ifndef QT_NO_STYLE_STYLESHEET
2456 QWeakPointer<QStyle> origStyle;
2460 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2461 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2462 // set when changing that attribute and passes the widget's CURRENT style.
2463 // therefore no need to do a reassignment.
2469 #ifndef QT_NO_STYLE_STYLESHEET
2470 origStyle = extra->style.data();
2472 extra->style = newStyle;
2476 if (q->windowType() != Qt::Desktop) {
2478 oldStyle->unpolish(q);
2481 macUpdateMetalAttribute();
2483 q->style()->polish(q);
2485 } else if (metalHack) {
2486 macUpdateMetalAttribute();
2492 for (int i = 0; i < children.size(); ++i) {
2493 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2495 c->d_func()->inheritStyle();
2499 #ifndef QT_NO_STYLE_STYLESHEET
2500 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2501 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2502 cssStyle->clearWidgetFont(q);
2507 QEvent e(QEvent::StyleChange);
2508 QApplication::sendEvent(q, &e);
2510 #ifndef QT_NO_STYLE_STYLESHEET
2511 // dereference the old stylesheet style
2512 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2517 // Inherits style from the current parent and propagates it as necessary
2518 void QWidgetPrivate::inheritStyle()
2520 #ifndef QT_NO_STYLE_STYLESHEET
2523 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2525 if (!q->styleSheet().isEmpty()) {
2531 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2532 QWidget *parent = q->parentWidget();
2533 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2534 // If we have stylesheet on app or parent has stylesheet style, we need
2535 // to be running a proxy
2536 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2537 QStyle *newStyle = parentStyle;
2538 if (q->testAttribute(Qt::WA_SetStyle))
2539 newStyle = new QStyleSheetStyle(origStyle);
2540 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2543 setStyle_helper(newStyle, true);
2547 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2548 // we just need our original style back
2549 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2552 // We could have inherited the proxy from our parent (which has a custom style)
2553 // In such a case we need to start following the application style (i.e revert
2554 // the propagation behavior of QStyleSheetStyle)
2555 if (!q->testAttribute(Qt::WA_SetStyle))
2558 setStyle_helper(origStyle, true);
2559 #endif // QT_NO_STYLE_STYLESHEET
2564 \fn bool QWidget::isWindow() const
2566 Returns true if the widget is an independent window, otherwise
2569 A window is a widget that isn't visually the child of any other
2570 widget and that usually has a frame and a
2571 \l{QWidget::setWindowTitle()}{window title}.
2573 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2574 It will then be grouped with its parent and deleted when the
2575 parent is deleted, minimized when the parent is minimized etc. If
2576 supported by the window manager, it will also have a common
2577 taskbar entry with its parent.
2579 QDialog and QMainWindow widgets are by default windows, even if a
2580 parent widget is specified in the constructor. This behavior is
2581 specified by the Qt::Window flag.
2583 \sa window(), isModal(), parentWidget()
2587 \property QWidget::modal
2588 \brief whether the widget is a modal widget
2590 This property only makes sense for windows. A modal widget
2591 prevents widgets in all other windows from getting any input.
2593 By default, this property is false.
2595 \sa isWindow(), windowModality, QDialog
2599 \property QWidget::windowModality
2600 \brief which windows are blocked by the modal widget
2603 This property only makes sense for windows. A modal widget
2604 prevents widgets in other windows from getting input. The value of
2605 this property controls which windows are blocked when the widget
2606 is visible. Changing this property while the window is visible has
2607 no effect; you must hide() the widget first, then show() it again.
2609 By default, this property is Qt::NonModal.
2611 \sa isWindow(), QWidget::modal, QDialog
2614 Qt::WindowModality QWidget::windowModality() const
2616 return static_cast<Qt::WindowModality>(data->window_modality);
2619 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2621 data->window_modality = windowModality;
2622 // setModal_sys() will be called by setAttribute()
2623 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2624 setAttribute(Qt::WA_SetWindowModality, true);
2628 \fn bool QWidget::underMouse() const
2630 Returns true if the widget is under the mouse cursor; otherwise
2633 This value is not updated properly during drag and drop
2636 \sa enterEvent(), leaveEvent()
2640 \property QWidget::minimized
2641 \brief whether this widget is minimized (iconified)
2643 This property is only relevant for windows.
2645 By default, this property is false.
2647 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2649 bool QWidget::isMinimized() const
2650 { return data->window_state & Qt::WindowMinimized; }
2653 Shows the widget minimized, as an icon.
2655 Calling this function only affects \l{isWindow()}{windows}.
2657 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2660 void QWidget::showMinimized()
2662 bool isMin = isMinimized();
2663 if (isMin && isVisible())
2669 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2674 \property QWidget::maximized
2675 \brief whether this widget is maximized
2677 This property is only relevant for windows.
2679 \note Due to limitations on some window systems, this does not always
2680 report the expected results (e.g., if the user on X11 maximizes the
2681 window via the window manager, Qt has no way of distinguishing this
2682 from any other resize). This is expected to improve as window manager
2685 By default, this property is false.
2687 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2689 bool QWidget::isMaximized() const
2690 { return data->window_state & Qt::WindowMaximized; }
2695 Returns the current window state. The window state is a OR'ed
2696 combination of Qt::WindowState: Qt::WindowMinimized,
2697 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2699 \sa Qt::WindowState setWindowState()
2701 Qt::WindowStates QWidget::windowState() const
2703 return Qt::WindowStates(data->window_state);
2708 The function sets the window state on child widgets similar to
2709 setWindowState(). The difference is that the window state changed
2710 event has the isOverride() flag set. It exists mainly to keep
2713 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2715 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2716 data->window_state = newstate;
2717 QApplication::sendEvent(this, &e);
2721 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2723 Sets the window state to \a windowState. The window state is a OR'ed
2724 combination of Qt::WindowState: Qt::WindowMinimized,
2725 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2727 If the window is not visible (i.e. isVisible() returns false), the
2728 window state will take effect when show() is called. For visible
2729 windows, the change is immediate. For example, to toggle between
2730 full-screen and normal mode, use the following code:
2732 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2734 In order to restore and activate a minimized window (while
2735 preserving its maximized and/or full-screen state), use the following:
2737 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2739 Calling this function will hide the widget. You must call show() to make
2740 the widget visible again.
2742 \note On some window systems Qt::WindowActive is not immediate, and may be
2743 ignored in certain cases.
2745 When the window state changes, the widget receives a changeEvent()
2746 of type QEvent::WindowStateChange.
2748 \sa Qt::WindowState windowState()
2752 \property QWidget::fullScreen
2753 \brief whether the widget is shown in full screen mode
2755 A widget in full screen mode occupies the whole screen area and does not
2756 display window decorations, such as a title bar.
2758 By default, this property is false.
2760 \sa windowState(), minimized, maximized
2762 bool QWidget::isFullScreen() const
2763 { return data->window_state & Qt::WindowFullScreen; }
2766 Shows the widget in full-screen mode.
2768 Calling this function only affects \l{isWindow()}{windows}.
2770 To return from full-screen mode, call showNormal().
2772 Full-screen mode works fine under Windows, but has certain
2773 problems under X. These problems are due to limitations of the
2774 ICCCM protocol that specifies the communication between X11
2775 clients and the window manager. ICCCM simply does not understand
2776 the concept of non-decorated full-screen windows. Therefore, the
2777 best we can do is to request a borderless window and place and
2778 resize it to fill the entire screen. Depending on the window
2779 manager, this may or may not work. The borderless window is
2780 requested using MOTIF hints, which are at least partially
2781 supported by virtually all modern window managers.
2783 An alternative would be to bypass the window manager entirely and
2784 create a window with the Qt::X11BypassWindowManagerHint flag. This
2785 has other severe problems though, like totally broken keyboard focus
2786 and very strange effects on desktop changes or when the user raises
2789 X11 window managers that follow modern post-ICCCM specifications
2790 support full-screen mode properly.
2792 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2794 void QWidget::showFullScreen()
2797 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2798 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2799 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2800 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2801 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2802 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2807 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2808 | Qt::WindowFullScreen);
2814 Shows the widget maximized.
2816 Calling this function only affects \l{isWindow()}{windows}.
2818 On X11, this function may not work properly with certain window
2819 managers. See the \l{Window Geometry} documentation for an explanation.
2821 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2823 void QWidget::showMaximized()
2827 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2828 | Qt::WindowMaximized);
2830 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2831 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2834 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2835 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2836 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2837 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2845 Restores the widget after it has been maximized or minimized.
2847 Calling this function only affects \l{isWindow()}{windows}.
2849 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2851 void QWidget::showNormal()
2855 setWindowState(windowState() & ~(Qt::WindowMinimized
2856 | Qt::WindowMaximized
2857 | Qt::WindowFullScreen));
2859 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2860 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2863 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2864 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2865 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2866 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2874 Returns true if this widget would become enabled if \a ancestor is
2875 enabled; otherwise returns false.
2879 This is the case if neither the widget itself nor every parent up
2880 to but excluding \a ancestor has been explicitly disabled.
2882 isEnabledTo(0) is equivalent to isEnabled().
2884 \sa setEnabled() enabled
2887 bool QWidget::isEnabledTo(QWidget* ancestor) const
2889 const QWidget * w = this;
2890 while (!w->testAttribute(Qt::WA_ForceDisabled)
2892 && w->parentWidget()
2893 && w->parentWidget() != ancestor)
2894 w = w->parentWidget();
2895 return !w->testAttribute(Qt::WA_ForceDisabled);
2898 #ifndef QT_NO_ACTION
2900 Appends the action \a action to this widget's list of actions.
2902 All QWidgets have a list of \l{QAction}s, however they can be
2903 represented graphically in many different ways. The default use of
2904 the QAction list (as returned by actions()) is to create a context
2907 A QWidget should only have one of each action and adding an action
2908 it already has will not cause the same action to be in the widget twice.
2910 The ownership of \a action is not transferred to this QWidget.
2912 \sa removeAction(), insertAction(), actions(), QMenu
2914 void QWidget::addAction(QAction *action)
2916 insertAction(0, action);
2920 Appends the actions \a actions to this widget's list of actions.
2922 \sa removeAction(), QMenu, addAction()
2924 void QWidget::addActions(QList<QAction*> actions)
2926 for(int i = 0; i < actions.count(); i++)
2927 insertAction(0, actions.at(i));
2931 Inserts the action \a action to this widget's list of actions,
2932 before the action \a before. It appends the action if \a before is 0 or
2933 \a before is not a valid action for this widget.
2935 A QWidget should only have one of each action.
2937 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2939 void QWidget::insertAction(QAction *before, QAction *action)
2942 qWarning("QWidget::insertAction: Attempt to insert null action");
2947 if(d->actions.contains(action))
2948 removeAction(action);
2950 int pos = d->actions.indexOf(before);
2953 pos = d->actions.size();
2955 d->actions.insert(pos, action);
2957 QActionPrivate *apriv = action->d_func();
2958 apriv->widgets.append(this);
2960 QActionEvent e(QEvent::ActionAdded, action, before);
2961 QApplication::sendEvent(this, &e);
2965 Inserts the actions \a actions to this widget's list of actions,
2966 before the action \a before. It appends the action if \a before is 0 or
2967 \a before is not a valid action for this widget.
2969 A QWidget can have at most one of each action.
2971 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2973 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2975 for(int i = 0; i < actions.count(); ++i)
2976 insertAction(before, actions.at(i));
2980 Removes the action \a action from this widget's list of actions.
2981 \sa insertAction(), actions(), insertAction()
2983 void QWidget::removeAction(QAction *action)
2990 QActionPrivate *apriv = action->d_func();
2991 apriv->widgets.removeAll(this);
2993 if (d->actions.removeAll(action)) {
2994 QActionEvent e(QEvent::ActionRemoved, action);
2995 QApplication::sendEvent(this, &e);
3000 Returns the (possibly empty) list of this widget's actions.
3002 \sa contextMenuPolicy, insertAction(), removeAction()
3004 QList<QAction*> QWidget::actions() const
3009 #endif // QT_NO_ACTION
3012 \fn bool QWidget::isEnabledToTLW() const
3015 This function is deprecated. It is equivalent to isEnabled()
3019 \property QWidget::enabled
3020 \brief whether the widget is enabled
3022 In general an enabled widget handles keyboard and mouse events; a disabled
3023 widget does not. An exception is made with \l{QAbstractButton}.
3025 Some widgets display themselves differently when they are
3026 disabled. For example a button might draw its label grayed out. If
3027 your widget needs to know when it becomes enabled or disabled, you
3028 can use the changeEvent() with type QEvent::EnabledChange.
3030 Disabling a widget implicitly disables all its children. Enabling
3031 respectively enables all child widgets unless they have been
3032 explicitly disabled.
3034 By default, this property is true.
3036 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3038 void QWidget::setEnabled(bool enable)
3041 setAttribute(Qt::WA_ForceDisabled, !enable);
3042 d->setEnabled_helper(enable);
3045 void QWidgetPrivate::setEnabled_helper(bool enable)
3049 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3050 return; // nothing we can do
3052 if (enable != q->testAttribute(Qt::WA_Disabled))
3053 return; // nothing to do
3055 q->setAttribute(Qt::WA_Disabled, !enable);
3056 updateSystemBackground();
3058 if (!enable && q->window()->focusWidget() == q) {
3059 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3060 if (!parentIsEnabled || !q->focusNextChild())
3064 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3065 for (int i = 0; i < children.size(); ++i) {
3066 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3067 if (w && !w->testAttribute(attribute))
3068 w->d_func()->setEnabled_helper(enable);
3070 #if defined(Q_WS_X11)
3071 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3072 // enforce the windows behavior of clearing the cursor on
3074 qt_x11_enforce_cursor(q);
3077 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3078 // enforce the windows behavior of clearing the cursor on
3080 qt_qpa_set_cursor(q, false);
3082 #if defined(Q_WS_MAC)
3083 setEnabled_helper_sys(enable);
3086 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3087 QWidget *focusWidget = effectiveFocusWidget();
3090 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3091 qApp->inputMethod()->update(Qt::ImEnabled);
3093 qApp->inputMethod()->reset();
3094 qApp->inputMethod()->update(Qt::ImEnabled);
3098 QEvent e(QEvent::EnabledChange);
3099 QApplication::sendEvent(q, &e);
3103 \property QWidget::acceptDrops
3104 \brief whether drop events are enabled for this widget
3106 Setting this property to true announces to the system that this
3107 widget \e may be able to accept drop events.
3109 If the widget is the desktop (windowType() == Qt::Desktop), this may
3110 fail if another application is using the desktop; you can call
3111 acceptDrops() to test if this occurs.
3113 \warning Do not modify this property in a drag and drop event handler.
3115 By default, this property is false.
3119 bool QWidget::acceptDrops() const
3121 return testAttribute(Qt::WA_AcceptDrops);
3124 void QWidget::setAcceptDrops(bool on)
3126 setAttribute(Qt::WA_AcceptDrops, on);
3132 Disables widget input events if \a disable is true; otherwise
3133 enables input events.
3135 See the \l enabled documentation for more information.
3137 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3139 void QWidget::setDisabled(bool disable)
3141 setEnabled(!disable);
3145 \property QWidget::frameGeometry
3146 \brief geometry of the widget relative to its parent including any
3149 See the \l{Window Geometry} documentation for an overview of geometry
3150 issues with windows.
3152 By default, this property contains a value that depends on the user's
3153 platform and screen geometry.
3155 \sa geometry() x() y() pos()
3157 QRect QWidget::frameGeometry() const
3160 if (isWindow() && ! (windowType() == Qt::Popup)) {
3161 QRect fs = d->frameStrut();
3162 return QRect(data->crect.x() - fs.left(),
3163 data->crect.y() - fs.top(),
3164 data->crect.width() + fs.left() + fs.right(),
3165 data->crect.height() + fs.top() + fs.bottom());
3171 \property QWidget::x
3173 \brief the x coordinate of the widget relative to its parent including
3176 See the \l{Window Geometry} documentation for an overview of geometry
3177 issues with windows.
3179 By default, this property has a value of 0.
3181 \sa frameGeometry, y, pos
3183 int QWidget::x() const
3186 if (isWindow() && ! (windowType() == Qt::Popup))
3187 return data->crect.x() - d->frameStrut().left();
3188 return data->crect.x();
3192 \property QWidget::y
3193 \brief the y coordinate of the widget relative to its parent and
3194 including any window frame
3196 See the \l{Window Geometry} documentation for an overview of geometry
3197 issues with windows.
3199 By default, this property has a value of 0.
3201 \sa frameGeometry, x, pos
3203 int QWidget::y() const
3206 if (isWindow() && ! (windowType() == Qt::Popup))
3207 return data->crect.y() - d->frameStrut().top();
3208 return data->crect.y();
3212 \property QWidget::pos
3213 \brief the position of the widget within its parent widget
3215 If the widget is a window, the position is that of the widget on
3216 the desktop, including its frame.
3218 When changing the position, the widget, if visible, receives a
3219 move event (moveEvent()) immediately. If the widget is not
3220 currently visible, it is guaranteed to receive an event before it
3223 By default, this property contains a position that refers to the
3226 \warning Calling move() or setGeometry() inside moveEvent() can
3227 lead to infinite recursion.
3229 See the \l{Window Geometry} documentation for an overview of geometry
3230 issues with windows.
3232 \sa frameGeometry, size x(), y()
3234 QPoint QWidget::pos() const
3237 if (isWindow() && ! (windowType() == Qt::Popup)) {
3238 QRect fs = d->frameStrut();
3239 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3241 return data->crect.topLeft();
3245 \property QWidget::geometry
3246 \brief the geometry of the widget relative to its parent and
3247 excluding the window frame
3249 When changing the geometry, the widget, if visible, receives a
3250 move event (moveEvent()) and/or a resize event (resizeEvent())
3251 immediately. If the widget is not currently visible, it is
3252 guaranteed to receive appropriate events before it is shown.
3254 The size component is adjusted if it lies outside the range
3255 defined by minimumSize() and maximumSize().
3257 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3258 can lead to infinite recursion.
3260 See the \l{Window Geometry} documentation for an overview of geometry
3261 issues with windows.
3263 By default, this property contains a value that depends on the user's
3264 platform and screen geometry.
3266 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3267 resizeEvent(), minimumSize(), maximumSize()
3271 \property QWidget::normalGeometry
3273 \brief the geometry of the widget as it will appear when shown as
3274 a normal (not maximized or full screen) top-level widget
3276 For child widgets this property always holds an empty rectangle.
3278 By default, this property contains an empty rectangle.
3280 \sa QWidget::windowState(), QWidget::geometry
3284 \property QWidget::size
3285 \brief the size of the widget excluding any window frame
3287 If the widget is visible when it is being resized, it receives a resize event
3288 (resizeEvent()) immediately. If the widget is not currently
3289 visible, it is guaranteed to receive an event before it is shown.
3291 The size is adjusted if it lies outside the range defined by
3292 minimumSize() and maximumSize().
3294 By default, this property contains a value that depends on the user's
3295 platform and screen geometry.
3297 \warning Calling resize() or setGeometry() inside resizeEvent() can
3298 lead to infinite recursion.
3300 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3301 appear on screen. This also applies to windows.
3303 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3307 \property QWidget::width
3308 \brief the width of the widget excluding any window frame
3310 See the \l{Window Geometry} documentation for an overview of geometry
3311 issues with windows.
3313 \note Do not use this function to find the width of a screen on
3314 a \l{QDesktopWidget}{multiple screen desktop}. Read
3315 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3317 By default, this property contains a value that depends on the user's
3318 platform and screen geometry.
3320 \sa geometry, height, size
3324 \property QWidget::height
3325 \brief the height of the widget excluding any window frame
3327 See the \l{Window Geometry} documentation for an overview of geometry
3328 issues with windows.
3330 \note Do not use this function to find the height of a screen
3331 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3332 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3334 By default, this property contains a value that depends on the user's
3335 platform and screen geometry.
3337 \sa geometry, width, size
3341 \property QWidget::rect
3342 \brief the internal geometry of the widget excluding any window
3345 The rect property equals QRect(0, 0, width(), height()).
3347 See the \l{Window Geometry} documentation for an overview of geometry
3348 issues with windows.
3350 By default, this property contains a value that depends on the user's
3351 platform and screen geometry.
3357 QRect QWidget::normalGeometry() const
3360 if (!d->extra || !d->extra->topextra)
3363 if (!isMaximized() && !isFullScreen())
3366 return d->topData()->normalGeometry;
3371 \property QWidget::childrenRect
3372 \brief the bounding rectangle of the widget's children
3374 Hidden children are excluded.
3376 By default, for a widget with no children, this property contains a
3377 rectangle with zero width and height located at the origin.
3379 \sa childrenRegion() geometry()
3382 QRect QWidget::childrenRect() const
3385 QRect r(0, 0, 0, 0);
3386 for (int i = 0; i < d->children.size(); ++i) {
3387 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3388 if (w && !w->isWindow() && !w->isHidden())
3395 \property QWidget::childrenRegion
3396 \brief the combined region occupied by the widget's children
3398 Hidden children are excluded.
3400 By default, for a widget with no children, this property contains an
3403 \sa childrenRect() geometry() mask()
3406 QRegion QWidget::childrenRegion() const
3410 for (int i = 0; i < d->children.size(); ++i) {
3411 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3412 if (w && !w->isWindow() && !w->isHidden()) {
3413 QRegion mask = w->mask();
3417 r |= mask.translated(w->pos());
3425 \property QWidget::minimumSize
3426 \brief the widget's minimum size
3428 The widget cannot be resized to a smaller size than the minimum
3429 widget size. The widget's size is forced to the minimum size if
3430 the current size is smaller.
3432 The minimum size set by this function will override the minimum size
3433 defined by QLayout. In order to unset the minimum size, use a
3434 value of \c{QSize(0, 0)}.
3436 By default, this property contains a size with zero width and height.
3438 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3441 QSize QWidget::minimumSize() const
3444 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3448 \property QWidget::maximumSize
3449 \brief the widget's maximum size in pixels
3451 The widget cannot be resized to a larger size than the maximum
3454 By default, this property contains a size in which both width and height
3455 have values of 16777215.
3457 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3460 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3463 QSize QWidget::maximumSize() const
3466 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3467 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3472 \property QWidget::minimumWidth
3473 \brief the widget's minimum width in pixels
3475 This property corresponds to the width held by the \l minimumSize property.
3477 By default, this property has a value of 0.
3479 \sa minimumSize, minimumHeight
3483 \property QWidget::minimumHeight
3484 \brief the widget's minimum height in pixels
3486 This property corresponds to the height held by the \l minimumSize property.
3488 By default, this property has a value of 0.
3490 \sa minimumSize, minimumWidth
3494 \property QWidget::maximumWidth
3495 \brief the widget's maximum width in pixels
3497 This property corresponds to the width held by the \l maximumSize property.
3499 By default, this property contains a value of 16777215.
3501 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3504 \sa maximumSize, maximumHeight
3508 \property QWidget::maximumHeight
3509 \brief the widget's maximum height in pixels
3511 This property corresponds to the height held by the \l maximumSize property.
3513 By default, this property contains a value of 16777215.
3515 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3518 \sa maximumSize, maximumWidth
3522 \property QWidget::sizeIncrement
3523 \brief the size increment of the widget
3525 When the user resizes the window, the size will move in steps of
3526 sizeIncrement().width() pixels horizontally and
3527 sizeIncrement.height() pixels vertically, with baseSize() as the
3528 basis. Preferred widget sizes are for non-negative integers \e i
3530 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3532 Note that while you can set the size increment for all widgets, it
3533 only affects windows.
3535 By default, this property contains a size with zero width and height.
3537 \warning The size increment has no effect under Windows, and may
3538 be disregarded by the window manager on X11.
3540 \sa size, minimumSize, maximumSize
3542 QSize QWidget::sizeIncrement() const
3545 return (d->extra && d->extra->topextra)
3546 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3551 \property QWidget::baseSize
3552 \brief the base size of the widget
3554 The base size is used to calculate a proper widget size if the
3555 widget defines sizeIncrement().
3557 By default, for a newly-created widget, this property contains a size with
3558 zero width and height.
3560 \sa setSizeIncrement()
3563 QSize QWidget::baseSize() const
3566 return (d->extra != 0 && d->extra->topextra != 0)
3567 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3571 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3575 int mw = minw, mh = minh;
3576 if (mw == QWIDGETSIZE_MAX)
3578 if (mh == QWIDGETSIZE_MAX)
3580 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3581 qWarning("QWidget::setMinimumSize: (%s/%s) "
3582 "The largest allowed size is (%d,%d)",
3583 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3585 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3586 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3588 if (minw < 0 || minh < 0) {
3589 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3591 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3592 minw = mw = qMax(minw, 0);
3593 minh = mh = qMax(minh, 0);
3596 if (extra->minw == mw && extra->minh == mh)
3600 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3607 This function corresponds to setMinimumSize(QSize(minw, minh)).
3608 Sets the minimum width to \a minw and the minimum height to \a
3612 void QWidget::setMinimumSize(int minw, int minh)
3615 if (!d->setMinimumSize_helper(minw, minh))
3619 d->setConstraints_sys();
3620 if (minw > width() || minh > height()) {
3621 bool resized = testAttribute(Qt::WA_Resized);
3622 bool maximized = isMaximized();
3623 resize(qMax(minw,width()), qMax(minh,height()));
3624 setAttribute(Qt::WA_Resized, resized); //not a user resize
3626 data->window_state = data->window_state | Qt::WindowMaximized;
3628 #ifndef QT_NO_GRAPHICSVIEW
3630 if (d->extra->proxyWidget)
3631 d->extra->proxyWidget->setMinimumSize(minw, minh);
3634 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3637 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3640 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3641 qWarning("QWidget::setMaximumSize: (%s/%s) "
3642 "The largest allowed size is (%d,%d)",
3643 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3645 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3646 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3648 if (maxw < 0 || maxh < 0) {
3649 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3651 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3652 maxw = qMax(maxw, 0);
3653 maxh = qMax(maxh, 0);
3656 if (extra->maxw == maxw && extra->maxh == maxh)
3660 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3661 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3668 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3669 maxh)). Sets the maximum width to \a maxw and the maximum height
3672 void QWidget::setMaximumSize(int maxw, int maxh)
3675 if (!d->setMaximumSize_helper(maxw, maxh))
3679 d->setConstraints_sys();
3680 if (maxw < width() || maxh < height()) {
3681 bool resized = testAttribute(Qt::WA_Resized);
3682 resize(qMin(maxw,width()), qMin(maxh,height()));
3683 setAttribute(Qt::WA_Resized, resized); //not a user resize
3686 #ifndef QT_NO_GRAPHICSVIEW
3688 if (d->extra->proxyWidget)
3689 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3693 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3699 Sets the x (width) size increment to \a w and the y (height) size
3702 void QWidget::setSizeIncrement(int w, int h)
3706 QTLWExtra* x = d->topData();
3707 if (x->incw == w && x->inch == h)
3712 d->setConstraints_sys();
3718 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3719 the widgets base size to width \a basew and height \a baseh.
3721 void QWidget::setBaseSize(int basew, int baseh)
3725 QTLWExtra* x = d->topData();
3726 if (x->basew == basew && x->baseh == baseh)
3731 d->setConstraints_sys();
3735 Sets both the minimum and maximum sizes of the widget to \a s,
3736 thereby preventing it from ever growing or shrinking.
3738 This will override the default size constraints set by QLayout.
3740 To remove constraints, set the size to QWIDGETSIZE_MAX.
3742 Alternatively, if you want the widget to have a
3743 fixed size based on its contents, you can call
3744 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3746 \sa maximumSize, minimumSize
3749 void QWidget::setFixedSize(const QSize & s)
3751 setFixedSize(s.width(), s.height());
3756 \fn void QWidget::setFixedSize(int w, int h)
3759 Sets the width of the widget to \a w and the height to \a h.
3762 void QWidget::setFixedSize(int w, int h)
3765 bool minSizeSet = d->setMinimumSize_helper(w, h);
3766 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3767 if (!minSizeSet && !maxSizeSet)
3771 d->setConstraints_sys();
3773 d->updateGeometry_helper(true);
3775 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3779 void QWidget::setMinimumWidth(int w)
3783 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3784 setMinimumSize(w, minimumSize().height());
3785 d->extra->explicitMinSize = expl;
3788 void QWidget::setMinimumHeight(int h)
3792 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3793 setMinimumSize(minimumSize().width(), h);
3794 d->extra->explicitMinSize = expl;
3797 void QWidget::setMaximumWidth(int w)
3801 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3802 setMaximumSize(w, maximumSize().height());
3803 d->extra->explicitMaxSize = expl;
3806 void QWidget::setMaximumHeight(int h)
3810 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3811 setMaximumSize(maximumSize().width(), h);
3812 d->extra->explicitMaxSize = expl;
3816 Sets both the minimum and maximum width of the widget to \a w
3817 without changing the heights. Provided for convenience.
3819 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3822 void QWidget::setFixedWidth(int w)
3826 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3827 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3828 setMinimumSize(w, minimumSize().height());
3829 setMaximumSize(w, maximumSize().height());
3830 d->extra->explicitMinSize = explMin;
3831 d->extra->explicitMaxSize = explMax;
3836 Sets both the minimum and maximum heights of the widget to \a h
3837 without changing the widths. Provided for convenience.
3839 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3842 void QWidget::setFixedHeight(int h)
3846 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3847 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3848 setMinimumSize(minimumSize().width(), h);
3849 setMaximumSize(maximumSize().width(), h);
3850 d->extra->explicitMinSize = explMin;
3851 d->extra->explicitMaxSize = explMax;
3856 Translates the widget coordinate \a pos to the coordinate system
3857 of \a parent. The \a parent must not be 0 and must be a parent
3858 of the calling widget.
3860 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3863 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3867 const QWidget * w = this;
3868 while (w != parent) {
3869 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3870 "parent must be in parent hierarchy");
3871 p = w->mapToParent(p);
3872 w = w->parentWidget();
3880 Translates the widget coordinate \a pos from the coordinate system
3881 of \a parent to this widget's coordinate system. The \a parent
3882 must not be 0 and must be a parent of the calling widget.
3884 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3887 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3891 const QWidget * w = this;
3892 while (w != parent) {
3893 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3894 "parent must be in parent hierarchy");
3896 p = w->mapFromParent(p);
3897 w = w->parentWidget();
3905 Translates the widget coordinate \a pos to a coordinate in the
3908 Same as mapToGlobal() if the widget has no parent.
3910 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3913 QPoint QWidget::mapToParent(const QPoint &pos) const
3915 return pos + data->crect.topLeft();
3919 Translates the parent widget coordinate \a pos to widget
3922 Same as mapFromGlobal() if the widget has no parent.
3924 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3927 QPoint QWidget::mapFromParent(const QPoint &pos) const
3929 return pos - data->crect.topLeft();
3934 Returns the window for this widget, i.e. the next ancestor widget
3935 that has (or could have) a window-system frame.
3937 If the widget is a window, the widget itself is returned.
3939 Typical usage is changing the window title:
3941 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3946 QWidget *QWidget::window() const
3948 QWidget *w = (QWidget *)this;
3949 QWidget *p = w->parentWidget();
3950 while (!w->isWindow() && p) {
3952 p = p->parentWidget();
3960 Returns the native parent for this widget, i.e. the next ancestor widget
3961 that has a system identifier, or 0 if it does not have any native parent.
3963 \sa effectiveWinId()
3965 QWidget *QWidget::nativeParentWidget() const
3967 QWidget *parent = parentWidget();
3968 while (parent && !parent->internalWinId())
3969 parent = parent->parentWidget();
3973 /*! \fn QWidget *QWidget::topLevelWidget() const
3976 Use window() instead.
3982 Returns the background role of the widget.
3984 The background role defines the brush from the widget's \l palette that
3985 is used to render the background.
3987 If no explicit background role is set, the widget inherts its parent
3988 widget's background role.
3990 \sa setBackgroundRole(), foregroundRole()
3992 QPalette::ColorRole QWidget::backgroundRole() const
3995 const QWidget *w = this;
3997 QPalette::ColorRole role = w->d_func()->bg_role;
3998 if (role != QPalette::NoRole)
4000 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4002 w = w->parentWidget();
4004 return QPalette::Window;
4008 Sets the background role of the widget to \a role.
4010 The background role defines the brush from the widget's \l palette that
4011 is used to render the background.
4013 If \a role is QPalette::NoRole, then the widget inherits its
4014 parent's background role.
4016 Note that styles are free to choose any color from the palette.
4017 You can modify the palette or set a style sheet if you don't
4018 achieve the result you want with setBackgroundRole().
4020 \sa backgroundRole(), foregroundRole()
4023 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4027 d->updateSystemBackground();
4028 d->propagatePaletteChange();
4029 d->updateIsOpaque();
4033 Returns the foreground role.
4035 The foreground role defines the color from the widget's \l palette that
4036 is used to draw the foreground.
4038 If no explicit foreground role is set, the function returns a role
4039 that contrasts with the background role.
4041 \sa setForegroundRole(), backgroundRole()
4043 QPalette::ColorRole QWidget::foregroundRole() const
4046 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4047 if (rl != QPalette::NoRole)
4049 QPalette::ColorRole role = QPalette::WindowText;
4050 switch (backgroundRole()) {
4051 case QPalette::Button:
4052 role = QPalette::ButtonText;
4054 case QPalette::Base:
4055 role = QPalette::Text;
4057 case QPalette::Dark:
4058 case QPalette::Shadow:
4059 role = QPalette::Light;
4061 case QPalette::Highlight:
4062 role = QPalette::HighlightedText;
4064 case QPalette::ToolTipBase:
4065 role = QPalette::ToolTipText;
4074 Sets the foreground role of the widget to \a role.
4076 The foreground role defines the color from the widget's \l palette that
4077 is used to draw the foreground.
4079 If \a role is QPalette::NoRole, the widget uses a foreground role
4080 that contrasts with the background role.
4082 Note that styles are free to choose any color from the palette.
4083 You can modify the palette or set a style sheet if you don't
4084 achieve the result you want with setForegroundRole().
4086 \sa foregroundRole(), backgroundRole()
4088 void QWidget::setForegroundRole(QPalette::ColorRole role)
4092 d->updateSystemBackground();
4093 d->propagatePaletteChange();
4097 \property QWidget::palette
4098 \brief the widget's palette
4100 This property describes the widget's palette. The palette is used by the
4101 widget's style when rendering standard components, and is available as a
4102 means to ensure that custom widgets can maintain consistency with the
4103 native platform's look and feel. It's common that different platforms, or
4104 different styles, have different palettes.
4106 When you assign a new palette to a widget, the color roles from this
4107 palette are combined with the widget's default palette to form the
4108 widget's final palette. The palette entry for the widget's background role
4109 is used to fill the widget's background (see QWidget::autoFillBackground),
4110 and the foreground role initializes QPainter's pen.
4112 The default depends on the system environment. QApplication maintains a
4113 system/theme palette which serves as a default for all widgets. There may
4114 also be special palette defaults for certain types of widgets (e.g., on
4115 Windows XP and Vista, all classes that derive from QMenuBar have a special
4116 default palette). You can also define default palettes for widgets
4117 yourself by passing a custom palette and the name of a widget to
4118 QApplication::setPalette(). Finally, the style always has the option of
4119 polishing the palette as it's assigned (see QStyle::polish()).
4121 QWidget propagates explicit palette roles from parent to child. If you
4122 assign a brush or color to a specific role on a palette and assign that
4123 palette to a widget, that role will propagate to all the widget's
4124 children, overriding any system defaults for that role. Note that palettes
4125 by default don't propagate to windows (see isWindow()) unless the
4126 Qt::WA_WindowPropagation attribute is enabled.
4128 QWidget's palette propagation is similar to its font propagation.
4130 The current style, which is used to render the content of all standard Qt
4131 widgets, is free to choose colors and brushes from the widget palette, or
4132 in some cases, to ignore the palette (partially, or completely). In
4133 particular, certain styles like GTK style, Mac style, Windows XP, and
4134 Vista style, depend on third party APIs to render the content of widgets,
4135 and these styles typically do not follow the palette. Because of this,
4136 assigning roles to a widget's palette is not guaranteed to change the
4137 appearance of the widget. Instead, you may choose to apply a \l
4138 styleSheet. You can refer to our Knowledge Base article
4139 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4142 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4143 When using style sheets, the palette of a widget can be customized using
4144 the "color", "background-color", "selection-color",
4145 "selection-background-color" and "alternate-background-color".
4147 \sa QApplication::palette(), QWidget::font()
4149 const QPalette &QWidget::palette() const
4152 data->pal.setCurrentColorGroup(QPalette::Disabled);
4153 } else if ((!isVisible() || isActiveWindow())
4154 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4155 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4158 data->pal.setCurrentColorGroup(QPalette::Active);
4161 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4162 if (qt_mac_can_clickThrough(this))
4163 data->pal.setCurrentColorGroup(QPalette::Active);
4166 data->pal.setCurrentColorGroup(QPalette::Inactive);
4171 void QWidget::setPalette(const QPalette &palette)
4174 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4176 // Determine which palette is inherited from this widget's ancestors and
4177 // QApplication::palette, resolve this against \a palette (attributes from
4178 // the inherited palette are copied over this widget's palette). Then
4179 // propagate this palette to this widget's children.
4180 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4181 QPalette resolvedPalette = palette.resolve(naturalPalette);
4182 d->setPalette_helper(resolvedPalette);
4188 Returns the palette that the widget \a w inherits from its ancestors and
4189 QApplication::palette. \a inheritedMask is the combination of the widget's
4190 ancestors palette request masks (i.e., which attributes from the parent
4191 widget's palette are implicitly imposed on this widget by the user). Note
4192 that this font does not take into account the palette set on \a w itself.
4194 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4197 QPalette naturalPalette = QApplication::palette(q);
4198 if (!q->testAttribute(Qt::WA_StyleSheet)
4199 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4200 #ifndef QT_NO_GRAPHICSVIEW
4201 || (extra && extra->proxyWidget)
4202 #endif //QT_NO_GRAPHICSVIEW
4204 if (QWidget *p = q->parentWidget()) {
4205 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4206 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4207 QPalette inheritedPalette = p->palette();
4208 inheritedPalette.resolve(inheritedMask);
4209 naturalPalette = inheritedPalette.resolve(naturalPalette);
4211 naturalPalette = p->palette();
4215 #ifndef QT_NO_GRAPHICSVIEW
4216 else if (extra && extra->proxyWidget) {
4217 QPalette inheritedPalette = extra->proxyWidget->palette();
4218 inheritedPalette.resolve(inheritedMask);
4219 naturalPalette = inheritedPalette.resolve(naturalPalette);
4221 #endif //QT_NO_GRAPHICSVIEW
4223 naturalPalette.resolve(0);
4224 return naturalPalette;
4229 Determine which palette is inherited from this widget's ancestors and
4230 QApplication::palette, resolve this against this widget's palette
4231 (attributes from the inherited palette are copied over this widget's
4232 palette). Then propagate this palette to this widget's children.
4234 void QWidgetPrivate::resolvePalette()
4236 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4237 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4238 setPalette_helper(resolvedPalette);
4241 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4244 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4247 updateSystemBackground();
4248 propagatePaletteChange();
4255 \property QWidget::font
4256 \brief the font currently set for the widget
4258 This property describes the widget's requested font. The font is used by
4259 the widget's style when rendering standard components, and is available as
4260 a means to ensure that custom widgets can maintain consistency with the
4261 native platform's look and feel. It's common that different platforms, or
4262 different styles, define different fonts for an application.
4264 When you assign a new font to a widget, the properties from this font are
4265 combined with the widget's default font to form the widget's final
4266 font. You can call fontInfo() to get a copy of the widget's final
4267 font. The final font is also used to initialize QPainter's font.
4269 The default depends on the system environment. QApplication maintains a
4270 system/theme font which serves as a default for all widgets. There may
4271 also be special font defaults for certain types of widgets. You can also
4272 define default fonts for widgets yourself by passing a custom font and the
4273 name of a widget to QApplication::setFont(). Finally, the font is matched
4274 against Qt's font database to find the best match.
4276 QWidget propagates explicit font properties from parent to child. If you
4277 change a specific property on a font and assign that font to a widget,
4278 that property will propagate to all the widget's children, overriding any
4279 system defaults for that property. Note that fonts by default don't
4280 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4281 attribute is enabled.
4283 QWidget's font propagation is similar to its palette propagation.
4285 The current style, which is used to render the content of all standard Qt
4286 widgets, is free to choose to use the widget font, or in some cases, to
4287 ignore it (partially, or completely). In particular, certain styles like
4288 GTK style, Mac style, Windows XP, and Vista style, apply special
4289 modifications to the widget font to match the platform's native look and
4290 feel. Because of this, assigning properties to a widget's font is not
4291 guaranteed to change the appearance of the widget. Instead, you may choose
4292 to apply a \l styleSheet.
4294 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4295 style sheets will take precedence if the settings conflict.
4297 \sa fontInfo(), fontMetrics()
4300 void QWidget::setFont(const QFont &font)
4304 #ifndef QT_NO_STYLE_STYLESHEET
4305 const QStyleSheetStyle* style;
4306 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4307 style->saveWidgetFont(this, font);
4311 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4313 // Determine which font is inherited from this widget's ancestors and
4314 // QApplication::font, resolve this against \a font (attributes from the
4315 // inherited font are copied over). Then propagate this font to this
4316 // widget's children.
4317 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4318 QFont resolvedFont = font.resolve(naturalFont);
4319 d->setFont_helper(resolvedFont);
4325 Returns the font that the widget \a w inherits from its ancestors and
4326 QApplication::font. \a inheritedMask is the combination of the widget's
4327 ancestors font request masks (i.e., which attributes from the parent
4328 widget's font are implicitly imposed on this widget by the user). Note
4329 that this font does not take into account the font set on \a w itself.
4331 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4332 is applied, fonts are not propagated anymore
4334 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4337 QFont naturalFont = QApplication::font(q);
4338 if (!q->testAttribute(Qt::WA_StyleSheet)
4339 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4340 #ifndef QT_NO_GRAPHICSVIEW
4341 || (extra && extra->proxyWidget)
4342 #endif //QT_NO_GRAPHICSVIEW
4344 if (QWidget *p = q->parentWidget()) {
4345 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4346 if (!naturalFont.isCopyOf(QApplication::font())) {
4347 QFont inheritedFont = p->font();
4348 inheritedFont.resolve(inheritedMask);
4349 naturalFont = inheritedFont.resolve(naturalFont);
4351 naturalFont = p->font();
4355 #ifndef QT_NO_GRAPHICSVIEW
4356 else if (extra && extra->proxyWidget) {
4357 QFont inheritedFont = extra->proxyWidget->font();
4358 inheritedFont.resolve(inheritedMask);
4359 naturalFont = inheritedFont.resolve(naturalFont);
4361 #endif //QT_NO_GRAPHICSVIEW
4363 naturalFont.resolve(0);
4370 Determine which font is implicitly imposed on this widget by its ancestors
4371 and QApplication::font, resolve this against its own font (attributes from
4372 the implicit font are copied over). Then propagate this font to this
4375 void QWidgetPrivate::resolveFont()
4377 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4378 QFont resolvedFont = data.fnt.resolve(naturalFont);
4379 setFont_helper(resolvedFont);
4385 Assign \a font to this widget, and propagate it to all children, except
4386 style sheet widgets (handled differently) and windows that don't enable
4387 window propagation. \a implicitMask is the union of all ancestor widgets'
4388 font request masks, and determines which attributes from this widget's
4389 font should propagate.
4391 void QWidgetPrivate::updateFont(const QFont &font)
4394 #ifndef QT_NO_STYLE_STYLESHEET
4395 const QStyleSheetStyle* cssStyle;
4396 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4399 data.fnt = QFont(font, q);
4400 #if defined(Q_WS_X11)
4401 // make sure the font set on this widget is associated with the correct screen
4402 data.fnt.x11SetScreen(xinfo.screen());
4404 // Combine new mask with natural mask and propagate to children.
4405 #ifndef QT_NO_GRAPHICSVIEW
4406 if (!q->parentWidget() && extra && extra->proxyWidget) {
4407 QGraphicsProxyWidget *p = extra->proxyWidget;
4408 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4410 #endif //QT_NO_GRAPHICSVIEW
4411 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4412 inheritedFontResolveMask = 0;
4414 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4416 for (int i = 0; i < children.size(); ++i) {
4417 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4420 #ifndef QT_NO_STYLE_STYLESHEET
4421 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4422 // Style sheets follow a different font propagation scheme.
4424 cssStyle->updateStyleSheetFont(w);
4426 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4427 // Propagate font changes.
4428 QWidgetPrivate *wd = w->d_func();
4429 wd->inheritedFontResolveMask = newMask;
4435 #ifndef QT_NO_STYLE_STYLESHEET
4437 cssStyle->updateStyleSheetFont(q);
4441 QEvent e(QEvent::FontChange);
4442 QApplication::sendEvent(q, &e);
4445 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4449 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4451 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4452 if (!children.isEmpty()) {
4453 for (int i = 0; i < children.size(); ++i) {
4454 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4455 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4456 w->d_func()->setLayoutDirection_helper(direction);
4459 QEvent e(QEvent::LayoutDirectionChange);
4460 QApplication::sendEvent(q, &e);
4463 void QWidgetPrivate::resolveLayoutDirection()
4466 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4467 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4471 \property QWidget::layoutDirection
4473 \brief the layout direction for this widget
4475 By default, this property is set to Qt::LeftToRight.
4477 When the layout direction is set on a widget, it will propagate to
4478 the widget's children, but not to a child that is a window and not
4479 to a child for which setLayoutDirection() has been explicitly
4480 called. Also, child widgets added \e after setLayoutDirection()
4481 has been called for the parent do not inherit the parent's layout
4484 This method no longer affects text layout direction since Qt 4.7.
4486 \sa QApplication::layoutDirection
4488 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4492 if (direction == Qt::LayoutDirectionAuto) {
4493 unsetLayoutDirection();
4497 setAttribute(Qt::WA_SetLayoutDirection);
4498 d->setLayoutDirection_helper(direction);
4501 Qt::LayoutDirection QWidget::layoutDirection() const
4503 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4506 void QWidget::unsetLayoutDirection()
4509 setAttribute(Qt::WA_SetLayoutDirection, false);
4510 d->resolveLayoutDirection();
4514 \fn QFontMetrics QWidget::fontMetrics() const
4516 Returns the font metrics for the widget's current font.
4517 Equivalent to QFontMetrics(widget->font()).
4519 \sa font(), fontInfo(), setFont()
4523 \fn QFontInfo QWidget::fontInfo() const
4525 Returns the font info for the widget's current font.
4526 Equivalent to QFontInto(widget->font()).
4528 \sa font(), fontMetrics(), setFont()
4533 \property QWidget::cursor
4534 \brief the cursor shape for this widget
4536 The mouse cursor will assume this shape when it's over this
4537 widget. See the \link Qt::CursorShape list of predefined cursor
4538 objects\endlink for a range of useful shapes.
4540 An editor widget might use an I-beam cursor:
4541 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4543 If no cursor has been set, or after a call to unsetCursor(), the
4544 parent's cursor is used.
4546 By default, this property contains a cursor with the Qt::ArrowCursor
4549 Some underlying window implementations will reset the cursor if it
4550 leaves a widget even if the mouse is grabbed. If you want to have
4551 a cursor set for all widgets, even when outside the window, consider
4552 QApplication::setOverrideCursor().
4554 \sa QApplication::setOverrideCursor()
4557 #ifndef QT_NO_CURSOR
4558 QCursor QWidget::cursor() const
4561 if (testAttribute(Qt::WA_SetCursor))
4562 return (d->extra && d->extra->curs)
4564 : QCursor(Qt::ArrowCursor);
4565 if (isWindow() || !parentWidget())
4566 return QCursor(Qt::ArrowCursor);
4567 return parentWidget()->cursor();
4570 void QWidget::setCursor(const QCursor &cursor)
4573 // On Mac we must set the cursor even if it is the ArrowCursor.
4574 #if !defined(Q_WS_MAC)
4575 if (cursor.shape() != Qt::ArrowCursor
4576 || (d->extra && d->extra->curs))
4580 QCursor *newCursor = new QCursor(cursor);
4581 delete d->extra->curs;
4582 d->extra->curs = newCursor;
4584 setAttribute(Qt::WA_SetCursor);
4585 d->setCursor_sys(cursor);
4587 QEvent event(QEvent::CursorChange);
4588 QApplication::sendEvent(this, &event);
4591 void QWidget::unsetCursor()
4595 delete d->extra->curs;
4599 setAttribute(Qt::WA_SetCursor, false);
4600 d->unsetCursor_sys();
4602 QEvent event(QEvent::CursorChange);
4603 QApplication::sendEvent(this, &event);
4609 \enum QWidget::RenderFlag
4611 This enum describes how to render the widget when calling QWidget::render().
4613 \value DrawWindowBackground If you enable this option, the widget's background
4614 is rendered into the target even if autoFillBackground is not set. By default,
4615 this option is enabled.
4617 \value DrawChildren If you enable this option, the widget's children
4618 are rendered recursively into the target. By default, this option is enabled.
4620 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4621 is ignored when rendering into the target. By default, this option is disabled.
4629 Renders the \a sourceRegion of this widget into the \a target
4630 using \a renderFlags to determine how to render. Rendering
4631 starts at \a targetOffset in the \a target. For example:
4633 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4635 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4636 the region, i.e. the entire widget.
4638 Ensure that you call QPainter::end() for the \a target device's
4639 active painter (if any) before rendering. For example:
4641 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4643 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4644 or QGLWidget::renderPixmap() instead.
4646 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4647 const QRegion &sourceRegion, RenderFlags renderFlags)
4649 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4655 Renders the widget into the \a painter's QPainter::device().
4657 Transformations and settings applied to the \a painter will be used
4660 \note The \a painter must be active. On Mac OS X the widget will be
4661 rendered into a QPixmap and then drawn by the \a painter.
4663 \sa QPainter::device()
4665 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4666 const QRegion &sourceRegion, RenderFlags renderFlags)
4669 qWarning("QWidget::render: Null pointer to painter");
4673 if (!painter->isActive()) {
4674 qWarning("QWidget::render: Cannot render with an inactive painter");
4678 const qreal opacity = painter->opacity();
4679 if (qFuzzyIsNull(opacity))
4680 return; // Fully transparent.
4683 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4684 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4686 if (toBePainted.isEmpty())
4691 d->extra->inRenderWithPainter = true;
4694 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4696 QPaintEngine *engine = painter->paintEngine();
4698 QPaintEnginePrivate *enginePriv = engine->d_func();
4699 Q_ASSERT(enginePriv);
4700 QPaintDevice *target = engine->paintDevice();
4703 // Render via a pixmap when dealing with non-opaque painters or printers.
4704 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4705 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4706 d->extra->inRenderWithPainter = false;
4710 // Set new shared painter.
4711 QPainter *oldPainter = d->sharedPainter();
4712 d->setSharedPainter(painter);
4714 // Save current system clip, viewport and transform,
4715 const QTransform oldTransform = enginePriv->systemTransform;
4716 const QRegion oldSystemClip = enginePriv->systemClip;
4717 const QRegion oldSystemViewport = enginePriv->systemViewport;
4719 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4720 if (painter->hasClipping()) {
4721 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4722 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4724 enginePriv->setSystemViewport(oldSystemClip);
4727 render(target, targetOffset, toBePainted, renderFlags);
4729 // Restore system clip, viewport and transform.
4730 enginePriv->systemClip = oldSystemClip;
4731 enginePriv->setSystemViewport(oldSystemViewport);
4732 enginePriv->setSystemTransform(oldTransform);
4734 // Restore shared painter.
4735 d->setSharedPainter(oldPainter);
4738 d->extra->inRenderWithPainter = false;
4741 static void sendResizeEvents(QWidget *target)
4743 QResizeEvent e(target->size(), QSize());
4744 QApplication::sendEvent(target, &e);
4746 const QObjectList children = target->children();
4747 for (int i = 0; i < children.size(); ++i) {
4748 QWidget *child = static_cast<QWidget*>(children.at(i));
4749 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4750 sendResizeEvents(child);
4757 Renders the widget into a pixmap restricted by the
4758 given \a rectangle. If the \a widget has any children, then
4759 they are also painted in the appropriate positions.
4761 If no rectangle is specified (the default) the entire widget is
4764 Replacement for Qt 4's QPixmap::grabWidget().
4766 \sa render(), QPixmap
4769 /* INVOKABLE since used by QPixmap::grabWidget(). */
4770 QPixmap QWidget::grab(const QRect &rectangle)
4773 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4774 sendResizeEvents(this);
4780 r.setWidth(width() - rectangle.x());
4782 r.setHeight(height() - rectangle.y());
4784 if (!r.intersects(rect()))
4787 QPixmap res(r.size());
4789 res.fill(Qt::transparent);
4790 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4791 | QWidget::DrawChildren | QWidget::IgnoreMask);
4796 \brief The graphicsEffect function returns a pointer to the
4797 widget's graphics effect.
4799 If the widget has no graphics effect, 0 is returned.
4803 \sa setGraphicsEffect()
4805 #ifndef QT_NO_GRAPHICSEFFECT
4806 QGraphicsEffect *QWidget::graphicsEffect() const
4809 return d->graphicsEffect;
4811 #endif //QT_NO_GRAPHICSEFFECT
4815 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4817 Sets \a effect as the widget's effect. If there already is an effect installed
4818 on this widget, QWidget will delete the existing effect before installing
4821 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4822 the effect from the widget and install it on this widget.
4824 QWidget takes ownership of \a effect.
4826 \note This function will apply the effect on itself and all its children.
4830 \sa graphicsEffect()
4832 #ifndef QT_NO_GRAPHICSEFFECT
4833 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4836 if (d->graphicsEffect == effect)
4839 if (d->graphicsEffect) {
4840 d->invalidateBuffer(rect());
4841 delete d->graphicsEffect;
4842 d->graphicsEffect = 0;
4847 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4848 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4849 d->graphicsEffect = effect;
4850 effect->d_func()->setGraphicsEffectSource(source);
4854 d->updateIsOpaque();
4856 #endif //QT_NO_GRAPHICSEFFECT
4858 bool QWidgetPrivate::isAboutToShow() const
4867 // The widget will be shown if any of its ancestors are about to show.
4868 QWidget *parent = q->parentWidget();
4869 return parent ? parent->d_func()->isAboutToShow() : false;
4872 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4875 const bool isVisible = q->isVisible();
4877 // Make sure the widget is laid out correctly.
4878 if (!isVisible && !isAboutToShow()) {
4879 QWidget *topLevel = q->window();
4880 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4881 topLevel->ensurePolished();
4883 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4884 // they're not explicitly hidden.
4885 QWidget *widget = q;
4886 QWidgetList hiddenWidgets;
4888 if (widget->isHidden()) {
4889 widget->setAttribute(Qt::WA_WState_Hidden, false);
4890 hiddenWidgets.append(widget);
4891 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4892 widget->d_func()->updateGeometry_helper(true);
4894 widget = widget->parentWidget();
4897 // Activate top-level layout.
4898 if (topLevel->d_func()->layout)
4899 topLevel->d_func()->layout->activate();
4901 // Adjust size if necessary.
4902 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4903 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4904 && !topLevel->testAttribute(Qt::WA_Resized)) {
4905 topLevel->adjustSize();
4906 topLevel->setAttribute(Qt::WA_Resized, false);
4909 // Activate child layouts.
4910 topLevel->d_func()->activateChildLayoutsRecursively();
4912 // We're not cheating with WA_WState_Hidden anymore.
4913 for (int i = 0; i < hiddenWidgets.size(); ++i) {
4914 QWidget *widget = hiddenWidgets.at(i);
4915 widget->setAttribute(Qt::WA_WState_Hidden);
4916 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4917 widget->parentWidget()->d_func()->layout->invalidate();
4919 } else if (isVisible) {
4920 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4923 // Calculate the region to be painted.
4924 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4925 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4926 toBePainted &= extra->mask;
4930 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4931 QWidget::RenderFlags renderFlags)
4934 Q_ASSERT(!toBePainted.isEmpty());
4938 const QTransform originalTransform = painter->worldTransform();
4939 const bool useDeviceCoordinates = originalTransform.isScaling();
4940 if (!useDeviceCoordinates) {
4942 // Render via a pixmap.
4943 const QRect rect = toBePainted.boundingRect();
4944 const QSize size = rect.size();
4948 QPixmap pixmap(size);
4949 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4950 pixmap.fill(Qt::transparent);
4951 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4953 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4954 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4956 painter->drawPixmap(targetOffset, pixmap);
4959 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4963 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4964 QTransform transform = originalTransform;
4965 transform.translate(targetOffset.x(), targetOffset.y());
4967 QPaintDevice *device = painter->device();
4970 // Calculate device rect.
4971 const QRectF rect(toBePainted.boundingRect());
4972 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4973 deviceRect &= QRect(0, 0, device->width(), device->height());
4975 QPixmap pixmap(deviceRect.size());
4976 pixmap.fill(Qt::transparent);
4978 // Create a pixmap device coordinate painter.
4979 QPainter pixmapPainter(&pixmap);
4980 pixmapPainter.setRenderHints(painter->renderHints());
4981 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4982 pixmapPainter.setTransform(transform);
4984 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4985 pixmapPainter.end();
4987 // And then draw the pixmap.
4988 painter->setTransform(QTransform());
4989 painter->drawPixmap(deviceRect.topLeft(), pixmap);
4990 painter->setTransform(originalTransform);
4995 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
4996 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5002 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5003 dirtyOnWidget = QRegion();
5005 // We disable the rendering of QToolBar in the backingStore if
5006 // it's supposed to be in the unified toolbar on Mac OS X.
5007 if (backingStore && isInUnifiedToolbar)
5013 #ifndef QT_NO_GRAPHICSEFFECT
5014 if (graphicsEffect && graphicsEffect->isEnabled()) {
5015 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5016 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5018 if (!sourced->context) {
5019 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5020 sourced->context = &context;
5021 if (!sharedPainter) {
5022 QPaintEngine *paintEngine = pdev->paintEngine();
5023 paintEngine->d_func()->systemClip = rgn.translated(offset);
5025 p.translate(offset);
5026 context.painter = &p;
5027 graphicsEffect->draw(&p);
5028 paintEngine->d_func()->systemClip = QRegion();
5030 context.painter = sharedPainter;
5031 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5032 sourced->invalidateCache();
5033 sourced->lastEffectTransform = sharedPainter->worldTransform();
5035 sharedPainter->save();
5036 sharedPainter->translate(offset);
5037 graphicsEffect->draw(sharedPainter);
5038 sharedPainter->restore();
5040 sourced->context = 0;
5044 #endif //QT_NO_GRAFFICSEFFECT
5046 const bool asRoot = flags & DrawAsRoot;
5047 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5048 const bool recursive = flags & DrawRecursive;
5049 const bool alsoInvisible = flags & DrawInvisible;
5051 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5053 QRegion toBePainted(rgn);
5054 if (asRoot && !alsoInvisible)
5055 toBePainted &= clipRect(); //(rgn & visibleRegion());
5056 if (!(flags & DontSubtractOpaqueChildren))
5057 subtractOpaqueChildren(toBePainted, q->rect());
5059 if (!toBePainted.isEmpty()) {
5060 bool onScreen = paintOnScreen();
5061 if (!onScreen || alsoOnScreen) {
5062 //update the "in paint event" flag
5063 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5064 qWarning("QWidget::repaint: Recursive repaint detected");
5065 q->setAttribute(Qt::WA_WState_InPaintEvent);
5067 //clip away the new area
5068 #ifndef QT_NO_PAINT_DEBUG
5069 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5071 QPaintEngine *paintEngine = pdev->paintEngine();
5073 setRedirected(pdev, -offset);
5076 // (Alien support) Special case for Mac when redirecting: If the paint device
5077 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5078 // outside the paint event is not supported on QWidgets. The attributeis
5079 // restored further down.
5080 if (pdev->devType() == QInternal::Widget)
5081 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5085 paintEngine->d_func()->systemClip = toBePainted;
5087 paintEngine->d_func()->systemRect = q->data->crect;
5089 //paint the background
5090 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5091 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5093 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5097 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5099 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5101 QColor tint = q->palette().window().color();
5102 tint.setAlphaF(qreal(.6));
5103 p.fillRect(toBePainted.boundingRect(), tint);
5108 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5109 qDebug() << "clipping to" << toBePainted << "location == " << offset
5110 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5113 //actually send the paint event
5114 QPaintEvent e(toBePainted);
5115 QCoreApplication::sendSpontaneousEvent(q, &e);
5120 if (pdev->devType() == QInternal::Widget)
5121 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5123 restoreRedirected();
5125 paintEngine->d_func()->systemRect = QRect();
5127 paintEngine->d_func()->currentClipDevice = 0;
5128 paintEngine->d_func()->systemClip = QRegion();
5130 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5131 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5132 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5134 if (paintEngine && paintEngine->autoDestruct()) {
5138 #ifndef QT_NO_PAINT_DEBUG
5140 QWidgetBackingStore::unflushPaint(q, toBePainted);
5142 } else if (q->isWindow()) {
5143 QPaintEngine *engine = pdev->paintEngine();
5146 p.setClipRegion(toBePainted);
5147 const QBrush bg = q->palette().brush(QPalette::Window);
5148 if (bg.style() == Qt::TexturePattern)
5149 p.drawTiledPixmap(q->rect(), bg.texture());
5151 p.fillRect(q->rect(), bg);
5153 if (engine->autoDestruct())
5159 if (recursive && !children.isEmpty()) {
5160 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5161 , sharedPainter, backingStore);
5165 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5166 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5170 qWarning("QWidget::render: null pointer to paint device");
5174 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5175 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5176 ? prepareToRender(sourceRegion, renderFlags)
5178 if (paintRegion.isEmpty())
5182 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5184 // Use the target's shared painter if set (typically set when doing
5185 // "other->render(widget);" in the widget's paintEvent.
5186 if (target->devType() == QInternal::Widget) {
5187 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5188 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5189 QPainter *targetPainter = targetPrivate->sharedPainter();
5190 if (targetPainter && targetPainter->isActive())
5191 setSharedPainter(targetPainter);
5196 // Use the target's redirected device if set and adjust offset and paint
5197 // region accordingly. This is typically the case when people call render
5198 // from the paintEvent.
5199 QPoint offset = targetOffset;
5200 offset -= paintRegion.boundingRect().topLeft();
5201 QPoint redirectionOffset;
5202 QPaintDevice *redirected = 0;
5204 if (target->devType() == QInternal::Widget)
5205 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5207 redirected = QPainter::redirected(target, &redirectionOffset);
5210 target = redirected;
5211 offset -= redirectionOffset;
5214 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5215 if (QPaintEngine *targetEngine = target->paintEngine()) {
5216 const QRegion targetSystemClip = targetEngine->systemClip();
5217 if (!targetSystemClip.isEmpty())
5218 paintRegion &= targetSystemClip.translated(-offset);
5222 // Set backingstore flags.
5223 int flags = DrawPaintOnScreen | DrawInvisible;
5224 if (renderFlags & QWidget::DrawWindowBackground)
5225 flags |= DrawAsRoot;
5227 if (renderFlags & QWidget::DrawChildren)
5228 flags |= DrawRecursive;
5230 flags |= DontSubtractOpaqueChildren;
5232 if (target->devType() == QInternal::Printer) {
5234 render_helper(&p, targetOffset, paintRegion, renderFlags);
5239 // Render via backingstore.
5240 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5242 // Restore shared painter.
5243 if (oldSharedPainter)
5244 setSharedPainter(oldSharedPainter);
5246 // Render via backingstore (no shared painter).
5247 drawWidget(target, paintRegion, offset, flags, 0);
5251 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5252 const QPoint &offset, int flags
5253 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5257 bool dirtyBoundingRect = true;
5258 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5259 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5262 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5263 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5264 && !(excludeNativeChildren && x->internalWinId())) {
5265 if (dirtyBoundingRect) {
5266 boundingRect = rgn.boundingRect();
5267 dirtyBoundingRect = false;
5270 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5276 } while (index >= 0);
5281 QWidgetPrivate *wd = w->d_func();
5282 const QPoint widgetPos(w->data->crect.topLeft());
5283 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5287 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5288 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5289 , sharedPainter, backingStore);
5292 if (w->updatesEnabled()
5293 #ifndef QT_NO_GRAPHICSVIEW
5294 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5295 #endif //QT_NO_GRAPHICSVIEW
5297 QRegion wRegion(rgn);
5298 wRegion &= wd->effectiveRectFor(w->data->crect);
5299 wRegion.translate(-widgetPos);
5301 wRegion &= wd->extra->mask;
5302 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5306 #ifndef QT_NO_GRAPHICSEFFECT
5307 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5309 if (system != Qt::DeviceCoordinates)
5310 return m_widget->rect();
5313 // Device coordinates without context not yet supported.
5314 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5318 return context->painter->worldTransform().mapRect(m_widget->rect());
5321 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5323 if (!context || context->painter != painter) {
5324 m_widget->render(painter);
5328 // The region saved in the context is neither clipped to the rect
5329 // nor the mask, so we have to clip it here before calling drawWidget.
5330 QRegion toBePainted = context->rgn;
5331 toBePainted &= m_widget->rect();
5332 QWidgetPrivate *wd = qt_widget_private(m_widget);
5333 if (wd->extra && wd->extra->hasMask)
5334 toBePainted &= wd->extra->mask;
5336 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5337 context->sharedPainter, context->backingStore);
5340 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5341 QGraphicsEffect::PixmapPadMode mode) const
5343 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5344 if (!context && deviceCoordinates) {
5345 // Device coordinates without context not yet supported.
5346 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5350 QPoint pixmapOffset;
5351 QRectF sourceRect = m_widget->rect();
5353 if (deviceCoordinates) {
5354 const QTransform &painterTransform = context->painter->worldTransform();
5355 sourceRect = painterTransform.mapRect(sourceRect);
5356 pixmapOffset = painterTransform.map(pixmapOffset);
5361 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5362 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5363 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5364 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5366 effectRect = sourceRect.toAlignedRect();
5369 *offset = effectRect.topLeft();
5371 pixmapOffset -= effectRect.topLeft();
5373 QPixmap pixmap(effectRect.size());
5374 pixmap.fill(Qt::transparent);
5375 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5378 #endif //QT_NO_GRAPHICSEFFECT
5380 #ifndef QT_NO_GRAPHICSVIEW
5384 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5385 widget and its ancestors. The search starts at \a origin (inclusive).
5386 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5389 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5392 QWExtra *extra = origin->d_func()->extra;
5393 if (extra && extra->proxyWidget)
5394 return extra->proxyWidget;
5395 return nearestGraphicsProxyWidget(origin->parentWidget());
5402 \property QWidget::locale
5403 \brief the widget's locale
5406 As long as no special locale has been set, this is either
5407 the parent's locale or (if this widget is a top level widget),
5410 If the widget displays dates or numbers, these should be formatted
5411 using the widget's locale.
5413 \sa QLocale QLocale::setDefault()
5416 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5419 if (locale == loc && !forceUpdate)
5424 if (!children.isEmpty()) {
5425 for (int i = 0; i < children.size(); ++i) {
5426 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5429 if (w->testAttribute(Qt::WA_SetLocale))
5431 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5433 w->d_func()->setLocale_helper(loc, forceUpdate);
5436 QEvent e(QEvent::LocaleChange);
5437 QApplication::sendEvent(q, &e);
5440 void QWidget::setLocale(const QLocale &locale)
5444 setAttribute(Qt::WA_SetLocale);
5445 d->setLocale_helper(locale);
5448 QLocale QWidget::locale() const
5455 void QWidgetPrivate::resolveLocale()
5459 if (!q->testAttribute(Qt::WA_SetLocale)) {
5460 setLocale_helper(q->isWindow()
5462 : q->parentWidget()->locale());
5466 void QWidget::unsetLocale()
5469 setAttribute(Qt::WA_SetLocale, false);
5473 static QString constructWindowTitleFromFilePath(const QString &filePath)
5475 QFileInfo fi(filePath);
5476 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5478 QString appName = QApplication::applicationName();
5479 if (!appName.isEmpty())
5480 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5486 \property QWidget::windowTitle
5487 \brief the window title (caption)
5489 This property only makes sense for top-level widgets, such as
5490 windows and dialogs. If no caption has been set, the title is based of the
5491 \l windowFilePath. If neither of these is set, then the title is
5494 If you use the \l windowModified mechanism, the window title must
5495 contain a "[*]" placeholder, which indicates where the '*' should
5496 appear. Normally, it should appear right after the file name
5497 (e.g., "document1.txt[*] - Text Editor"). If the \l
5498 windowModified property is false (the default), the placeholder
5501 \sa windowIcon, windowIconText, windowModified, windowFilePath
5503 QString QWidget::windowTitle() const
5506 if (d->extra && d->extra->topextra) {
5507 if (!d->extra->topextra->caption.isEmpty())
5508 return d->extra->topextra->caption;
5509 if (!d->extra->topextra->filePath.isEmpty())
5510 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5516 Returns a modified window title with the [*] place holder
5517 replaced according to the rules described in QWidget::setWindowTitle
5519 This function assumes that "[*]" can be quoted by another
5520 "[*]", so it will replace two place holders by one and
5521 a single last one by either "*" or nothing depending on
5526 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5531 extern QString qt_eval_adapt_window_title(const QString &title);
5532 QString cap = qt_eval_adapt_window_title(title);
5534 QString cap = title;
5540 QLatin1String placeHolder("[*]");
5541 int placeHolderLength = 3; // QLatin1String doesn't have length()
5543 int index = cap.indexOf(placeHolder);
5545 // here the magic begins
5546 while (index != -1) {
5547 index += placeHolderLength;
5549 while (cap.indexOf(placeHolder, index) == index) {
5551 index += placeHolderLength;
5554 if (count%2) { // odd number of [*] -> replace last one
5555 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5556 if (widget->isWindowModified()
5557 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5558 cap.replace(lastIndex, 3, QWidget::tr("*"));
5560 cap.remove(lastIndex, 3);
5563 index = cap.indexOf(placeHolder, index);
5566 cap.replace(QLatin1String("[*][*]"), placeHolder);
5571 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5574 if (q->testAttribute(Qt::WA_WState_Created))
5575 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5578 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5581 if (q->testAttribute(Qt::WA_WState_Created))
5582 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5585 void QWidget::setWindowIconText(const QString &iconText)
5587 if (QWidget::windowIconText() == iconText)
5591 d->topData()->iconText = iconText;
5592 d->setWindowIconText_helper(iconText);
5594 QEvent e(QEvent::IconTextChange);
5595 QApplication::sendEvent(this, &e);
5598 void QWidget::setWindowTitle(const QString &title)
5600 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5604 d->topData()->caption = title;
5605 d->setWindowTitle_helper(title);
5607 QEvent e(QEvent::WindowTitleChange);
5608 QApplication::sendEvent(this, &e);
5613 \property QWidget::windowIcon
5614 \brief the widget's icon
5616 This property only makes sense for windows. If no icon
5617 has been set, windowIcon() returns the application icon
5618 (QApplication::windowIcon()).
5620 \sa windowIconText, windowTitle
5622 QIcon QWidget::windowIcon() const
5624 const QWidget *w = this;
5626 const QWidgetPrivate *d = w->d_func();
5627 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5628 return *d->extra->topextra->icon;
5629 w = w->parentWidget();
5631 return QApplication::windowIcon();
5634 void QWidgetPrivate::setWindowIcon_helper()
5636 QEvent e(QEvent::WindowIconChange);
5637 QApplication::sendEvent(q_func(), &e);
5638 for (int i = 0; i < children.size(); ++i) {
5639 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5640 if (w && !w->isWindow())
5641 QApplication::sendEvent(w, &e);
5645 void QWidget::setWindowIcon(const QIcon &icon)
5649 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5652 if (!d->extra->topextra->icon)
5653 d->extra->topextra->icon = new QIcon();
5654 *d->extra->topextra->icon = icon;
5656 delete d->extra->topextra->iconPixmap;
5657 d->extra->topextra->iconPixmap = 0;
5659 d->setWindowIcon_sys();
5660 d->setWindowIcon_helper();
5665 \property QWidget::windowIconText
5666 \brief the widget's icon text
5668 This property only makes sense for windows. If no icon
5669 text has been set, this functions returns an empty string.
5671 \sa windowIcon, windowTitle
5674 QString QWidget::windowIconText() const
5677 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5681 \property QWidget::windowFilePath
5683 \brief the file path associated with a widget
5685 This property only makes sense for windows. It associates a file path with
5686 a window. If you set the file path, but have not set the window title, Qt
5687 sets the window title to contain a string created using the following
5693 \li The file name of the specified path, obtained using QFileInfo::fileName().
5699 \li The file name of the specified path, obtained using QFileInfo::fileName().
5700 \li An optional \c{*} character, if the \l windowModified property is set.
5701 \li The \c{0x2014} unicode character, padded either side by spaces.
5702 \li The application name, obtained from the application's
5703 \l{QCoreApplication::}{applicationName} property.
5706 If the window title is set at any point, then the window title takes precedence and
5707 will be shown instead of the file path string.
5709 Additionally, on Mac OS X, this has an added benefit that it sets the
5710 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5711 for the window, assuming that the file path exists.
5713 If no file path is set, this property contains an empty string.
5715 By default, this property contains an empty string.
5717 \sa windowTitle, windowIcon
5720 QString QWidget::windowFilePath() const
5723 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5726 void QWidget::setWindowFilePath(const QString &filePath)
5728 if (filePath == windowFilePath())
5734 d->extra->topextra->filePath = filePath;
5735 d->setWindowFilePath_helper(filePath);
5738 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5740 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5742 setWindowTitle_helper(QFileInfo(filePath).fileName());
5746 setWindowTitle_helper(q->windowTitle());
5750 setWindowFilePath_sys(filePath);
5755 Returns the window's role, or an empty string.
5757 \sa windowIcon, windowTitle
5760 QString QWidget::windowRole() const
5763 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5767 Sets the window's role to \a role. This only makes sense for
5770 void QWidget::setWindowRole(const QString &role)
5772 #if defined(Q_WS_X11)
5774 d->topData()->role = role;
5782 \property QWidget::mouseTracking
5783 \brief whether mouse tracking is enabled for the widget
5785 If mouse tracking is disabled (the default), the widget only
5786 receives mouse move events when at least one mouse button is
5787 pressed while the mouse is being moved.
5789 If mouse tracking is enabled, the widget receives mouse move
5790 events even if no buttons are pressed.
5792 \sa mouseMoveEvent()
5797 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5798 function resets this widget to have no focus proxy.
5800 Some widgets can "have focus", but create a child widget, such as
5801 QLineEdit, to actually handle the focus. In this case, the widget
5802 can set the line edit to be its focus proxy.
5804 setFocusProxy() sets the widget which will actually get focus when
5805 "this widget" gets it. If there is a focus proxy, setFocus() and
5806 hasFocus() operate on the focus proxy.
5811 void QWidget::setFocusProxy(QWidget * w)
5814 if (!w && !d->extra)
5817 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5819 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5825 d->extra->focus_proxy = w;
5830 Returns the focus proxy, or 0 if there is no focus proxy.
5835 QWidget * QWidget::focusProxy() const
5838 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5843 \property QWidget::focus
5844 \brief whether this widget (or its focus proxy) has the keyboard
5847 By default, this property is false.
5849 \note Obtaining the value of this property for a widget is effectively equivalent
5850 to checking whether QApplication::focusWidget() refers to the widget.
5852 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5854 bool QWidget::hasFocus() const
5856 const QWidget* w = this;
5857 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5858 w = w->d_func()->extra->focus_proxy;
5859 if (QWidget *window = w->window()) {
5860 #ifndef QT_NO_GRAPHICSVIEW
5861 QWExtra *e = window->d_func()->extra;
5862 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5866 return (QApplication::focusWidget() == w);
5870 Gives the keyboard input focus to this widget (or its focus
5871 proxy) if this widget or one of its parents is the \link
5872 isActiveWindow() active window\endlink. The \a reason argument will
5873 be passed into any focus event sent from this function, it is used
5874 to give an explanation of what caused the widget to get focus.
5875 If the window is not active, the widget will be given the focus when
5876 the window becomes active.
5878 First, a focus out event is sent to the focus widget (if any) to
5879 tell it that it is about to lose the focus. Then a focus in event
5880 is sent to this widget to tell it that it just received the focus.
5881 (Nothing happens if the focus in and focus out widgets are the
5884 \note On embedded platforms, setFocus() will not cause an input panel
5885 to be opened by the input method. If you want this to happen, you
5886 have to send a QEvent::RequestSoftwareInputPanel event to the
5889 setFocus() gives focus to a widget regardless of its focus policy,
5890 but does not clear any keyboard grab (see grabKeyboard()).
5892 Be aware that if the widget is hidden, it will not accept focus
5895 \warning If you call setFocus() in a function which may itself be
5896 called from focusOutEvent() or focusInEvent(), you may get an
5899 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5900 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5901 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5904 void QWidget::setFocus(Qt::FocusReason reason)
5910 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5911 f = f->d_func()->extra->focus_proxy;
5913 if (QApplication::focusWidget() == f
5914 #if defined(Q_WS_WIN)
5915 && GetFocus() == f->internalWinId()
5920 #ifndef QT_NO_GRAPHICSVIEW
5921 QWidget *previousProxyFocus = 0;
5922 if (QWExtra *topData = window()->d_func()->extra) {
5923 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5924 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5925 if (previousProxyFocus && previousProxyFocus->focusProxy())
5926 previousProxyFocus = previousProxyFocus->focusProxy();
5927 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5935 while (w && w->isHidden()) {
5936 w->d_func()->focus_child = f;
5937 w = w->isWindow() ? 0 : w->parentWidget();
5941 w->d_func()->focus_child = f;
5942 w = w->isWindow() ? 0 : w->parentWidget();
5946 #ifndef QT_NO_GRAPHICSVIEW
5947 // Update proxy state
5948 if (QWExtra *topData = window()->d_func()->extra) {
5949 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5950 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5951 topData->proxyWidget->setFocus(reason);
5952 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5957 if (f->isActiveWindow()) {
5958 QApplicationPrivate::setFocusWidget(f, reason);
5959 #ifndef QT_NO_ACCESSIBILITY
5961 // The negation of the condition in setFocus_sys
5962 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5963 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5966 // menus update the focus manually and this would create bogus events
5967 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5970 QAccessibleEvent event(QAccessible::Focus, f);
5971 QAccessible::updateAccessibility(&event);
5974 #ifndef QT_NO_GRAPHICSVIEW
5975 if (QWExtra *topData = window()->d_func()->extra) {
5976 if (topData->proxyWidget) {
5977 if (previousProxyFocus && previousProxyFocus != f) {
5978 // Send event to self
5979 QFocusEvent event(QEvent::FocusOut, reason);
5980 QPointer<QWidget> that = previousProxyFocus;
5981 QApplication::sendEvent(previousProxyFocus, &event);
5983 QApplication::sendEvent(that->style(), &event);
5986 #ifndef QT_NO_GRAPHICSVIEW
5987 // Update proxy state
5988 if (QWExtra *topData = window()->d_func()->extra)
5989 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
5990 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
5992 // Send event to self
5993 QFocusEvent event(QEvent::FocusIn, reason);
5994 QPointer<QWidget> that = f;
5995 QApplication::sendEvent(f, &event);
5997 QApplication::sendEvent(that->style(), &event);
6006 \fn void QWidget::setFocus()
6009 Gives the keyboard input focus to this widget (or its focus
6010 proxy) if this widget or one of its parents is the
6011 \l{isActiveWindow()}{active window}.
6015 Takes keyboard input focus from the widget.
6017 If the widget has active focus, a \link focusOutEvent() focus out
6018 event\endlink is sent to this widget to tell it that it is about
6021 This widget must enable focus setting in order to get the keyboard
6022 input focus, i.e. it must call setFocusPolicy().
6024 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6025 setFocusPolicy(), QApplication::focusWidget()
6028 void QWidget::clearFocus()
6032 if (w->d_func()->focus_child == this)
6033 w->d_func()->focus_child = 0;
6034 w = w->parentWidget();
6036 #ifndef QT_NO_GRAPHICSVIEW
6037 QWExtra *topData = d_func()->extra;
6038 if (topData && topData->proxyWidget)
6039 topData->proxyWidget->clearFocus();
6043 // Update proxy state
6044 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6045 #if defined(Q_WS_WIN)
6046 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6051 #ifndef QT_NO_ACCESSIBILITY
6052 QAccessibleEvent event(QAccessible::Focus, this);
6053 QAccessible::updateAccessibility(&event);
6061 \fn bool QWidget::focusNextChild()
6063 Finds a new widget to give the keyboard focus to, as appropriate
6064 for \key Tab, and returns true if it can find a new widget, or
6067 \sa focusPreviousChild()
6071 \fn bool QWidget::focusPreviousChild()
6073 Finds a new widget to give the keyboard focus to, as appropriate
6074 for \key Shift+Tab, and returns true if it can find a new widget,
6075 or false if it can't.
6077 \sa focusNextChild()
6081 Finds a new widget to give the keyboard focus to, as appropriate
6082 for Tab and Shift+Tab, and returns true if it can find a new
6083 widget, or false if it can't.
6085 If \a next is true, this function searches forward, if \a next
6086 is false, it searches backward.
6088 Sometimes, you will want to reimplement this function. For
6089 example, a web browser might reimplement it to move its "current
6090 active link" forward or backward, and call
6091 focusNextPrevChild() only when it reaches the last or
6092 first link on the "page".
6094 Child widgets call focusNextPrevChild() on their parent widgets,
6095 but only the window that contains the child widgets decides where
6096 to redirect focus. By reimplementing this function for an object,
6097 you thus gain control of focus traversal for all child widgets.
6099 \sa focusNextChild(), focusPreviousChild()
6102 bool QWidget::focusNextPrevChild(bool next)
6105 QWidget* p = parentWidget();
6106 bool isSubWindow = (windowType() == Qt::SubWindow);
6107 if (!isWindow() && !isSubWindow && p)
6108 return p->focusNextPrevChild(next);
6109 #ifndef QT_NO_GRAPHICSVIEW
6110 if (d->extra && d->extra->proxyWidget)
6111 return d->extra->proxyWidget->focusNextPrevChild(next);
6113 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6114 if (!w) return false;
6116 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6121 Returns the last child of this widget that setFocus had been
6122 called on. For top level widgets this is the widget that will get
6123 focus in case this window gets activated
6125 This is not the same as QApplication::focusWidget(), which returns
6126 the focus widget in the currently active window.
6129 QWidget *QWidget::focusWidget() const
6131 return const_cast<QWidget *>(d_func()->focus_child);
6135 Returns the next widget in this widget's focus chain.
6137 \sa previousInFocusChain()
6139 QWidget *QWidget::nextInFocusChain() const
6141 return const_cast<QWidget *>(d_func()->focus_next);
6145 \brief The previousInFocusChain function returns the previous
6146 widget in this widget's focus chain.
6148 \sa nextInFocusChain()
6152 QWidget *QWidget::previousInFocusChain() const
6154 return const_cast<QWidget *>(d_func()->focus_prev);
6158 \property QWidget::isActiveWindow
6159 \brief whether this widget's window is the active window
6161 The active window is the window that contains the widget that has
6162 keyboard focus (The window may still have focus if it has no
6163 widgets or none of its widgets accepts keyboard focus).
6165 When popup windows are visible, this property is true for both the
6166 active window \e and for the popup.
6168 By default, this property is false.
6170 \sa activateWindow(), QApplication::activeWindow()
6172 bool QWidget::isActiveWindow() const
6174 QWidget *tlw = window();
6175 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6178 #ifndef QT_NO_GRAPHICSVIEW
6179 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6180 if (isVisible() && tlwExtra->proxyWidget)
6181 return tlwExtra->proxyWidget->isActiveWindow();
6186 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6187 if(qt_mac_is_macdrawer(tlw) &&
6188 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6191 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6192 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6195 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6196 if(tlw->windowType() == Qt::Tool &&
6198 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6200 QWidget *w = QApplication::activeWindow();
6201 while(w && tlw->windowType() == Qt::Tool &&
6202 !w->isModal() && w->parentWidget()) {
6203 w = w->parentWidget()->window();
6208 #if defined(Q_WS_WIN32)
6209 HWND active = GetActiveWindow();
6210 if (!tlw->testAttribute(Qt::WA_WState_Created))
6212 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6219 Puts the \a second widget after the \a first widget in the focus order.
6221 Note that since the tab order of the \a second widget is changed, you
6222 should order a chain like this:
6224 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6228 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6230 If \a first or \a second has a focus proxy, setTabOrder()
6231 correctly substitutes the proxy.
6233 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6235 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6237 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6240 if (first->window() != second->window()) {
6241 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6245 QWidget *fp = first->focusProxy();
6247 // If first is redirected, set first to the last child of first
6248 // that can take keyboard focus so that second is inserted after
6249 // that last child, and the focus order within first is (more
6250 // likely to be) preserved.
6251 QList<QWidget *> l = first->findChildren<QWidget *>();
6252 for (int i = l.size()-1; i >= 0; --i) {
6253 QWidget * next = l.at(i);
6254 if (next->window() == fp->window()) {
6256 if (fp->focusPolicy() != Qt::NoFocus)
6266 if (QWidget *sp = second->focusProxy())
6269 // QWidget *fp = first->d_func()->focus_prev;
6270 QWidget *fn = first->d_func()->focus_next;
6272 if (fn == second || first == second)
6275 QWidget *sp = second->d_func()->focus_prev;
6276 QWidget *sn = second->d_func()->focus_next;
6278 fn->d_func()->focus_prev = second;
6279 first->d_func()->focus_next = second;
6281 second->d_func()->focus_next = fn;
6282 second->d_func()->focus_prev = first;
6284 sp->d_func()->focus_next = sn;
6285 sn->d_func()->focus_prev = sp;
6288 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6289 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6291 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6292 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6297 Moves the relevant subwidgets of this widget from the \a oldtlw's
6298 tab chain to that of the new parent, if there's anything to move and
6301 This function is called from QWidget::reparent() *after* the widget
6302 has been reparented.
6307 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6310 if (oldtlw == q->window())
6311 return; // nothing to do
6314 focus_child->clearFocus();
6316 // separate the focus chain into new (children of myself) and old (the rest)
6317 QWidget *firstOld = 0;
6318 //QWidget *firstNew = q; //invariant
6319 QWidget *o = 0; // last in the old list
6320 QWidget *n = q; // last in the new list
6322 bool prevWasNew = true;
6323 QWidget *w = focus_next;
6325 //Note: for efficiency, we do not maintain the list invariant inside the loop
6326 //we append items to the relevant list, and we optimize by not changing pointers
6327 //when subsequent items are going into the same list.
6329 bool currentIsNew = q->isAncestorOf(w);
6332 //prev was old -- append to new list
6333 n->d_func()->focus_next = w;
6334 w->d_func()->focus_prev = n;
6339 //prev was new -- append to old list, if there is one
6341 o->d_func()->focus_next = w;
6342 w->d_func()->focus_prev = o;
6344 // "create" the old list
6350 w = w->d_func()->focus_next;
6351 prevWasNew = currentIsNew;
6354 //repair the old list:
6356 o->d_func()->focus_next = firstOld;
6357 firstOld->d_func()->focus_prev = o;
6360 if (!q->isWindow()) {
6361 QWidget *topLevel = q->window();
6362 //insert new chain into toplevel's chain
6364 QWidget *prev = topLevel->d_func()->focus_prev;
6366 topLevel->d_func()->focus_prev = n;
6367 prev->d_func()->focus_next = q;
6370 n->d_func()->focus_next = topLevel;
6372 //repair the new list
6373 n->d_func()->focus_next = q;
6381 Measures the shortest distance from a point to a rect.
6383 This function is called from QDesktopwidget::screen(QPoint) to find the
6384 closest screen for a point.
6385 In directional KeypadNavigation, it is called to find the closest
6386 widget to the current focus widget center.
6388 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6392 if (p.x() < r.left())
6393 dx = r.left() - p.x();
6394 else if (p.x() > r.right())
6395 dx = p.x() - r.right();
6396 if (p.y() < r.top())
6397 dy = r.top() - p.y();
6398 else if (p.y() > r.bottom())
6399 dy = p.y() - r.bottom();
6404 \property QWidget::frameSize
6405 \brief the size of the widget including any window frame
6407 By default, this property contains a value that depends on the user's
6408 platform and screen geometry.
6410 QSize QWidget::frameSize() const
6413 if (isWindow() && !(windowType() == Qt::Popup)) {
6414 QRect fs = d->frameStrut();
6415 return QSize(data->crect.width() + fs.left() + fs.right(),
6416 data->crect.height() + fs.top() + fs.bottom());
6418 return data->crect.size();
6421 /*! \fn void QWidget::move(int x, int y)
6425 This corresponds to move(QPoint(\a x, \a y)).
6428 void QWidget::move(const QPoint &p)
6431 setAttribute(Qt::WA_Moved);
6433 d->topData()->posFromMove = true;
6434 if (testAttribute(Qt::WA_WState_Created)) {
6435 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6436 p.y() + geometry().y() - QWidget::y(),
6437 width(), height(), true);
6438 d->setDirtyOpaqueRegion();
6440 data->crect.moveTopLeft(p); // no frame yet
6441 setAttribute(Qt::WA_PendingMoveEvent);
6445 /*! \fn void QWidget::resize(int w, int h)
6448 This corresponds to resize(QSize(\a w, \a h)).
6451 void QWidget::resize(const QSize &s)
6454 setAttribute(Qt::WA_Resized);
6455 if (testAttribute(Qt::WA_WState_Created)) {
6456 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6457 d->setDirtyOpaqueRegion();
6459 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6460 setAttribute(Qt::WA_PendingResizeEvent);
6464 void QWidget::setGeometry(const QRect &r)
6467 setAttribute(Qt::WA_Resized);
6468 setAttribute(Qt::WA_Moved);
6470 d->topData()->posFromMove = false;
6471 if (testAttribute(Qt::WA_WState_Created)) {
6472 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6473 d->setDirtyOpaqueRegion();
6475 data->crect.setTopLeft(r.topLeft());
6476 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6477 setAttribute(Qt::WA_PendingMoveEvent);
6478 setAttribute(Qt::WA_PendingResizeEvent);
6484 Saves the current geometry and state for top-level widgets.
6486 To save the geometry when the window closes, you can
6487 implement a close event like this:
6489 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6491 See the \l{Window Geometry} documentation for an overview of geometry
6492 issues with windows.
6494 Use QMainWindow::saveState() to save the geometry and the state of
6495 toolbars and dock widgets.
6497 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6499 QByteArray QWidget::saveGeometry() const
6502 // We check if the window was maximized during this invocation. If so, we need to record the
6503 // starting position as 0,0.
6505 QRect newFramePosition = frameGeometry();
6506 QRect newNormalPosition = normalGeometry();
6507 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6508 // Change the starting position
6509 newFramePosition.moveTo(0, 0);
6510 newNormalPosition.moveTo(0, 0);
6514 QDataStream stream(&array, QIODevice::WriteOnly);
6515 stream.setVersion(QDataStream::Qt_4_0);
6516 const quint32 magicNumber = 0x1D9D0CB;
6517 quint16 majorVersion = 1;
6518 quint16 minorVersion = 0;
6519 stream << magicNumber
6524 << newNormalPosition
6529 << qint32(QApplication::desktop()->screenNumber(this))
6530 << quint8(windowState() & Qt::WindowMaximized)
6531 << quint8(windowState() & Qt::WindowFullScreen);
6538 Restores the geometry and state top-level widgets stored in the
6539 byte array \a geometry. Returns true on success; otherwise
6542 If the restored geometry is off-screen, it will be modified to be
6543 inside the available screen geometry.
6545 To restore geometry saved using QSettings, you can use code like
6548 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6550 See the \l{Window Geometry} documentation for an overview of geometry
6551 issues with windows.
6553 Use QMainWindow::restoreState() to restore the geometry and the
6554 state of toolbars and dock widgets.
6556 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6558 bool QWidget::restoreGeometry(const QByteArray &geometry)
6560 if (geometry.size() < 4)
6562 QDataStream stream(geometry);
6563 stream.setVersion(QDataStream::Qt_4_0);
6565 const quint32 magicNumber = 0x1D9D0CB;
6566 quint32 storedMagicNumber;
6567 stream >> storedMagicNumber;
6568 if (storedMagicNumber != magicNumber)
6571 const quint16 currentMajorVersion = 1;
6572 quint16 majorVersion = 0;
6573 quint16 minorVersion = 0;
6575 stream >> majorVersion >> minorVersion;
6577 if (majorVersion != currentMajorVersion)
6579 // (Allow all minor versions.)
6581 QRect restoredFrameGeometry;
6582 QRect restoredNormalGeometry;
6583 qint32 restoredScreenNumber;
6587 stream >> restoredFrameGeometry
6588 >> restoredNormalGeometry
6589 >> restoredScreenNumber
6593 const int frameHeight = 20;
6594 if (!restoredFrameGeometry.isValid())
6595 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6597 if (!restoredNormalGeometry.isValid())
6598 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6599 if (!restoredNormalGeometry.isValid()) {
6600 // use the widget's adjustedSize if the sizeHint() doesn't help
6601 restoredNormalGeometry.setSize(restoredNormalGeometry
6603 .expandedTo(d_func()->adjustedSize()));
6606 const QDesktopWidget * const desktop = QApplication::desktop();
6607 if (restoredScreenNumber >= desktop->numScreens())
6608 restoredScreenNumber = desktop->primaryScreen();
6610 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6612 // Modify the restored geometry if we are about to restore to coordinates
6613 // that would make the window "lost". This happens if:
6614 // - The restored geometry is completely oustside the available geometry
6615 // - The title bar is outside the available geometry.
6616 // - (Mac only) The window is higher than the available geometry. It must
6617 // be possible to bring the size grip on screen by moving the window.
6619 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6620 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6623 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6624 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6625 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6626 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6628 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6630 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6631 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6632 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6633 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6635 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6637 if (maximized || fullScreen) {
6638 // set geomerty before setting the window state to make
6639 // sure the window is maximized to the right screen.
6640 // Skip on windows: the window is restored into a broken
6641 // half-maximized state.
6643 setGeometry(restoredNormalGeometry);
6645 Qt::WindowStates ws = windowState();
6647 ws |= Qt::WindowMaximized;
6649 ws |= Qt::WindowFullScreen;
6651 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6656 offset = d_func()->topData()->fullScreenOffset;
6658 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6659 move(restoredFrameGeometry.topLeft() + offset);
6660 resize(restoredNormalGeometry.size());
6665 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6668 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6672 Sets the margins around the contents of the widget to have the sizes
6673 \a left, \a top, \a right, and \a bottom. The margins are used by
6674 the layout system, and may be used by subclasses to specify the area
6675 to draw in (e.g. excluding the frame).
6677 Changing the margins will trigger a resizeEvent().
6679 \sa contentsRect(), getContentsMargins()
6681 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6684 if (left == d->leftmargin && top == d->topmargin
6685 && right == d->rightmargin && bottom == d->bottommargin)
6687 d->leftmargin = left;
6689 d->rightmargin = right;
6690 d->bottommargin = bottom;
6692 if (QLayout *l=d->layout)
6693 l->update(); //force activate; will do updateGeometry
6697 // ### Qt 5: compat, remove
6700 QResizeEvent e(data->crect.size(), data->crect.size());
6701 QApplication::sendEvent(this, &e);
6703 setAttribute(Qt::WA_PendingResizeEvent, true);
6706 QEvent e(QEvent::ContentsRectChange);
6707 QApplication::sendEvent(this, &e);
6714 \brief The setContentsMargins function sets the margins around the
6717 Sets the margins around the contents of the widget to have the
6718 sizes determined by \a margins. The margins are
6719 used by the layout system, and may be used by subclasses to
6720 specify the area to draw in (e.g. excluding the frame).
6722 Changing the margins will trigger a resizeEvent().
6724 \sa contentsRect(), getContentsMargins()
6726 void QWidget::setContentsMargins(const QMargins &margins)
6728 setContentsMargins(margins.left(), margins.top(),
6729 margins.right(), margins.bottom());
6733 Returns the widget's contents margins for \a left, \a top, \a
6734 right, and \a bottom.
6736 \sa setContentsMargins(), contentsRect()
6738 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6742 *left = d->leftmargin;
6744 *top = d->topmargin;
6746 *right = d->rightmargin;
6748 *bottom = d->bottommargin;
6754 \brief The contentsMargins function returns the widget's contents margins.
6756 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6758 QMargins QWidget::contentsMargins() const
6761 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6766 Returns the area inside the widget's margins.
6768 \sa setContentsMargins(), getContentsMargins()
6770 QRect QWidget::contentsRect() const
6773 return QRect(QPoint(d->leftmargin, d->topmargin),
6774 QPoint(data->crect.width() - 1 - d->rightmargin,
6775 data->crect.height() - 1 - d->bottommargin));
6782 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6784 This signal is emitted when the widget's \l contextMenuPolicy is
6785 Qt::CustomContextMenu, and the user has requested a context menu on
6786 the widget. The position \a pos is the position of the context menu
6787 event that the widget receives. Normally this is in widget
6788 coordinates. The exception to this rule is QAbstractScrollArea and
6789 its subclasses that map the context menu event to coordinates of the
6790 \link QAbstractScrollArea::viewport() viewport() \endlink .
6793 \sa mapToGlobal() QMenu contextMenuPolicy
6798 \property QWidget::contextMenuPolicy
6799 \brief how the widget shows a context menu
6801 The default value of this property is Qt::DefaultContextMenu,
6802 which means the contextMenuEvent() handler is called. Other values
6803 are Qt::NoContextMenu, Qt::PreventContextMenu,
6804 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6805 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6808 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6811 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6813 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6816 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6818 data->context_menu_policy = (uint) policy;
6822 \property QWidget::focusPolicy
6823 \brief the way the widget accepts keyboard focus
6825 The policy is Qt::TabFocus if the widget accepts keyboard
6826 focus by tabbing, Qt::ClickFocus if the widget accepts
6827 focus by clicking, Qt::StrongFocus if it accepts both, and
6828 Qt::NoFocus (the default) if it does not accept focus at
6831 You must enable keyboard focus for a widget if it processes
6832 keyboard events. This is normally done from the widget's
6833 constructor. For instance, the QLineEdit constructor calls
6834 setFocusPolicy(Qt::StrongFocus).
6836 If the widget has a focus proxy, then the focus policy will
6837 be propagated to it.
6839 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6843 Qt::FocusPolicy QWidget::focusPolicy() const
6845 return (Qt::FocusPolicy)data->focus_policy;
6848 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6850 data->focus_policy = (uint) policy;
6852 if (d->extra && d->extra->focus_proxy)
6853 d->extra->focus_proxy->setFocusPolicy(policy);
6857 \property QWidget::updatesEnabled
6858 \brief whether updates are enabled
6860 An updates enabled widget receives paint events and has a system
6861 background; a disabled widget does not. This also implies that
6862 calling update() and repaint() has no effect if updates are
6865 By default, this property is true.
6867 setUpdatesEnabled() is normally used to disable updates for a
6868 short period of time, for instance to avoid screen flicker during
6869 large changes. In Qt, widgets normally do not generate screen
6870 flicker, but on X11 the server might erase regions on the screen
6871 when widgets get hidden before they can be replaced by other
6872 widgets. Disabling updates solves this.
6875 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6877 Disabling a widget implicitly disables all its children. Enabling a widget
6878 enables all child widgets \e except top-level widgets or those that
6879 have been explicitly disabled. Re-enabling updates implicitly calls
6880 update() on the widget.
6884 void QWidget::setUpdatesEnabled(bool enable)
6887 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6888 d->setUpdatesEnabled_helper(enable);
6891 /*! \fn void QWidget::show()
6893 Shows the widget and its child widgets. This function is
6894 equivalent to setVisible(true).
6896 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6897 showNormal(), isVisible()
6903 Makes the widget visible in the isVisible() meaning of the word.
6904 It is only called for toplevels or widgets with visible parents.
6906 void QWidgetPrivate::show_recursive()
6909 // polish if necessary
6911 if (!q->testAttribute(Qt::WA_WState_Created))
6912 createRecursively();
6913 q->ensurePolished();
6915 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6916 q->parentWidget()->d_func()->layout->activate();
6917 // activate our layout before we and our children become visible
6924 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6928 disableUpdates = disableUpdates && q->updatesEnabled();
6930 q->setAttribute(Qt::WA_UpdatesDisabled);
6932 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6933 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6934 QApplication::sendEvent(q, &e);
6935 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6938 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6939 QResizeEvent e(data.crect.size(), QSize());
6940 QApplication::sendEvent(q, &e);
6941 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6945 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6950 for (int i = 0; i < children.size(); ++i) {
6951 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6952 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6956 void QWidgetPrivate::activateChildLayoutsRecursively()
6958 sendPendingMoveAndResizeEvents(false, true);
6960 for (int i = 0; i < children.size(); ++i) {
6961 QWidget *child = qobject_cast<QWidget *>(children.at(i));
6962 if (!child || child->isHidden() || child->isWindow())
6965 child->ensurePolished();
6967 // Activate child's layout
6968 QWidgetPrivate *childPrivate = child->d_func();
6969 if (childPrivate->layout)
6970 childPrivate->layout->activate();
6972 // Pretend we're visible.
6973 const bool wasVisible = child->isVisible();
6975 child->setAttribute(Qt::WA_WState_Visible);
6977 // Do the same for all my children.
6978 childPrivate->activateChildLayoutsRecursively();
6980 // We're not cheating anymore.
6982 child->setAttribute(Qt::WA_WState_Visible, false);
6986 void QWidgetPrivate::show_helper()
6989 data.in_show = true; // qws optimization
6990 // make sure we receive pending move and resize events
6991 sendPendingMoveAndResizeEvents();
6993 // become visible before showing all children
6994 q->setAttribute(Qt::WA_WState_Visible);
6996 // finally show all children recursively
6997 showChildren(false);
7001 // popup handling: new popups and tools need to be raised, and
7002 // existing popups must be closed. Also propagate the current
7003 // windows's KeyboardFocusChange status.
7004 if (q->isWindow()) {
7005 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7007 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7008 q->setAttribute(Qt::WA_KeyboardFocusChange);
7010 while (QApplication::activePopupWidget()) {
7011 if (!QApplication::activePopupWidget()->close())
7017 // Automatic embedding of child windows of widgets already embedded into
7018 // QGraphicsProxyWidget when they are shown the first time.
7019 bool isEmbedded = false;
7020 #ifndef QT_NO_GRAPHICSVIEW
7021 if (q->isWindow()) {
7022 isEmbedded = q->graphicsProxyWidget() ? true : false;
7023 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7024 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7025 if (ancestorProxy) {
7027 ancestorProxy->d_func()->embedSubWindow(q);
7032 Q_UNUSED(isEmbedded);
7035 // On Windows, show the popup now so that our own focus handling
7036 // stores the correct old focus widget even if it's stolen in the
7038 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7039 if (!isEmbedded && q->windowType() == Qt::Popup)
7040 qApp->d_func()->openPopup(q);
7043 // send the show event before showing the window
7044 QShowEvent showEvent;
7045 QApplication::sendEvent(q, &showEvent);
7047 if (!isEmbedded && q->isModal() && q->isWindow())
7048 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7049 // stacking might be wrong
7050 QApplicationPrivate::enterModal(q);
7055 if (!isEmbedded && q->windowType() == Qt::Popup)
7056 qApp->d_func()->openPopup(q);
7058 #ifndef QT_NO_ACCESSIBILITY
7059 if (q->windowType() != Qt::ToolTip) { // Tooltips are read aloud twice in MS narrator.
7060 QAccessibleEvent event(QAccessible::ObjectShow, q);
7061 QAccessible::updateAccessibility(&event);
7065 if (QApplicationPrivate::hidden_focus_widget == q) {
7066 QApplicationPrivate::hidden_focus_widget = 0;
7067 q->setFocus(Qt::OtherFocusReason);
7070 // Process events when showing a Qt::SplashScreen widget before the event loop
7071 // is spinnning; otherwise it might not show up on particular platforms.
7072 // This makes QSplashScreen behave the same on all platforms.
7073 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7074 QApplication::processEvents();
7076 data.in_show = false; // reset qws optimization
7079 /*! \fn void QWidget::hide()
7081 Hides the widget. This function is equivalent to
7085 \note If you are working with QDialog or its subclasses and you invoke
7086 the show() function after this function, the dialog will be displayed in
7087 its original position.
7089 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7094 void QWidgetPrivate::hide_helper()
7098 bool isEmbedded = false;
7099 #if !defined QT_NO_GRAPHICSVIEW
7100 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7102 Q_UNUSED(isEmbedded);
7105 if (!isEmbedded && (q->windowType() == Qt::Popup))
7106 qApp->d_func()->closePopup(q);
7108 // Move test modal here. Otherwise, a modal dialog could get
7109 // destroyed and we lose all access to its parent because we haven't
7110 // left modality. (Eg. modal Progress Dialog)
7111 if (!isEmbedded && q->isModal() && q->isWindow())
7112 QApplicationPrivate::leaveModal(q);
7114 #if defined(Q_WS_WIN)
7115 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7116 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7117 q->parentWidget()->activateWindow(); // Activate parent
7120 q->setAttribute(Qt::WA_Mapped, false);
7123 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7126 q->setAttribute(Qt::WA_WState_Visible, false);
7130 QHideEvent hideEvent;
7131 QApplication::sendEvent(q, &hideEvent);
7132 hideChildren(false);
7134 // next bit tries to move the focus if the focus widget is now
7137 qApp->d_func()->sendSyntheticEnterLeave(q);
7138 QWidget *fw = QApplication::focusWidget();
7139 while (fw && !fw->isWindow()) {
7141 q->focusNextPrevChild(true);
7144 fw = fw->parentWidget();
7148 if (QWidgetBackingStore *bs = maybeBackingStore())
7149 bs->removeDirtyWidget(q);
7151 #ifndef QT_NO_ACCESSIBILITY
7153 QAccessibleEvent event(QAccessible::ObjectHide, q);
7154 QAccessible::updateAccessibility(&event);
7160 \fn bool QWidget::isHidden() const
7162 Returns true if the widget is hidden, otherwise returns false.
7164 A hidden widget will only become visible when show() is called on
7165 it. It will not be automatically shown when the parent is shown.
7167 To check visibility, use !isVisible() instead (notice the exclamation mark).
7169 isHidden() implies !isVisible(), but a widget can be not visible
7170 and not hidden at the same time. This is the case for widgets that are children of
7171 widgets that are not visible.
7174 Widgets are hidden if:
7176 \li they were created as independent windows,
7177 \li they were created as children of visible widgets,
7178 \li hide() or setVisible(false) was called.
7183 void QWidget::setVisible(bool visible)
7185 if (visible) { // show
7186 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7191 // Designer uses a trick to make grabWidget work without showing
7192 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7193 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7194 parentWidget()->window()->d_func()->createRecursively();
7196 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7197 //but not children of non-visible parents
7198 QWidget *pw = parentWidget();
7199 if (!testAttribute(Qt::WA_WState_Created)
7200 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7204 #if defined(Q_WS_X11)
7205 if (windowType() == Qt::Window)
7206 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7209 bool wasResized = testAttribute(Qt::WA_Resized);
7210 Qt::WindowStates initialWindowState = windowState();
7212 // polish if necessary
7215 // remember that show was called explicitly
7216 setAttribute(Qt::WA_WState_ExplicitShowHide);
7217 // whether we need to inform the parent widget immediately
7218 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7219 // we are no longer hidden
7220 setAttribute(Qt::WA_WState_Hidden, false);
7222 if (needUpdateGeometry)
7223 d->updateGeometry_helper(true);
7225 // activate our layout before we and our children become visible
7227 d->layout->activate();
7230 QWidget *parent = parentWidget();
7231 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7232 parent->d_func()->layout->activate();
7233 if (parent->isWindow())
7235 parent = parent->parentWidget();
7238 parent->d_func()->setDirtyOpaqueRegion();
7241 // adjust size if necessary
7243 && (isWindow() || !parentWidget()->d_func()->layout)) {
7246 if (windowState() != initialWindowState)
7247 setWindowState(initialWindowState);
7251 setAttribute(Qt::WA_Resized, false);
7254 setAttribute(Qt::WA_KeyboardFocusChange, false);
7256 if (isWindow() || parentWidget()->isVisible()) {
7259 qApp->d_func()->sendSyntheticEnterLeave(this);
7262 QEvent showToParentEvent(QEvent::ShowToParent);
7263 QApplication::sendEvent(this, &showToParentEvent);
7265 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7267 #if defined(Q_WS_WIN)
7268 // reset WS_DISABLED style in a Blocked window
7269 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7270 && QApplicationPrivate::isBlockedByModal(this))
7272 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7273 dwStyle &= ~WS_DISABLED;
7274 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7277 if (QApplicationPrivate::hidden_focus_widget == this)
7278 QApplicationPrivate::hidden_focus_widget = 0;
7282 // hw: The test on getOpaqueRegion() needs to be more intelligent
7283 // currently it doesn't work if the widget is hidden (the region will
7284 // be clipped). The real check should be testing the cached region
7285 // (and dirty flag) directly.
7286 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7287 parentWidget()->d_func()->setDirtyOpaqueRegion();
7289 setAttribute(Qt::WA_WState_Hidden);
7290 setAttribute(Qt::WA_WState_ExplicitShowHide);
7291 if (testAttribute(Qt::WA_WState_Created))
7294 // invalidate layout similar to updateGeometry()
7295 if (!isWindow() && parentWidget()) {
7296 if (parentWidget()->d_func()->layout)
7297 parentWidget()->d_func()->layout->invalidate();
7298 else if (parentWidget()->isVisible())
7299 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7302 QEvent hideToParentEvent(QEvent::HideToParent);
7303 QApplication::sendEvent(this, &hideToParentEvent);
7307 /*!\fn void QWidget::setHidden(bool hidden)
7309 Convenience function, equivalent to setVisible(!\a hidden).
7313 void QWidgetPrivate::_q_showIfNotHidden()
7316 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7317 q->setVisible(true);
7320 void QWidgetPrivate::showChildren(bool spontaneous)
7322 QList<QObject*> childList = children;
7323 for (int i = 0; i < childList.size(); ++i) {
7324 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7326 || widget->isWindow()
7327 || widget->testAttribute(Qt::WA_WState_Hidden))
7330 widget->setAttribute(Qt::WA_Mapped);
7331 widget->d_func()->showChildren(true);
7333 QApplication::sendSpontaneousEvent(widget, &e);
7335 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7336 widget->d_func()->show_recursive();
7343 void QWidgetPrivate::hideChildren(bool spontaneous)
7345 QList<QObject*> childList = children;
7346 for (int i = 0; i < childList.size(); ++i) {
7347 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7348 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7351 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7352 // When hiding a widget we need to make sure that no mouse_down events are active, because
7353 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7354 // The solution is simple, before going through with this we check if there are any mouse_down events in
7355 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7356 // then we continue.
7357 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7358 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7359 // mouse release event. There are two ways to interpret this:
7360 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7361 // might be waiting for a release event that will never arrive.
7362 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7363 // supposed to trigger because it is not visible.
7364 if(widget == qt_button_down)
7368 widget->setAttribute(Qt::WA_Mapped, false);
7370 widget->setAttribute(Qt::WA_WState_Visible, false);
7371 widget->d_func()->hideChildren(spontaneous);
7374 QApplication::sendSpontaneousEvent(widget, &e);
7376 QApplication::sendEvent(widget, &e);
7377 if (widget->internalWinId()
7378 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7379 // hide_sys() on an ancestor won't have any affect on this
7380 // widget, so it needs an explicit hide_sys() of its own
7381 widget->d_func()->hide_sys();
7384 qApp->d_func()->sendSyntheticEnterLeave(widget);
7385 #ifndef QT_NO_ACCESSIBILITY
7387 QAccessibleEvent event(QAccessible::ObjectHide, widget);
7388 QAccessible::updateAccessibility(&event);
7394 bool QWidgetPrivate::close_helper(CloseMode mode)
7396 if (data.is_closing)
7400 data.is_closing = 1;
7402 QPointer<QWidget> that = q;
7403 QPointer<QWidget> parentWidget = q->parentWidget();
7405 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7406 if (mode != CloseNoEvent) {
7408 if (mode == CloseWithSpontaneousEvent)
7409 QApplication::sendSpontaneousEvent(q, &e);
7411 QApplication::sendEvent(q, &e);
7412 if (!that.isNull() && !e.isAccepted()) {
7413 data.is_closing = 0;
7418 if (!that.isNull() && !q->isHidden())
7421 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7422 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7425 /* if there is no non-withdrawn primary window left (except
7426 the ones without QuitOnClose), we emit the lastWindowClosed
7428 QWidgetList list = QApplication::topLevelWidgets();
7429 bool lastWindowClosed = true;
7430 for (int i = 0; i < list.size(); ++i) {
7431 QWidget *w = list.at(i);
7432 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7434 lastWindowClosed = false;
7437 if (lastWindowClosed) {
7438 QGuiApplicationPrivate::emitLastWindowClosed();
7439 QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7440 applicationPrivate->maybeQuit();
7445 if (!that.isNull()) {
7446 data.is_closing = 0;
7447 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7448 q->setAttribute(Qt::WA_DeleteOnClose, false);
7457 Closes this widget. Returns true if the widget was closed;
7458 otherwise returns false.
7460 First it sends the widget a QCloseEvent. The widget is \link
7461 hide() hidden\endlink if it \link QCloseEvent::accept()
7462 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7463 ignores\endlink the event, nothing happens. The default
7464 implementation of QWidget::closeEvent() accepts the close event.
7466 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7467 is also deleted. A close events is delivered to the widget no
7468 matter if the widget is visible or not.
7470 The \l QApplication::lastWindowClosed() signal is emitted when the
7471 last visible primary window (i.e. window with no parent) with the
7472 Qt::WA_QuitOnClose attribute set is closed. By default this
7473 attribute is set for all widgets except transient windows such as
7474 splash screens, tool windows, and popup menus.
7478 bool QWidget::close()
7480 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7484 \property QWidget::visible
7485 \brief whether the widget is visible
7487 Calling setVisible(true) or show() sets the widget to visible
7488 status if all its parent widgets up to the window are visible. If
7489 an ancestor is not visible, the widget won't become visible until
7490 all its ancestors are shown. If its size or position has changed,
7491 Qt guarantees that a widget gets move and resize events just
7492 before it is shown. If the widget has not been resized yet, Qt
7493 will adjust the widget's size to a useful default using
7496 Calling setVisible(false) or hide() hides a widget explicitly. An
7497 explicitly hidden widget will never become visible, even if all
7498 its ancestors become visible, unless you show it.
7500 A widget receives show and hide events when its visibility status
7501 changes. Between a hide and a show event, there is no need to
7502 waste CPU cycles preparing or displaying information to the user.
7503 A video application, for example, might simply stop generating new
7506 A widget that happens to be obscured by other windows on the
7507 screen is considered to be visible. The same applies to iconified
7508 windows and windows that exist on another virtual
7509 desktop (on platforms that support this concept). A widget
7510 receives spontaneous show and hide events when its mapping status
7511 is changed by the window system, e.g. a spontaneous hide event
7512 when the user minimizes the window, and a spontaneous show event
7513 when the window is restored again.
7515 You almost never have to reimplement the setVisible() function. If
7516 you need to change some settings before a widget is shown, use
7517 showEvent() instead. If you need to do some delayed initialization
7518 use the Polish event delivered to the event() function.
7520 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7521 showEvent(), hideEvent()
7526 Returns true if this widget would become visible if \a ancestor is
7527 shown; otherwise returns false.
7529 The true case occurs if neither the widget itself nor any parent
7530 up to but excluding \a ancestor has been explicitly hidden.
7532 This function will still return true if the widget is obscured by
7533 other windows on the screen, but could be physically visible if it
7534 or they were to be moved.
7536 isVisibleTo(0) is identical to isVisible().
7538 \sa show() hide() isVisible()
7541 bool QWidget::isVisibleTo(QWidget* ancestor) const
7545 const QWidget * w = this;
7546 while (!w->isHidden()
7548 && w->parentWidget()
7549 && w->parentWidget() != ancestor)
7550 w = w->parentWidget();
7551 return !w->isHidden();
7556 Returns the unobscured region where paint events can occur.
7558 For visible widgets, this is an approximation of the area not
7559 covered by other widgets; otherwise, this is an empty region.
7561 The repaint() function calls this function if necessary, so in
7562 general you do not need to call it.
7565 QRegion QWidget::visibleRegion() const
7569 QRect clipRect = d->clipRect();
7570 if (clipRect.isEmpty())
7572 QRegion r(clipRect);
7573 d->subtractOpaqueChildren(r, clipRect);
7574 d->subtractOpaqueSiblings(r);
7579 QSize QWidgetPrivate::adjustedSize() const
7583 QSize s = q->sizeHint();
7585 if (q->isWindow()) {
7586 Qt::Orientations exp;
7588 if (layout->hasHeightForWidth())
7589 s.setHeight(layout->totalHeightForWidth(s.width()));
7590 exp = layout->expandingDirections();
7593 if (q->sizePolicy().hasHeightForWidth())
7594 s.setHeight(q->heightForWidth(s.width()));
7595 exp = q->sizePolicy().expandingDirections();
7597 if (exp & Qt::Horizontal)
7598 s.setWidth(qMax(s.width(), 200));
7599 if (exp & Qt::Vertical)
7600 s.setHeight(qMax(s.height(), 100));
7601 #if defined(Q_WS_X11)
7602 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7604 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7606 #if defined (Q_OS_WINCE)
7607 s.setWidth(qMin(s.width(), screen.width()));
7608 s.setHeight(qMin(s.height(), screen.height()));
7610 s.setWidth(qMin(s.width(), screen.width()*2/3));
7611 s.setHeight(qMin(s.height(), screen.height()*2/3));
7613 if (QTLWExtra *extra = maybeTopData())
7614 extra->sizeAdjusted = true;
7618 QRect r = q->childrenRect(); // get children rectangle
7621 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7628 Adjusts the size of the widget to fit its contents.
7630 This function uses sizeHint() if it is valid, i.e., the size hint's width
7631 and height are \>= 0. Otherwise, it sets the size to the children
7632 rectangle that covers all child widgets (the union of all child widget
7635 For windows, the screen size is also taken into account. If the sizeHint()
7636 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7637 {expanding}, the window will be at least (200, 100). The maximum size of
7638 a window is 2/3 of the screen's width and height.
7640 \sa sizeHint(), childrenRect()
7643 void QWidget::adjustSize()
7647 QSize s = d->adjustedSize();
7650 d->layout->activate();
7658 \property QWidget::sizeHint
7659 \brief the recommended size for the widget
7661 If the value of this property is an invalid size, no size is
7664 The default implementation of sizeHint() returns an invalid size
7665 if there is no layout for this widget, and returns the layout's
7666 preferred size otherwise.
7668 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7669 setMinimumSize(), updateGeometry()
7672 QSize QWidget::sizeHint() const
7676 return d->layout->totalSizeHint();
7677 return QSize(-1, -1);
7681 \property QWidget::minimumSizeHint
7682 \brief the recommended minimum size for the widget
7684 If the value of this property is an invalid size, no minimum size
7687 The default implementation of minimumSizeHint() returns an invalid
7688 size if there is no layout for this widget, and returns the
7689 layout's minimum size otherwise. Most built-in widgets reimplement
7692 \l QLayout will never resize a widget to a size smaller than the
7693 minimum size hint unless minimumSize() is set or the size policy is
7694 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7695 size hint will be ignored.
7697 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7699 QSize QWidget::minimumSizeHint() const
7703 return d->layout->totalMinimumSize();
7704 return QSize(-1, -1);
7709 \fn QWidget *QWidget::parentWidget() const
7711 Returns the parent of this widget, or 0 if it does not have any
7717 Returns true if this widget is a parent, (or grandparent and so on
7718 to any level), of the given \a child, and both widgets are within
7719 the same window; otherwise returns false.
7722 bool QWidget::isAncestorOf(const QWidget *child) const
7727 if (child->isWindow())
7729 child = child->parentWidget();
7734 #if defined(Q_WS_WIN)
7735 inline void setDisabledStyle(QWidget *w, bool setStyle)
7737 // set/reset WS_DISABLED style.
7738 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7739 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7740 LONG newStyle = dwStyle;
7742 newStyle |= WS_DISABLED;
7744 newStyle &= ~WS_DISABLED;
7745 if (newStyle != dwStyle) {
7746 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7747 // we might need to repaint in some situations (eg. menu)
7754 /*****************************************************************************
7755 QWidget event handling
7756 *****************************************************************************/
7759 This is the main event handler; it handles event \a event. You can
7760 reimplement this function in a subclass, but we recommend using
7761 one of the specialized event handlers instead.
7763 Key press and release events are treated differently from other
7764 events. event() checks for Tab and Shift+Tab and tries to move the
7765 focus appropriately. If there is no widget to move the focus to
7766 (or the key press is not Tab or Shift+Tab), event() calls
7769 Mouse and tablet event handling is also slightly special: only
7770 when the widget is \l enabled, event() will call the specialized
7771 handlers such as mousePressEvent(); otherwise it will discard the
7774 This function returns true if the event was recognized, otherwise
7775 it returns false. If the recognized event was accepted (see \l
7776 QEvent::accepted), any further processing such as event
7777 propagation to the parent widget stops.
7779 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7780 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7781 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7782 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7783 QObject::event(), QObject::timerEvent()
7786 bool QWidget::event(QEvent *event)
7790 // ignore mouse events when disabled
7792 switch(event->type()) {
7793 case QEvent::TabletPress:
7794 case QEvent::TabletRelease:
7795 case QEvent::TabletMove:
7796 case QEvent::MouseButtonPress:
7797 case QEvent::MouseButtonRelease:
7798 case QEvent::MouseButtonDblClick:
7799 case QEvent::MouseMove:
7800 case QEvent::TouchBegin:
7801 case QEvent::TouchUpdate:
7802 case QEvent::TouchEnd:
7803 case QEvent::TouchCancel:
7804 case QEvent::ContextMenu:
7805 #ifndef QT_NO_WHEELEVENT
7813 switch (event->type()) {
7814 case QEvent::MouseMove:
7815 mouseMoveEvent((QMouseEvent*)event);
7818 case QEvent::MouseButtonPress:
7819 mousePressEvent((QMouseEvent*)event);
7822 case QEvent::MouseButtonRelease:
7823 mouseReleaseEvent((QMouseEvent*)event);
7826 case QEvent::MouseButtonDblClick:
7827 mouseDoubleClickEvent((QMouseEvent*)event);
7829 #ifndef QT_NO_WHEELEVENT
7831 wheelEvent((QWheelEvent*)event);
7834 #ifndef QT_NO_TABLETEVENT
7835 case QEvent::TabletMove:
7836 case QEvent::TabletPress:
7837 case QEvent::TabletRelease:
7838 tabletEvent((QTabletEvent*)event);
7841 case QEvent::KeyPress: {
7842 QKeyEvent *k = (QKeyEvent *)event;
7844 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7845 if (k->key() == Qt::Key_Backtab
7846 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7847 res = focusNextPrevChild(false);
7848 else if (k->key() == Qt::Key_Tab)
7849 res = focusNextPrevChild(true);
7854 #ifdef QT_KEYPAD_NAVIGATION
7855 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7856 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7857 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7858 if (k->key() == Qt::Key_Up)
7859 res = focusNextPrevChild(false);
7860 else if (k->key() == Qt::Key_Down)
7861 res = focusNextPrevChild(true);
7862 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7863 if (k->key() == Qt::Key_Up)
7864 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7865 else if (k->key() == Qt::Key_Right)
7866 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7867 else if (k->key() == Qt::Key_Down)
7868 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7869 else if (k->key() == Qt::Key_Left)
7870 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7878 #ifndef QT_NO_WHATSTHIS
7879 if (!k->isAccepted()
7880 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7881 && d->whatsThis.size()) {
7882 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7889 case QEvent::KeyRelease:
7890 keyReleaseEvent((QKeyEvent*)event);
7892 case QEvent::ShortcutOverride:
7895 case QEvent::InputMethod:
7896 inputMethodEvent((QInputMethodEvent *) event);
7899 case QEvent::InputMethodQuery:
7900 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7901 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7902 Qt::InputMethodQueries queries = query->queries();
7903 for (uint i = 0; i < 32; ++i) {
7904 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7906 QVariant v = inputMethodQuery(q);
7907 if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7908 v = QVariant(true); // special case for Qt4 compatibility
7909 query->setValue(q, v);
7916 case QEvent::PolishRequest:
7920 case QEvent::Polish: {
7921 style()->polish(this);
7922 setAttribute(Qt::WA_WState_Polished);
7923 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7925 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7926 d->resolvePalette();
7930 case QEvent::ApplicationWindowIconChange:
7931 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7932 d->setWindowIcon_sys();
7933 d->setWindowIcon_helper();
7936 case QEvent::FocusIn:
7937 #ifdef QT_SOFTKEYS_ENABLED
7938 QSoftKeyManager::updateSoftKeys();
7940 focusInEvent((QFocusEvent*)event);
7941 d->updateWidgetTransform();
7944 case QEvent::FocusOut:
7945 focusOutEvent((QFocusEvent*)event);
7949 #ifndef QT_NO_STATUSTIP
7950 if (d->statusTip.size()) {
7951 QStatusTipEvent tip(d->statusTip);
7952 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7959 #ifndef QT_NO_STATUSTIP
7960 if (d->statusTip.size()) {
7962 QStatusTipEvent tip(empty);
7963 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7969 case QEvent::HoverEnter:
7970 case QEvent::HoverLeave:
7975 // At this point the event has to be delivered, regardless
7976 // whether the widget isVisible() or not because it
7977 // already went through the filters
7978 paintEvent((QPaintEvent*)event);
7982 moveEvent((QMoveEvent*)event);
7983 d->updateWidgetTransform();
7986 case QEvent::Resize:
7987 resizeEvent((QResizeEvent*)event);
7988 d->updateWidgetTransform();
7992 closeEvent((QCloseEvent *)event);
7995 #ifndef QT_NO_CONTEXTMENU
7996 case QEvent::ContextMenu:
7997 switch (data->context_menu_policy) {
7998 case Qt::PreventContextMenu:
8000 case Qt::DefaultContextMenu:
8001 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8003 case Qt::CustomContextMenu:
8004 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8007 case Qt::ActionsContextMenu:
8008 if (d->actions.count()) {
8009 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8020 #endif // QT_NO_CONTEXTMENU
8022 #ifndef QT_NO_DRAGANDDROP
8024 dropEvent((QDropEvent*) event);
8027 case QEvent::DragEnter:
8028 dragEnterEvent((QDragEnterEvent*) event);
8031 case QEvent::DragMove:
8032 dragMoveEvent((QDragMoveEvent*) event);
8035 case QEvent::DragLeave:
8036 dragLeaveEvent((QDragLeaveEvent*) event);
8041 showEvent((QShowEvent*) event);
8045 hideEvent((QHideEvent*) event);
8048 case QEvent::ShowWindowRequest:
8053 case QEvent::ApplicationFontChange:
8056 case QEvent::ApplicationPaletteChange:
8057 if (!(windowType() == Qt::Desktop))
8058 d->resolvePalette();
8061 case QEvent::ToolBarChange:
8062 case QEvent::ActivationChange:
8063 case QEvent::EnabledChange:
8064 case QEvent::FontChange:
8065 case QEvent::StyleChange:
8066 case QEvent::PaletteChange:
8067 case QEvent::WindowTitleChange:
8068 case QEvent::IconTextChange:
8069 case QEvent::ModifiedChange:
8070 case QEvent::MouseTrackingChange:
8071 case QEvent::ParentChange:
8072 case QEvent::WindowStateChange:
8073 case QEvent::LocaleChange:
8074 case QEvent::MacSizeChange:
8075 case QEvent::ContentsRectChange:
8076 case QEvent::ThemeChange:
8080 case QEvent::WindowActivate:
8081 case QEvent::WindowDeactivate: {
8082 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8084 QList<QObject*> childList = d->children;
8085 for (int i = 0; i < childList.size(); ++i) {
8086 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8087 if (w && w->isVisible() && !w->isWindow())
8088 QApplication::sendEvent(w, event);
8091 #ifdef QT_SOFTKEYS_ENABLED
8093 QSoftKeyManager::updateSoftKeys();
8098 case QEvent::LanguageChange:
8101 QList<QObject*> childList = d->children;
8102 for (int i = 0; i < childList.size(); ++i) {
8103 QObject *o = childList.at(i);
8105 QApplication::sendEvent(o, event);
8111 case QEvent::ApplicationLayoutDirectionChange:
8112 d->resolveLayoutDirection();
8115 case QEvent::LayoutDirectionChange:
8117 d->layout->invalidate();
8121 case QEvent::UpdateRequest:
8122 d->syncBackingStore();
8124 case QEvent::UpdateLater:
8125 update(static_cast<QUpdateLaterEvent*>(event)->region());
8128 case QEvent::WindowBlocked:
8129 case QEvent::WindowUnblocked:
8131 QList<QObject*> childList = d->children;
8132 for (int i = 0; i < childList.size(); ++i) {
8133 QObject *o = childList.at(i);
8134 if (o && o != QApplication::activeModalWidget()) {
8135 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8136 // do not forward the event to child windows,
8137 // QApplication does this for us
8140 QApplication::sendEvent(o, event);
8143 #if defined(Q_WS_WIN)
8144 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8148 #ifndef QT_NO_TOOLTIP
8149 case QEvent::ToolTip:
8150 if (!d->toolTip.isEmpty())
8151 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8156 #ifndef QT_NO_WHATSTHIS
8157 case QEvent::WhatsThis:
8158 if (d->whatsThis.size())
8159 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8163 case QEvent::QueryWhatsThis:
8164 if (d->whatsThis.isEmpty())
8168 case QEvent::EmbeddingControl:
8169 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8170 data->fstrut_dirty = false;
8171 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8172 d->topData()->embedded = 1;
8175 #ifndef QT_NO_ACTION
8176 case QEvent::ActionAdded:
8177 case QEvent::ActionRemoved:
8178 case QEvent::ActionChanged:
8179 #ifdef QT_SOFTKEYS_ENABLED
8180 QSoftKeyManager::updateSoftKeys();
8182 actionEvent((QActionEvent*)event);
8186 case QEvent::KeyboardLayoutChange:
8190 // inform children of the change
8191 QList<QObject*> childList = d->children;
8192 for (int i = 0; i < childList.size(); ++i) {
8193 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8194 if (w && w->isVisible() && !w->isWindow())
8195 QApplication::sendEvent(w, event);
8200 case QEvent::MacGLWindowChange:
8201 d->needWindowChange = false;
8204 case QEvent::TouchBegin:
8205 case QEvent::TouchUpdate:
8206 case QEvent::TouchEnd:
8207 case QEvent::TouchCancel:
8212 #ifndef QT_NO_GESTURES
8213 case QEvent::Gesture:
8217 #ifndef QT_NO_PROPERTIES
8218 case QEvent::DynamicPropertyChange: {
8219 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8220 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8221 uint value = property(propName.constData()).toUInt();
8224 const char axis = propName.at(12);
8226 d->extra->customDpiX = value;
8227 else if (axis == 'Y')
8228 d->extra->customDpiY = value;
8229 d->updateFont(d->data.fnt);
8235 return QObject::event(event);
8241 This event handler can be reimplemented to handle state changes.
8243 The state being changed in this event can be retrieved through the \a event
8246 Change events include: QEvent::ToolBarChange,
8247 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8248 QEvent::StyleChange, QEvent::PaletteChange,
8249 QEvent::WindowTitleChange, QEvent::IconTextChange,
8250 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8251 QEvent::ParentChange, QEvent::WindowStateChange,
8252 QEvent::LanguageChange, QEvent::LocaleChange,
8253 QEvent::LayoutDirectionChange.
8256 void QWidget::changeEvent(QEvent * event)
8258 switch(event->type()) {
8259 case QEvent::EnabledChange: {
8261 #ifndef QT_NO_ACCESSIBILITY
8262 QAccessible::State s;
8264 QAccessibleStateChangeEvent event(s, this);
8265 QAccessible::updateAccessibility(&event);
8270 case QEvent::FontChange:
8271 case QEvent::StyleChange: {
8276 d->layout->invalidate();
8280 case QEvent::PaletteChange:
8284 case QEvent::ThemeChange:
8285 if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8286 && qApp && !QApplication::closingDown()) {
8287 if (testAttribute(Qt::WA_WState_Polished))
8288 QApplication::style()->unpolish(this);
8289 if (testAttribute(Qt::WA_WState_Polished))
8290 QApplication::style()->polish(this);
8291 QEvent styleChangedEvent(QEvent::StyleChange);
8292 QCoreApplication::sendEvent(this, &styleChangedEvent);
8299 case QEvent::MacSizeChange:
8302 case QEvent::ToolTipChange:
8303 case QEvent::MouseTrackingChange:
8304 qt_mac_update_mouseTracking(this);
8314 This event handler, for event \a event, can be reimplemented in a
8315 subclass to receive mouse move events for the widget.
8317 If mouse tracking is switched off, mouse move events only occur if
8318 a mouse button is pressed while the mouse is being moved. If mouse
8319 tracking is switched on, mouse move events occur even if no mouse
8322 QMouseEvent::pos() reports the position of the mouse cursor,
8323 relative to this widget. For press and release events, the
8324 position is usually the same as the position of the last mouse
8325 move event, but it might be different if the user's hand shakes.
8326 This is a feature of the underlying window system, not Qt.
8328 If you want to show a tooltip immediately, while the mouse is
8329 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8330 and show them as a tooltip), you must first enable mouse tracking
8331 as described above. Then, to ensure that the tooltip is updated
8332 immediately, you must call QToolTip::showText() instead of
8333 setToolTip() in your implementation of mouseMoveEvent().
8335 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8336 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8339 void QWidget::mouseMoveEvent(QMouseEvent *event)
8345 This event handler, for event \a event, can be reimplemented in a
8346 subclass to receive mouse press events for the widget.
8348 If you create new widgets in the mousePressEvent() the
8349 mouseReleaseEvent() may not end up where you expect, depending on
8350 the underlying window system (or X11 window manager), the widgets'
8351 location and maybe more.
8353 The default implementation implements the closing of popup widgets
8354 when you click outside the window. For other widget types it does
8357 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8358 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8361 void QWidget::mousePressEvent(QMouseEvent *event)
8364 if ((windowType() == Qt::Popup)) {
8367 while ((w = QApplication::activePopupWidget()) && w != this){
8369 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8370 w->hide(); // hide at least
8372 if (!rect().contains(event->pos())){
8379 This event handler, for event \a event, can be reimplemented in a
8380 subclass to receive mouse release events for the widget.
8382 \sa mousePressEvent(), mouseDoubleClickEvent(),
8383 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8386 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8392 This event handler, for event \a event, can be reimplemented in a
8393 subclass to receive mouse double click events for the widget.
8395 The default implementation generates a normal mouse press event.
8397 \note The widget will also receive mouse press and mouse release
8398 events in addition to the double click event. It is up to the
8399 developer to ensure that the application interprets these events
8402 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8403 event(), QMouseEvent
8406 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8410 #ifndef QT_NO_WHEELEVENT
8412 This event handler, for event \a event, can be reimplemented in a
8413 subclass to receive wheel events for the widget.
8415 If you reimplement this handler, it is very important that you
8416 \link QWheelEvent ignore()\endlink the event if you do not handle
8417 it, so that the widget's parent can interpret it.
8419 The default implementation ignores the event.
8421 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8425 void QWidget::wheelEvent(QWheelEvent *event)
8429 #endif // QT_NO_WHEELEVENT
8431 #ifndef QT_NO_TABLETEVENT
8433 This event handler, for event \a event, can be reimplemented in a
8434 subclass to receive tablet events for the widget.
8436 If you reimplement this handler, it is very important that you
8437 \link QTabletEvent ignore()\endlink the event if you do not handle
8438 it, so that the widget's parent can interpret it.
8440 The default implementation ignores the event.
8442 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8446 void QWidget::tabletEvent(QTabletEvent *event)
8450 #endif // QT_NO_TABLETEVENT
8453 This event handler, for event \a event, can be reimplemented in a
8454 subclass to receive key press events for the widget.
8456 A widget must call setFocusPolicy() to accept focus initially and
8457 have focus in order to receive a key press event.
8459 If you reimplement this handler, it is very important that you
8460 call the base class implementation if you do not act upon the key.
8462 The default implementation closes popup widgets if the user
8463 presses Esc. Otherwise the event is ignored, so that the widget's
8464 parent can interpret it.
8466 Note that QKeyEvent starts with isAccepted() == true, so you do not
8467 need to call QKeyEvent::accept() - just do not call the base class
8468 implementation if you act upon the key.
8470 \sa keyReleaseEvent(), setFocusPolicy(),
8471 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8474 void QWidget::keyPressEvent(QKeyEvent *event)
8476 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8485 This event handler, for event \a event, can be reimplemented in a
8486 subclass to receive key release events for the widget.
8488 A widget must \link setFocusPolicy() accept focus\endlink
8489 initially and \link hasFocus() have focus\endlink in order to
8490 receive a key release event.
8492 If you reimplement this handler, it is very important that you
8493 call the base class implementation if you do not act upon the key.
8495 The default implementation ignores the event, so that the widget's
8496 parent can interpret it.
8498 Note that QKeyEvent starts with isAccepted() == true, so you do not
8499 need to call QKeyEvent::accept() - just do not call the base class
8500 implementation if you act upon the key.
8502 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8503 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8506 void QWidget::keyReleaseEvent(QKeyEvent *event)
8512 \fn void QWidget::focusInEvent(QFocusEvent *event)
8514 This event handler can be reimplemented in a subclass to receive
8515 keyboard focus events (focus received) for the widget. The event
8516 is passed in the \a event parameter
8518 A widget normally must setFocusPolicy() to something other than
8519 Qt::NoFocus in order to receive focus events. (Note that the
8520 application programmer can call setFocus() on any widget, even
8521 those that do not normally accept focus.)
8523 The default implementation updates the widget (except for windows
8524 that do not specify a focusPolicy()).
8526 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8527 keyReleaseEvent(), event(), QFocusEvent
8530 void QWidget::focusInEvent(QFocusEvent *)
8532 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8538 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8540 This event handler can be reimplemented in a subclass to receive
8541 keyboard focus events (focus lost) for the widget. The events is
8542 passed in the \a event parameter.
8544 A widget normally must setFocusPolicy() to something other than
8545 Qt::NoFocus in order to receive focus events. (Note that the
8546 application programmer can call setFocus() on any widget, even
8547 those that do not normally accept focus.)
8549 The default implementation updates the widget (except for windows
8550 that do not specify a focusPolicy()).
8552 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8553 keyReleaseEvent(), event(), QFocusEvent
8556 void QWidget::focusOutEvent(QFocusEvent *)
8558 if (focusPolicy() != Qt::NoFocus || !isWindow())
8563 \fn void QWidget::enterEvent(QEvent *event)
8565 This event handler can be reimplemented in a subclass to receive
8566 widget enter events which are passed in the \a event parameter.
8568 An event is sent to the widget when the mouse cursor enters the
8571 \sa leaveEvent(), mouseMoveEvent(), event()
8574 void QWidget::enterEvent(QEvent *)
8579 \fn void QWidget::leaveEvent(QEvent *event)
8581 This event handler can be reimplemented in a subclass to receive
8582 widget leave events which are passed in the \a event parameter.
8584 A leave event is sent to the widget when the mouse cursor leaves
8587 \sa enterEvent(), mouseMoveEvent(), event()
8590 void QWidget::leaveEvent(QEvent *)
8595 \fn void QWidget::paintEvent(QPaintEvent *event)
8597 This event handler can be reimplemented in a subclass to receive paint
8598 events passed in \a event.
8600 A paint event is a request to repaint all or part of a widget. It can
8601 happen for one of the following reasons:
8604 \li repaint() or update() was invoked,
8605 \li the widget was obscured and has now been uncovered, or
8606 \li many other reasons.
8609 Many widgets can simply repaint their entire surface when asked to, but
8610 some slow widgets need to optimize by painting only the requested region:
8611 QPaintEvent::region(). This speed optimization does not change the result,
8612 as painting is clipped to that region during event processing. QListView
8613 and QTableView do this, for example.
8615 Qt also tries to speed up painting by merging multiple paint events into
8616 one. When update() is called several times or the window system sends
8617 several paint events, Qt merges these events into one event with a larger
8618 region (see QRegion::united()). The repaint() function does not permit this
8619 optimization, so we suggest using update() whenever possible.
8621 When the paint event occurs, the update region has normally been erased, so
8622 you are painting on the widget's background.
8624 The background can be set using setBackgroundRole() and setPalette().
8626 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8627 is no need to write double-buffering code in paintEvent() to avoid flicker.
8629 \b{Note for the X11 platform}: It is possible to toggle global double
8630 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8632 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8634 \note Generally, you should refrain from calling update() or repaint()
8635 \b{inside} a paintEvent(). For example, calling update() or repaint() on
8636 children inside a paintevent() results in undefined behavior; the child may
8637 or may not get a paint event.
8639 \warning If you are using a custom paint engine without Qt's backingstore,
8640 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8641 never be called; the backingstore will be used instead.
8643 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8644 {Analog Clock Example}
8647 void QWidget::paintEvent(QPaintEvent *)
8653 \fn void QWidget::moveEvent(QMoveEvent *event)
8655 This event handler can be reimplemented in a subclass to receive
8656 widget move events which are passed in the \a event parameter.
8657 When the widget receives this event, it is already at the new
8660 The old position is accessible through QMoveEvent::oldPos().
8662 \sa resizeEvent(), event(), move(), QMoveEvent
8665 void QWidget::moveEvent(QMoveEvent *)
8671 This event handler can be reimplemented in a subclass to receive
8672 widget resize events which are passed in the \a event parameter.
8673 When resizeEvent() is called, the widget already has its new
8674 geometry. The old size is accessible through
8675 QResizeEvent::oldSize().
8677 The widget will be erased and receive a paint event immediately
8678 after processing the resize event. No drawing need be (or should
8679 be) done inside this handler.
8682 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8686 void QWidget::resizeEvent(QResizeEvent * /* event */)
8690 #ifndef QT_NO_ACTION
8692 \fn void QWidget::actionEvent(QActionEvent *event)
8694 This event handler is called with the given \a event whenever the
8695 widget's actions are changed.
8697 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8699 void QWidget::actionEvent(QActionEvent *)
8706 This event handler is called with the given \a event when Qt receives a window
8707 close request for a top-level widget from the window system.
8709 By default, the event is accepted and the widget is closed. You can reimplement
8710 this function to change the way the widget responds to window close requests.
8711 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8714 Main window applications typically use reimplementations of this function to check
8715 whether the user's work has been saved and ask for permission before closing.
8716 For example, the \l{Application Example} uses a helper function to determine whether
8717 or not to close the window:
8719 \snippet mainwindows/application/mainwindow.cpp 3
8720 \snippet mainwindows/application/mainwindow.cpp 4
8722 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8725 void QWidget::closeEvent(QCloseEvent *event)
8730 #ifndef QT_NO_CONTEXTMENU
8732 This event handler, for event \a event, can be reimplemented in a
8733 subclass to receive widget context menu events.
8735 The handler is called when the widget's \l contextMenuPolicy is
8736 Qt::DefaultContextMenu.
8738 The default implementation ignores the context event.
8739 See the \l QContextMenuEvent documentation for more details.
8741 \sa event(), QContextMenuEvent customContextMenuRequested()
8744 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8748 #endif // QT_NO_CONTEXTMENU
8752 This event handler, for event \a event, can be reimplemented in a
8753 subclass to receive Input Method composition events. This handler
8754 is called when the state of the input method changes.
8756 Note that when creating custom text editing widgets, the
8757 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8758 (using the setAttribute() function) in order to receive input
8761 The default implementation calls event->ignore(), which rejects the
8762 Input Method event. See the \l QInputMethodEvent documentation for more
8765 \sa event(), QInputMethodEvent
8767 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8773 This method is only relevant for input widgets. It is used by the
8774 input method to query a set of properties of the widget to be
8775 able to support complex input method operations as support for
8776 surrounding text and reconversions.
8778 \a query specifies which property is queried.
8780 \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8782 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8785 case Qt::ImCursorRectangle:
8786 return QRect(width()/2, 0, 1, height());
8789 case Qt::ImAnchorPosition:
8791 return inputMethodQuery(Qt::ImCursorPosition);
8793 return (int)inputMethodHints();
8800 \property QWidget::inputMethodHints
8801 \brief What input method specific hints the widget has.
8803 This is only relevant for input widgets. It is used by
8804 the input method to retrieve hints as to how the input method
8805 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8806 is set, the input method may change its visual components to reflect
8807 that only numbers can be entered.
8809 \note The flags are only hints, so the particular input method
8810 implementation is free to ignore them. If you want to be
8811 sure that a certain type of characters are entered,
8812 you should also set a QValidator on the widget.
8814 The default value is Qt::ImhNone.
8818 \sa inputMethodQuery()
8820 Qt::InputMethodHints QWidget::inputMethodHints() const
8823 const QWidgetPrivate *priv = d_func();
8824 while (priv->inheritsInputMethodHints) {
8825 priv = priv->q_func()->parentWidget()->d_func();
8828 return priv->imHints;
8834 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8839 qApp->inputMethod()->update(Qt::ImHints);
8844 #ifndef QT_NO_DRAGANDDROP
8847 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8849 This event handler is called when a drag is in progress and the
8850 mouse enters this widget. The event is passed in the \a event parameter.
8852 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8855 See the \link dnd.html Drag-and-drop documentation\endlink for an
8856 overview of how to provide drag-and-drop in your application.
8858 \sa QDrag, QDragEnterEvent
8860 void QWidget::dragEnterEvent(QDragEnterEvent *)
8865 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8867 This event handler is called if a drag is in progress, and when
8868 any of the following conditions occur: the cursor enters this widget,
8869 the cursor moves within this widget, or a modifier key is pressed on
8870 the keyboard while this widget has the focus. The event is passed
8871 in the \a event parameter.
8873 See the \link dnd.html Drag-and-drop documentation\endlink for an
8874 overview of how to provide drag-and-drop in your application.
8876 \sa QDrag, QDragMoveEvent
8878 void QWidget::dragMoveEvent(QDragMoveEvent *)
8883 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8885 This event handler is called when a drag is in progress and the
8886 mouse leaves this widget. The event is passed in the \a event
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, QDragLeaveEvent
8894 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8899 \fn void QWidget::dropEvent(QDropEvent *event)
8901 This event handler is called when the drag is dropped on this
8902 widget. The event is passed in the \a event parameter.
8904 See the \link dnd.html Drag-and-drop documentation\endlink for an
8905 overview of how to provide drag-and-drop in your application.
8907 \sa QDrag, QDropEvent
8909 void QWidget::dropEvent(QDropEvent *)
8913 #endif // QT_NO_DRAGANDDROP
8916 \fn void QWidget::showEvent(QShowEvent *event)
8918 This event handler can be reimplemented in a subclass to receive
8919 widget show events which are passed in the \a event parameter.
8921 Non-spontaneous show events are sent to widgets immediately
8922 before they are shown. The spontaneous show events of windows are
8923 delivered afterwards.
8925 Note: A widget receives spontaneous show and hide events when its
8926 mapping status is changed by the window system, e.g. a spontaneous
8927 hide event when the user minimizes the window, and a spontaneous
8928 show event when the window is restored again. After receiving a
8929 spontaneous hide event, a widget is still considered visible in
8930 the sense of isVisible().
8932 \sa visible, event(), QShowEvent
8934 void QWidget::showEvent(QShowEvent *)
8939 \fn void QWidget::hideEvent(QHideEvent *event)
8941 This event handler can be reimplemented in a subclass to receive
8942 widget hide events. The event is passed in the \a event parameter.
8944 Hide events are sent to widgets immediately after they have been
8947 Note: A widget receives spontaneous show and hide events when its
8948 mapping status is changed by the window system, e.g. a spontaneous
8949 hide event when the user minimizes the window, and a spontaneous
8950 show event when the window is restored again. After receiving a
8951 spontaneous hide event, a widget is still considered visible in
8952 the sense of isVisible().
8954 \sa visible, event(), QHideEvent
8956 void QWidget::hideEvent(QHideEvent *)
8961 This special event handler can be reimplemented in a subclass to
8962 receive native platform events identified by \a eventType
8963 which are passed in the \a message parameter.
8965 In your reimplementation of this function, if you want to stop the
8966 event being handled by Qt, return true and set \a result.
8967 If you return false, this native event is passed back to Qt,
8968 which translates the event into a Qt event and sends it to the widget.
8970 \note Events are only delivered to this event handler if the widget is
8971 has a native Window handle.
8973 \note This function superseedes the event filter functions
8974 x11Event(), winEvent() and macEvent() of Qt 4.
8977 \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
8978 \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
8982 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
8984 Q_UNUSED(eventType);
8991 Ensures that the widget has been polished by QStyle (i.e., has a
8992 proper font and palette).
8994 QWidget calls this function after it has been fully constructed
8995 but before it is shown the very first time. You can call this
8996 function if you want to ensure that the widget is polished before
8997 doing an operation, e.g., the correct font size might be needed in
8998 the widget's sizeHint() reimplementation. Note that this function
8999 \e is called from the default implementation of sizeHint().
9001 Polishing is useful for final initialization that must happen after
9002 all constructors (from base classes as well as from subclasses)
9005 If you need to change some settings when a widget is polished,
9006 reimplement event() and handle the QEvent::Polish event type.
9008 \b{Note:} The function is declared const so that it can be called from
9009 other const functions (e.g., sizeHint()).
9013 void QWidget::ensurePolished() const
9017 const QMetaObject *m = metaObject();
9018 if (m == d->polished)
9022 QEvent e(QEvent::Polish);
9023 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9025 // polish children after 'this'
9026 QList<QObject*> children = d->children;
9027 for (int i = 0; i < children.size(); ++i) {
9028 QObject *o = children.at(i);
9029 if(!o->isWidgetType())
9031 if (QWidget *w = qobject_cast<QWidget *>(o))
9032 w->ensurePolished();
9035 if (d->parent && d->sendChildEvents) {
9036 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9037 QCoreApplication::sendEvent(d->parent, &e);
9039 if (d->extra && d->extra->topextra && d->extra->topextra->window
9040 && d->extra->topextra->window->objectName().isEmpty()) {
9041 QString on = objectName();
9043 on = QString::fromUtf8(metaObject()->className());
9044 on += QStringLiteral("Class");
9046 on += QStringLiteral("Window");
9047 d->extra->topextra->window->setObjectName(on);
9052 Returns the mask currently set on a widget. If no mask is set the
9053 return value will be an empty region.
9055 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9057 QRegion QWidget::mask() const
9060 return d->extra ? d->extra->mask : QRegion();
9064 Returns the layout manager that is installed on this widget, or 0
9065 if no layout manager is installed.
9067 The layout manager sets the geometry of the widget's children
9068 that have been added to the layout.
9070 \sa setLayout(), sizePolicy(), {Layout Management}
9072 QLayout *QWidget::layout() const
9074 return d_func()->layout;
9079 \fn void QWidget::setLayout(QLayout *layout)
9081 Sets the layout manager for this widget to \a layout.
9083 If there already is a layout manager installed on this widget,
9084 QWidget won't let you install another. You must first delete the
9085 existing layout manager (returned by layout()) before you can
9086 call setLayout() with the new layout.
9088 If \a layout is the layout manger on a different widget, setLayout()
9089 will reparent the layout and make it the layout manager for this widget.
9093 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9095 An alternative to calling this function is to pass this widget to
9096 the layout's constructor.
9098 The QWidget will take ownership of \a layout.
9100 \sa layout(), {Layout Management}
9103 void QWidget::setLayout(QLayout *l)
9106 qWarning("QWidget::setLayout: Cannot set layout to 0");
9111 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9112 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9113 objectName().toLocal8Bit().data());
9117 QObject *oldParent = l->parent();
9118 if (oldParent && oldParent != this) {
9119 if (oldParent->isWidgetType()) {
9120 // Steal the layout off a widget parent. Takes effect when
9121 // morphing laid-out container widgets in Designer.
9122 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9123 oldParentWidget->takeLayout();
9125 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9126 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9127 objectName().toLocal8Bit().data());
9133 l->d_func()->topLevel = true;
9135 if (oldParent != this) {
9137 l->d_func()->reparentChildWidgets(this);
9141 if (isWindow() && d->maybeTopData())
9142 d->topData()->sizeAdjusted = false;
9146 \fn QLayout *QWidget::takeLayout()
9148 Remove the layout from the widget.
9152 QLayout *QWidget::takeLayout()
9155 QLayout *l = layout();
9164 \property QWidget::sizePolicy
9165 \brief the default layout behavior of the widget
9167 If there is a QLayout that manages this widget's children, the
9168 size policy specified by that layout is used. If there is no such
9169 QLayout, the result of this function is used.
9171 The default policy is Preferred/Preferred, which means that the
9172 widget can be freely resized, but prefers to be the size
9173 sizeHint() returns. Button-like widgets set the size policy to
9174 specify that they may stretch horizontally, but are fixed
9175 vertically. The same applies to lineedit controls (such as
9176 QLineEdit, QSpinBox or an editable QComboBox) and other
9177 horizontally orientated widgets (such as QProgressBar).
9178 QToolButton's are normally square, so they allow growth in both
9179 directions. Widgets that support different directions (such as
9180 QSlider, QScrollBar or QHeader) specify stretching in the
9181 respective direction only. Widgets that can provide scroll bars
9182 (usually subclasses of QScrollArea) tend to specify that they can
9183 use additional space, and that they can make do with less than
9186 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9188 QSizePolicy QWidget::sizePolicy() const
9191 return d->size_policy;
9194 void QWidget::setSizePolicy(QSizePolicy policy)
9197 setAttribute(Qt::WA_WState_OwnSizePolicy);
9198 if (policy == d->size_policy)
9200 d->size_policy = policy;
9202 #ifndef QT_NO_GRAPHICSVIEW
9203 if (QWExtra *extra = d->extra) {
9204 if (extra->proxyWidget)
9205 extra->proxyWidget->setSizePolicy(policy);
9211 if (isWindow() && d->maybeTopData())
9212 d->topData()->sizeAdjusted = false;
9216 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9219 Sets the size policy of the widget to \a horizontal and \a
9220 vertical, with standard stretch and no height-for-width.
9222 \sa QSizePolicy::QSizePolicy()
9226 Returns the preferred height for this widget, given the width \a w.
9228 If this widget has a layout, the default implementation returns
9229 the layout's preferred height. if there is no layout, the default
9230 implementation returns -1 indicating that the preferred height
9231 does not depend on the width.
9234 int QWidget::heightForWidth(int w) const
9236 if (layout() && layout()->hasHeightForWidth())
9237 return layout()->totalHeightForWidth(w);
9245 Returns true if the widget's preferred height depends on its width; otherwise returns false.
9247 bool QWidget::hasHeightForWidth() const
9250 return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9254 \fn QWidget *QWidget::childAt(int x, int y) const
9256 Returns the visible child widget at the position (\a{x}, \a{y})
9257 in the widget's coordinate system. If there is no visible child
9258 widget at the specified position, the function returns 0.
9264 Returns the visible child widget at point \a p in the widget's own
9268 QWidget *QWidget::childAt(const QPoint &p) const
9270 return d_func()->childAt_helper(p, false);
9273 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9275 if (children.isEmpty())
9280 // Unified tool bars on the Mac require special handling since they live outside
9281 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9282 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9283 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9285 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9288 if (!pointInsideRectAndMask(p))
9290 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9293 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9296 Q_UNUSED(includeFrame);
9298 for (int i = children.size() - 1; i >= 0; --i) {
9299 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9300 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9301 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9305 // Map the point 'p' from parent coordinates to child coordinates.
9306 QPoint childPoint = p;
9308 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9309 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9310 // QWidget::mapFromParent won't do the trick.
9311 if (includeFrame && qobject_cast<QToolBar *>(child))
9312 childPoint = qt_mac_nativeMapFromParent(child, p);
9315 childPoint -= child->data->crect.topLeft();
9317 // Check if the point hits the child.
9318 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9321 // Do the same for the child's descendants.
9322 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9325 // We have found our target; namely the child at position 'p'.
9331 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9335 widgetItem->invalidateSizeCache();
9337 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9338 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9339 if (parent->d_func()->layout)
9340 parent->d_func()->layout->invalidate();
9341 else if (parent->isVisible())
9342 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9348 Notifies the layout system that this widget has changed and may
9349 need to change geometry.
9351 Call this function if the sizeHint() or sizePolicy() have changed.
9353 For explicitly hidden widgets, updateGeometry() is a no-op. The
9354 layout system will be notified as soon as the widget is shown.
9357 void QWidget::updateGeometry()
9360 d->updateGeometry_helper(false);
9363 /*! \property QWidget::windowFlags
9365 Window flags are a combination of a type (e.g. Qt::Dialog) and
9366 zero or more hints to the window system (e.g.
9367 Qt::FramelessWindowHint).
9369 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9370 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9371 0) on the desktop. If the widget is a window and becomes a
9372 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9373 relative to its parent widget.
9375 \note This function calls setParent() when changing the flags for
9376 a window, causing the widget to be hidden. You must call show() to make
9377 the widget visible again..
9379 \sa windowType(), {Window Flags Example}
9381 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9383 if (data->window_flags == flags)
9388 if ((data->window_flags | flags) & Qt::Window) {
9389 // the old type was a window and/or the new type is a window
9390 QPoint oldPos = pos();
9391 bool visible = isVisible();
9392 setParent(parentWidget(), flags);
9394 // if both types are windows or neither of them are, we restore
9396 if (!((data->window_flags ^ flags) & Qt::Window)
9397 && (visible || testAttribute(Qt::WA_Moved))) {
9400 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9401 d->adjustQuitOnCloseAttribute();
9403 data->window_flags = flags;
9408 Sets the window flags for the widget to \a flags,
9409 \e without telling the window system.
9411 \warning Do not call this function unless you really know what
9414 \sa setWindowFlags()
9416 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9418 data->window_flags = flags;
9422 \fn Qt::WindowType QWidget::windowType() const
9424 Returns the window type of this widget. This is identical to
9425 windowFlags() & Qt::WindowType_Mask.
9431 Sets the parent of the widget to \a parent, and resets the window
9432 flags. The widget is moved to position (0, 0) in its new parent.
9434 If the new parent widget is in a different window, the
9435 reparented widget and its children are appended to the end of the
9436 \l{setFocusPolicy()}{tab chain} of the new parent
9437 widget, in the same internal order as before. If one of the moved
9438 widgets had keyboard focus, setParent() calls clearFocus() for that
9441 If the new parent widget is in the same window as the
9442 old parent, setting the parent doesn't change the tab order or
9445 If the "new" parent widget is the old parent widget, this function
9448 \note The widget becomes invisible as part of changing its parent,
9449 even if it was previously visible. You must call show() to make the
9450 widget visible again.
9452 \warning It is very unlikely that you will ever need this
9453 function. If you have a widget that changes its content
9454 dynamically, it is far easier to use \l QStackedWidget.
9456 \sa setWindowFlags()
9458 void QWidget::setParent(QWidget *parent)
9460 if (parent == parentWidget())
9462 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9468 This function also takes widget flags, \a f as an argument.
9471 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9474 d->inSetParent = true;
9475 bool resized = testAttribute(Qt::WA_Resized);
9476 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9477 QWidget *oldtlw = window();
9479 QWidget *desktopWidget = 0;
9480 if (parent && parent->windowType() == Qt::Desktop)
9481 desktopWidget = parent;
9482 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9484 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC)
9485 if (newParent && parent && !desktopWidget) {
9486 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9488 // On Mac, toolbars inside the unified title bar will never overlap with
9489 // siblings in the content view. So we skip enforce native siblings in that case
9490 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9493 parent->d_func()->enforceNativeChildren();
9494 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9495 setAttribute(Qt::WA_NativeWindow);
9500 if (!testAttribute(Qt::WA_WState_Hidden)) {
9502 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9505 QEvent e(QEvent::ParentAboutToChange);
9506 QApplication::sendEvent(this, &e);
9509 if (newParent && isAncestorOf(focusWidget()))
9510 focusWidget()->clearFocus();
9512 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9513 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9515 d->setParent_sys(parent, f);
9517 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9518 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9519 if (oldBsTracker && oldBsTracker != bsTracker)
9520 oldBsTracker->unregisterWidgetSubtree(this);
9525 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9527 oldBs->removeDirtyWidget(this);
9528 // Move the widget and all its static children from
9529 // the old backing store to the new one.
9530 oldBs->moveStaticWidgets(this);
9533 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9536 d->reparentFocusWidgets(oldtlw);
9537 setAttribute(Qt::WA_Resized, resized);
9538 if (!testAttribute(Qt::WA_StyleSheet)
9539 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9541 d->resolvePalette();
9543 d->resolveLayoutDirection();
9546 // Note: GL widgets under WGL or EGL will always need a ParentChange
9547 // event to handle recreation/rebinding of the GL context, hence the
9548 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9551 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9552 || (f & Qt::MSWindowsOwnDC)
9555 // propagate enabled updates enabled state to non-windows
9557 if (!testAttribute(Qt::WA_ForceDisabled))
9558 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9559 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9560 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9564 // send and post remaining QObject events
9565 if (parent && d->sendChildEvents) {
9566 QChildEvent e(QEvent::ChildAdded, this);
9567 QApplication::sendEvent(parent, &e);
9570 //### already hidden above ---> must probably do something smart on the mac
9572 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9573 // if(!qt_mac_is_macdrawer(q)) //special case
9574 // q->setAttribute(Qt::WA_WState_Hidden);
9576 // q->setAttribute(Qt::WA_WState_Hidden);
9579 if (parent && d->sendChildEvents && d->polished) {
9580 QChildEvent e(QEvent::ChildPolished, this);
9581 QCoreApplication::sendEvent(parent, &e);
9584 QEvent e(QEvent::ParentChange);
9585 QApplication::sendEvent(this, &e);
9589 if (isWindow() || parentWidget()->isVisible())
9590 setAttribute(Qt::WA_WState_Hidden, true);
9591 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9592 setAttribute(Qt::WA_WState_Hidden, false);
9595 d->updateIsOpaque();
9597 #ifndef QT_NO_GRAPHICSVIEW
9598 // Embed the widget into a proxy if the parent is embedded.
9599 // ### Doesn't handle reparenting out of an embedded widget.
9600 if (oldtlw->graphicsProxyWidget()) {
9601 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9602 ancestorProxy->d_func()->unembedSubWindow(this);
9604 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9605 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9606 ancestorProxy->d_func()->embedSubWindow(this);
9610 d->inSetParent = false;
9614 Scrolls the widget including its children \a dx pixels to the
9615 right and \a dy downward. Both \a dx and \a dy may be negative.
9617 After scrolling, the widgets will receive paint events for
9618 the areas that need to be repainted. For widgets that Qt knows to
9619 be opaque, this is only the newly exposed parts.
9620 For example, if an opaque widget is scrolled 8 pixels to the left,
9621 only an 8-pixel wide stripe at the right edge needs updating.
9623 Since widgets propagate the contents of their parents by default,
9624 you need to set the \l autoFillBackground property, or use
9625 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9628 For widgets that use contents propagation, a scroll will cause an
9629 update of the entire scroll area.
9631 \sa {Transparency and Double Buffering}
9634 void QWidget::scroll(int dx, int dy)
9636 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9638 if (dx == 0 && dy == 0)
9641 #ifndef QT_NO_GRAPHICSVIEW
9642 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9643 // Graphics View maintains its own dirty region as a list of rects;
9644 // until we can connect item updates directly to the view, we must
9645 // separately add a translated dirty region.
9646 if (!d->dirty.isEmpty()) {
9647 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9648 proxy->update(rect);
9650 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9654 d->setDirtyOpaqueRegion();
9655 d->scroll_sys(dx, dy);
9661 This version only scrolls \a r and does not move the children of
9664 If \a r is empty or invalid, the result is undefined.
9668 void QWidget::scroll(int dx, int dy, const QRect &r)
9671 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9673 if (dx == 0 && dy == 0)
9676 #ifndef QT_NO_GRAPHICSVIEW
9677 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9678 // Graphics View maintains its own dirty region as a list of rects;
9679 // until we can connect item updates directly to the view, we must
9680 // separately add a translated dirty region.
9681 if (!d->dirty.isEmpty()) {
9682 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9683 proxy->update(rect);
9685 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9689 d->scroll_sys(dx, dy, r);
9693 Repaints the widget directly by calling paintEvent() immediately,
9694 unless updates are disabled or the widget is hidden.
9696 We suggest only using repaint() if you need an immediate repaint,
9697 for example during animation. In almost all circumstances update()
9698 is better, as it permits Qt to optimize for speed and minimize
9701 \warning If you call repaint() in a function which may itself be
9702 called from paintEvent(), you may get infinite recursion. The
9703 update() function never causes recursion.
9705 \sa update(), paintEvent(), setUpdatesEnabled()
9708 void QWidget::repaint()
9715 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9718 If \a w is negative, it is replaced with \c{width() - x}, and if
9719 \a h is negative, it is replaced width \c{height() - y}.
9721 void QWidget::repaint(int x, int y, int w, int h)
9723 if (x > data->crect.width() || y > data->crect.height())
9727 w = data->crect.width() - x;
9729 h = data->crect.height() - y;
9731 repaint(QRect(x, y, w, h));
9736 This version repaints a rectangle \a rect inside the widget.
9738 void QWidget::repaint(const QRect &rect)
9742 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9747 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9750 if (hasBackingStoreSupport()) {
9752 if (qt_widget_private(this)->isInUnifiedToolbar) {
9753 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9757 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9758 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9759 tlwExtra->inRepaint = true;
9760 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9761 tlwExtra->inRepaint = false;
9764 d->repaint_sys(rect);
9771 This version repaints a region \a rgn inside the widget.
9773 void QWidget::repaint(const QRegion &rgn)
9777 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9782 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9785 if (hasBackingStoreSupport()) {
9787 if (qt_widget_private(this)->isInUnifiedToolbar) {
9788 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9792 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9793 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9794 tlwExtra->inRepaint = true;
9795 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9796 tlwExtra->inRepaint = false;
9799 d->repaint_sys(rgn);
9804 Updates the widget unless updates are disabled or the widget is
9807 This function does not cause an immediate repaint; instead it
9808 schedules a paint event for processing when Qt returns to the main
9809 event loop. This permits Qt to optimize for more speed and less
9810 flicker than a call to repaint() does.
9812 Calling update() several times normally results in just one
9815 Qt normally erases the widget's area before the paintEvent() call.
9816 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9817 responsible for painting all its pixels with an opaque color.
9819 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9821 void QWidget::update()
9826 /*! \fn void QWidget::update(int x, int y, int w, int h)
9829 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9836 This version updates a rectangle \a rect inside the widget.
9838 void QWidget::update(const QRect &rect)
9840 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9843 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9844 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9848 if (hasBackingStoreSupport()) {
9850 if (qt_widget_private(this)->isInUnifiedToolbar) {
9851 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9855 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9856 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9857 tlwExtra->backingStoreTracker->markDirty(rect, this);
9859 d_func()->repaint_sys(rect);
9866 This version repaints a region \a rgn inside the widget.
9868 void QWidget::update(const QRegion &rgn)
9870 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9873 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9874 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9878 if (hasBackingStoreSupport()) {
9880 if (qt_widget_private(this)->isInUnifiedToolbar) {
9881 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9885 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9886 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9887 tlwExtra->backingStoreTracker->markDirty(rgn, this);
9889 d_func()->repaint_sys(rgn);
9897 This just sets the corresponding attribute bit to 1 or 0
9899 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9902 if (attribute < int(8*sizeof(uint))) {
9904 data->widget_attributes |= (1<<attribute);
9906 data->widget_attributes &= ~(1<<attribute);
9908 const int x = attribute - 8*sizeof(uint);
9909 const int int_off = x / (8*sizeof(uint));
9911 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9913 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9918 Sets the attribute \a attribute on this widget if \a on is true;
9919 otherwise clears the attribute.
9923 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9925 if (testAttribute(attribute) == on)
9929 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9930 "QWidget::setAttribute(WidgetAttribute, bool)",
9931 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9933 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
9934 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
9935 // see qwidget_win.cpp, ::paintEngine for details
9937 if (d->noPaintOnScreen)
9942 setAttribute_internal(attribute, on, data, d);
9944 switch (attribute) {
9946 #ifndef QT_NO_DRAGANDDROP
9947 case Qt::WA_AcceptDrops: {
9948 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9949 setAttribute(Qt::WA_DropSiteRegistered, true);
9950 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9951 setAttribute(Qt::WA_DropSiteRegistered, false);
9952 QEvent e(QEvent::AcceptDropsChange);
9953 QApplication::sendEvent(this, &e);
9956 case Qt::WA_DropSiteRegistered: {
9957 d->registerDropSite(on);
9958 for (int i = 0; i < d->children.size(); ++i) {
9959 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9960 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9961 w->setAttribute(Qt::WA_DropSiteRegistered, on);
9967 case Qt::WA_NoChildEventsForParent:
9968 d->sendChildEvents = !on;
9970 case Qt::WA_NoChildEventsFromChildren:
9971 d->receiveChildEvents = !on;
9973 case Qt::WA_MacBrushedMetal:
9975 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
9976 // fall through since changing the metal attribute affects the opaque size grip.
9977 case Qt::WA_MacOpaqueSizeGrip:
9978 d->macUpdateOpaqueSizeGrip();
9980 case Qt::WA_MacShowFocusRect:
9987 qt_mac_update_mouseTracking(this);
9990 case Qt::WA_MacAlwaysShowToolWindow:
9992 d->macUpdateHideOnSuspend();
9995 case Qt::WA_MacNormalSize:
9996 case Qt::WA_MacSmallSize:
9997 case Qt::WA_MacMiniSize:
10000 // We can only have one of these set at a time
10001 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10002 Qt::WA_MacMiniSize };
10003 for (int i = 0; i < 3; ++i) {
10004 if (MacSizes[i] != attribute)
10005 setAttribute_internal(MacSizes[i], false, data, d);
10007 d->macUpdateSizeAttribute();
10011 case Qt::WA_ShowModal:
10014 QApplicationPrivate::leaveModal(this);
10015 // reset modality type to Modeless when clearing WA_ShowModal
10016 data->window_modality = Qt::NonModal;
10017 } else if (data->window_modality == Qt::NonModal) {
10018 // determine the modality type if it hasn't been set prior
10019 // to setting WA_ShowModal. set the default to WindowModal
10020 // if we are the child of a group leader; otherwise use
10021 // ApplicationModal.
10022 QWidget *w = parentWidget();
10025 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10026 w = w->parentWidget();
10030 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10032 : Qt::ApplicationModal;
10033 // Some window managers does not allow us to enter modal after the
10034 // window is showing. Therefore, to be consistent, we cannot call
10035 // QApplicationPrivate::enterModal(this) here. The window must be
10036 // hidden before changing modality.
10038 if (testAttribute(Qt::WA_WState_Created)) {
10039 // don't call setModal_sys() before create_sys()
10043 case Qt::WA_MouseTracking: {
10044 QEvent e(QEvent::MouseTrackingChange);
10045 QApplication::sendEvent(this, &e);
10047 case Qt::WA_NativeWindow: {
10048 d->createTLExtra();
10050 QWidget *focusWidget = d->effectiveFocusWidget();
10051 if (on && !internalWinId() && hasFocus()
10052 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10053 qApp->inputMethod()->reset();
10054 qApp->inputMethod()->update(Qt::ImEnabled);
10056 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10058 // On Mac, toolbars inside the unified title bar will never overlap with
10059 // siblings in the content view. So we skip enforce native siblings in that case
10060 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10063 parentWidget()->d_func()->enforceNativeChildren();
10064 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10066 if (isEnabled() && focusWidget->isEnabled()
10067 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10068 qApp->inputMethod()->update(Qt::ImEnabled);
10073 case Qt::WA_PaintOnScreen:
10074 d->updateIsOpaque();
10075 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10076 // Recreate the widget if it's already created as an alien widget and
10077 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10078 // So must their children.
10080 setAttribute(Qt::WA_NativeWindow);
10081 d->enforceNativeChildren();
10085 case Qt::WA_OpaquePaintEvent:
10086 d->updateIsOpaque();
10088 case Qt::WA_NoSystemBackground:
10089 d->updateIsOpaque();
10091 case Qt::WA_UpdatesDisabled:
10092 d->updateSystemBackground();
10094 case Qt::WA_TransparentForMouseEvents:
10096 d->macUpdateIgnoreMouseEvents();
10099 case Qt::WA_InputMethodEnabled: {
10101 if (qApp->focusObject() == this) {
10103 qApp->inputMethod()->reset();
10104 qApp->inputMethod()->update(Qt::ImEnabled);
10109 case Qt::WA_WindowPropagation:
10110 d->resolvePalette();
10112 d->resolveLocale();
10115 case Qt::WA_NoX11EventCompression:
10118 d->extra->compress_events = on;
10120 case Qt::WA_X11OpenGLOverlay:
10121 d->updateIsOpaque();
10123 case Qt::WA_X11DoNotAcceptFocus:
10124 if (testAttribute(Qt::WA_WState_Created))
10125 d->updateX11AcceptFocus();
10128 case Qt::WA_DontShowOnScreen: {
10129 if (on && isVisible()) {
10130 // Make sure we keep the current state and only hide the widget
10131 // from the desktop. show_sys will only update platform specific
10132 // attributes at this point.
10140 case Qt::WA_X11NetWmWindowTypeDesktop:
10141 case Qt::WA_X11NetWmWindowTypeDock:
10142 case Qt::WA_X11NetWmWindowTypeToolBar:
10143 case Qt::WA_X11NetWmWindowTypeMenu:
10144 case Qt::WA_X11NetWmWindowTypeUtility:
10145 case Qt::WA_X11NetWmWindowTypeSplash:
10146 case Qt::WA_X11NetWmWindowTypeDialog:
10147 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10148 case Qt::WA_X11NetWmWindowTypePopupMenu:
10149 case Qt::WA_X11NetWmWindowTypeToolTip:
10150 case Qt::WA_X11NetWmWindowTypeNotification:
10151 case Qt::WA_X11NetWmWindowTypeCombo:
10152 case Qt::WA_X11NetWmWindowTypeDND:
10153 if (testAttribute(Qt::WA_WState_Created))
10154 d->setNetWmWindowTypes();
10158 case Qt::WA_StaticContents:
10159 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10161 bs->addStaticWidget(this);
10163 bs->removeStaticWidget(this);
10166 case Qt::WA_TranslucentBackground:
10168 setAttribute(Qt::WA_NoSystemBackground);
10169 d->updateIsTranslucent();
10173 case Qt::WA_AcceptTouchEvents:
10174 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10176 d->registerTouchWindow();
10184 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10186 Returns true if attribute \a attribute is set on this widget;
10187 otherwise returns false.
10191 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10193 Q_D(const QWidget);
10194 const int x = attribute - 8*sizeof(uint);
10195 const int int_off = x / (8*sizeof(uint));
10196 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10200 \property QWidget::windowOpacity
10202 \brief The level of opacity for the window.
10204 The valid range of opacity is from 1.0 (completely opaque) to
10205 0.0 (completely transparent).
10207 By default the value of this property is 1.0.
10209 This feature is available on Embedded Linux, Mac OS X, Windows,
10210 and X11 platforms that support the Composite extension.
10212 This feature is not available on Windows CE.
10214 Note that under X11 you need to have a composite manager running,
10215 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10216 supported by the window manager you are using.
10218 \warning Changing this property from opaque to transparent might issue a
10219 paint event that needs to be processed before the window is displayed
10220 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10221 that semi-transparent windows update and resize significantly slower than
10226 qreal QWidget::windowOpacity() const
10228 Q_D(const QWidget);
10229 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10232 void QWidget::setWindowOpacity(qreal opacity)
10238 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10239 QTLWExtra *extra = d->topData();
10240 extra->opacity = uint(opacity * 255);
10241 setAttribute(Qt::WA_WState_WindowOpacitySet);
10243 if (!testAttribute(Qt::WA_WState_Created))
10246 #ifndef QT_NO_GRAPHICSVIEW
10247 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10248 // Avoid invalidating the cache if set.
10249 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10251 else if (QGraphicsScene *scene = proxy->scene())
10252 scene->update(proxy->sceneBoundingRect());
10257 d->setWindowOpacity_sys(opacity);
10261 \property QWidget::windowModified
10262 \brief whether the document shown in the window has unsaved changes
10264 A modified window is a window whose content has changed but has
10265 not been saved to disk. This flag will have different effects
10266 varied by the platform. On Mac OS X the close button will have a
10267 modified look; on other platforms, the window title will have an
10270 The window title must contain a "[*]" placeholder, which
10271 indicates where the '*' should appear. Normally, it should appear
10272 right after the file name (e.g., "document1.txt[*] - Text
10273 Editor"). If the window isn't modified, the placeholder is simply
10276 Note that if a widget is set as modified, all its ancestors will
10277 also be set as modified. However, if you call \c
10278 {setWindowModified(false)} on a widget, this will not propagate to
10279 its parent because other children of the parent might have been
10282 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10284 bool QWidget::isWindowModified() const
10286 return testAttribute(Qt::WA_WindowModified);
10289 void QWidget::setWindowModified(bool mod)
10292 setAttribute(Qt::WA_WindowModified, mod);
10295 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10296 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10298 d->setWindowTitle_helper(windowTitle());
10299 d->setWindowIconText_helper(windowIconText());
10301 d->setWindowModified_sys(mod);
10304 QEvent e(QEvent::ModifiedChange);
10305 QApplication::sendEvent(this, &e);
10308 #ifndef QT_NO_TOOLTIP
10310 \property QWidget::toolTip
10312 \brief the widget's tooltip
10314 Note that by default tooltips are only shown for widgets that are
10315 children of the active window. You can change this behavior by
10316 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10317 not on the widget with the tooltip.
10319 If you want to control a tooltip's behavior, you can intercept the
10320 event() function and catch the QEvent::ToolTip event (e.g., if you
10321 want to customize the area for which the tooltip should be shown).
10323 By default, this property contains an empty string.
10325 \sa QToolTip statusTip whatsThis
10327 void QWidget::setToolTip(const QString &s)
10332 QEvent event(QEvent::ToolTipChange);
10333 QApplication::sendEvent(this, &event);
10336 QString QWidget::toolTip() const
10338 Q_D(const QWidget);
10341 #endif // QT_NO_TOOLTIP
10344 #ifndef QT_NO_STATUSTIP
10346 \property QWidget::statusTip
10347 \brief the widget's status tip
10349 By default, this property contains an empty string.
10351 \sa toolTip whatsThis
10353 void QWidget::setStatusTip(const QString &s)
10359 QString QWidget::statusTip() const
10361 Q_D(const QWidget);
10362 return d->statusTip;
10364 #endif // QT_NO_STATUSTIP
10366 #ifndef QT_NO_WHATSTHIS
10368 \property QWidget::whatsThis
10370 \brief the widget's What's This help text.
10372 By default, this property contains an empty string.
10374 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10376 void QWidget::setWhatsThis(const QString &s)
10382 QString QWidget::whatsThis() const
10384 Q_D(const QWidget);
10385 return d->whatsThis;
10387 #endif // QT_NO_WHATSTHIS
10389 #ifndef QT_NO_ACCESSIBILITY
10391 \property QWidget::accessibleName
10393 \brief the widget's name as seen by assistive technologies
10395 This property is used by accessible clients to identify, find, or announce
10396 the widget for accessible clients.
10398 By default, this property contains an empty string.
10400 \sa QAccessibleInterface::text()
10402 void QWidget::setAccessibleName(const QString &name)
10405 d->accessibleName = name;
10406 QAccessibleEvent event(QAccessible::NameChanged, this);
10407 QAccessible::updateAccessibility(&event);
10410 QString QWidget::accessibleName() const
10412 Q_D(const QWidget);
10413 return d->accessibleName;
10417 \property QWidget::accessibleDescription
10419 \brief the widget's description as seen by assistive technologies
10421 By default, this property contains an empty string.
10423 \sa QAccessibleInterface::text()
10425 void QWidget::setAccessibleDescription(const QString &description)
10428 d->accessibleDescription = description;
10429 QAccessibleEvent event(QAccessible::DescriptionChanged, this);
10430 QAccessible::updateAccessibility(&event);
10433 QString QWidget::accessibleDescription() const
10435 Q_D(const QWidget);
10436 return d->accessibleDescription;
10438 #endif // QT_NO_ACCESSIBILITY
10440 #ifndef QT_NO_SHORTCUT
10442 Adds a shortcut to Qt's shortcut system that watches for the given
10443 \a key sequence in the given \a context. If the \a context is
10444 Qt::ApplicationShortcut, the shortcut applies to the application as a
10445 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10446 or to the window itself, Qt::WindowShortcut.
10448 If the same \a key sequence has been grabbed by several widgets,
10449 when the \a key sequence occurs a QEvent::Shortcut event is sent
10450 to all the widgets to which it applies in a non-deterministic
10451 order, but with the ``ambiguous'' flag set to true.
10453 \warning You should not normally need to use this function;
10454 instead create \l{QAction}s with the shortcut key sequences you
10455 require (if you also want equivalent menu options and toolbar
10456 buttons), or create \l{QShortcut}s if you just need key sequences.
10457 Both QAction and QShortcut handle all the event filtering for you,
10458 and provide signals which are triggered when the user triggers the
10459 key sequence, so are much easier to use than this low-level
10462 \sa releaseShortcut() setShortcutEnabled()
10464 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10469 setAttribute(Qt::WA_GrabbedShortcut);
10470 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10474 Removes the shortcut with the given \a id from Qt's shortcut
10475 system. The widget will no longer receive QEvent::Shortcut events
10476 for the shortcut's key sequence (unless it has other shortcuts
10477 with the same key sequence).
10479 \warning You should not normally need to use this function since
10480 Qt's shortcut system removes shortcuts automatically when their
10481 parent widget is destroyed. It is best to use QAction or
10482 QShortcut to handle shortcuts, since they are easier to use than
10483 this low-level function. Note also that this is an expensive
10486 \sa grabShortcut() setShortcutEnabled()
10488 void QWidget::releaseShortcut(int id)
10492 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10496 If \a enable is true, the shortcut with the given \a id is
10497 enabled; otherwise the shortcut is disabled.
10499 \warning You should not normally need to use this function since
10500 Qt's shortcut system enables/disables shortcuts automatically as
10501 widgets become hidden/visible and gain or lose focus. It is best
10502 to use QAction or QShortcut to handle shortcuts, since they are
10503 easier to use than this low-level function.
10505 \sa grabShortcut() releaseShortcut()
10507 void QWidget::setShortcutEnabled(int id, bool enable)
10511 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10517 If \a enable is true, auto repeat of the shortcut with the
10518 given \a id is enabled; otherwise it is disabled.
10520 \sa grabShortcut() releaseShortcut()
10522 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10526 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10528 #endif // QT_NO_SHORTCUT
10531 Updates the widget's micro focus.
10533 void QWidget::updateMicroFocus()
10535 // updating everything since this is currently called for any kind of state change
10536 qApp->inputMethod()->update(Qt::ImQueryAll);
10540 Raises this widget to the top of the parent widget's stack.
10542 After this call the widget will be visually in front of any
10543 overlapping sibling widgets.
10545 \note When using activateWindow(), you can call this function to
10546 ensure that the window is stacked on top.
10548 \sa lower(), stackUnder()
10551 void QWidget::raise()
10555 QWidget *p = parentWidget();
10556 const int parentChildCount = p->d_func()->children.size();
10557 if (parentChildCount < 2)
10559 const int from = p->d_func()->children.indexOf(this);
10560 Q_ASSERT(from >= 0);
10561 // Do nothing if the widget is already in correct stacking order _and_ created.
10562 if (from != parentChildCount -1)
10563 p->d_func()->children.move(from, parentChildCount - 1);
10564 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10566 else if (from == parentChildCount - 1)
10569 QRegion region(rect());
10570 d->subtractOpaqueSiblings(region);
10571 d->invalidateBuffer(region);
10573 if (testAttribute(Qt::WA_WState_Created))
10576 QEvent e(QEvent::ZOrderChange);
10577 QApplication::sendEvent(this, &e);
10581 Lowers the widget to the bottom of the parent widget's stack.
10583 After this call the widget will be visually behind (and therefore
10584 obscured by) any overlapping sibling widgets.
10586 \sa raise(), stackUnder()
10589 void QWidget::lower()
10593 QWidget *p = parentWidget();
10594 const int parentChildCount = p->d_func()->children.size();
10595 if (parentChildCount < 2)
10597 const int from = p->d_func()->children.indexOf(this);
10598 Q_ASSERT(from >= 0);
10599 // Do nothing if the widget is already in correct stacking order _and_ created.
10601 p->d_func()->children.move(from, 0);
10602 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10604 else if (from == 0)
10607 if (testAttribute(Qt::WA_WState_Created))
10610 QEvent e(QEvent::ZOrderChange);
10611 QApplication::sendEvent(this, &e);
10616 Places the widget under \a w in the parent widget's stack.
10618 To make this work, the widget itself and \a w must be siblings.
10620 \sa raise(), lower()
10622 void QWidget::stackUnder(QWidget* w)
10625 QWidget *p = parentWidget();
10626 if (!w || isWindow() || p != w->parentWidget() || this == w)
10629 int from = p->d_func()->children.indexOf(this);
10630 int to = p->d_func()->children.indexOf(w);
10631 Q_ASSERT(from >= 0);
10635 // Do nothing if the widget is already in correct stacking order _and_ created.
10637 p->d_func()->children.move(from, to);
10638 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10640 else if (from == to)
10643 if (testAttribute(Qt::WA_WState_Created))
10644 d->stackUnder_sys(w);
10646 QEvent e(QEvent::ZOrderChange);
10647 QApplication::sendEvent(this, &e);
10652 \fn bool QWidget::isTopLevel() const
10655 Use isWindow() instead.
10659 \fn bool QWidget::isRightToLeft() const
10664 \fn bool QWidget::isLeftToRight() const
10669 \macro QWIDGETSIZE_MAX
10672 Defines the maximum size for a QWidget object.
10674 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10675 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10677 \sa QWidget::setMaximumSize()
10681 \fn QWidget::setupUi(QWidget *widget)
10683 Sets up the user interface for the specified \a widget.
10685 \note This function is available with widgets that derive from user
10686 interface descriptions created using \l{uic}.
10688 \sa {Using a Designer UI File in Your Application}
10691 QRect QWidgetPrivate::frameStrut() const
10693 Q_Q(const QWidget);
10694 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10695 // x2 = x1 + w - 1, so w/h = 1
10696 return QRect(0, 0, 1, 1);
10699 if (data.fstrut_dirty
10701 // ### Fix properly for 4.3
10704 && q->testAttribute(Qt::WA_WState_Created))
10705 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10707 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10710 #ifdef QT_KEYPAD_NAVIGATION
10714 Changes the focus from the current focusWidget to a widget in
10717 Returns true, if there was a widget in that direction
10719 bool QWidgetPrivate::navigateToDirection(Direction direction)
10721 QWidget *targetWidget = widgetInNavigationDirection(direction);
10723 targetWidget->setFocus();
10724 return (targetWidget != 0);
10730 Searches for a widget that is positioned in the \a direction, starting
10731 from the current focusWidget.
10733 Returns the pointer to a found widget or 0, if there was no widget in
10736 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10738 const QWidget *sourceWidget = QApplication::focusWidget();
10741 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10742 const int sourceX =
10743 (direction == DirectionNorth || direction == DirectionSouth) ?
10744 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10745 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10746 const int sourceY =
10747 (direction == DirectionEast || direction == DirectionWest) ?
10748 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10749 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10750 const QPoint sourcePoint(sourceX, sourceY);
10751 const QPoint sourceCenter = sourceRect.center();
10752 const QWidget *sourceWindow = sourceWidget->window();
10754 QWidget *targetWidget = 0;
10755 int shortestDistance = INT_MAX;
10756 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10758 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10760 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10761 // but the owner of the proxy cannot.
10762 // Additionally, empty widgets should be ignored.
10763 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10766 // Only navigate to a target widget that...
10767 if ( targetCandidate != sourceWidget
10768 // ...takes the focus,
10769 && targetCandidate->focusPolicy() & Qt::TabFocus
10770 // ...is above if DirectionNorth,
10771 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10772 // ...is on the right if DirectionEast,
10773 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
10774 // ...is below if DirectionSouth,
10775 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
10776 // ...is on the left if DirectionWest,
10777 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
10779 && targetCandidate->isEnabled()
10781 && targetCandidate->isVisible()
10782 // ...is in the same window,
10783 && targetCandidate->window() == sourceWindow) {
10784 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10785 if (targetCandidateDistance < shortestDistance) {
10786 shortestDistance = targetCandidateDistance;
10787 targetWidget = targetCandidate;
10791 return targetWidget;
10797 Tells us if it there is currently a reachable widget by keypad navigation in
10798 a certain \a orientation.
10799 If no navigation is possible, occurring key events in that \a orientation may
10800 be used to interact with the value in the focused widget, even though it
10801 currently has not the editFocus.
10803 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10805 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10807 return orientation == Qt::Horizontal?
10808 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10809 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10810 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10811 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10816 Checks, if the \a widget is inside a QTabWidget. If is is inside
10817 one, left/right key events will be used to switch between tabs in keypad
10818 navigation. If there is no QTabWidget, the horizontal key events can be used
10820 interact with the value in the focused widget, even though it currently has
10823 \sa QWidget::hasEditFocus()
10825 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10827 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10828 if (qobject_cast<const QTabWidget*>(tabWidget))
10838 Sets the backing store to be the \a store specified.
10839 The QWidget will take ownership of the \a store.
10841 void QWidget::setBackingStore(QBackingStore *store)
10843 // ### createWinId() ??
10850 QTLWExtra *topData = d->topData();
10851 if (topData->backingStore == store)
10854 QBackingStore *oldStore = topData->backingStore;
10855 delete topData->backingStore;
10856 topData->backingStore = store;
10858 QWidgetBackingStore *bs = d->maybeBackingStore();
10862 if (isTopLevel()) {
10863 if (bs->store != oldStore && bs->store != store)
10872 Returns the QBackingStore this widget will be drawn into.
10874 QBackingStore *QWidget::backingStore() const
10876 Q_D(const QWidget);
10877 QTLWExtra *extra = d->maybeTopData();
10878 if (extra && extra->backingStore)
10879 return extra->backingStore;
10881 QWidgetBackingStore *bs = d->maybeBackingStore();
10883 return bs ? bs->store : 0;
10886 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10889 *left = (int)leftLayoutItemMargin;
10891 *top = (int)topLayoutItemMargin;
10893 *right = (int)rightLayoutItemMargin;
10895 *bottom = (int)bottomLayoutItemMargin;
10898 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10900 if (leftLayoutItemMargin == left
10901 && topLayoutItemMargin == top
10902 && rightLayoutItemMargin == right
10903 && bottomLayoutItemMargin == bottom)
10907 leftLayoutItemMargin = (signed char)left;
10908 topLayoutItemMargin = (signed char)top;
10909 rightLayoutItemMargin = (signed char)right;
10910 bottomLayoutItemMargin = (signed char)bottom;
10911 q->updateGeometry();
10914 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10917 QStyleOption myOpt;
10920 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
10924 QRect liRect = q->style()->subElementRect(element, opt, q);
10925 if (liRect.isValid()) {
10926 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10927 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10928 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10929 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10931 leftLayoutItemMargin = 0;
10932 topLayoutItemMargin = 0;
10933 rightLayoutItemMargin = 0;
10934 bottomLayoutItemMargin = 0;
10937 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10938 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10942 if (!q->parentWidget()) {
10943 Qt::WindowType type = q->windowType();
10944 if (type == Qt::Widget || type == Qt::SubWindow)
10946 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10947 q->setAttribute(Qt::WA_QuitOnClose, false);
10953 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10955 return widget->data;
10958 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10960 return widget->d_func();
10964 #ifndef QT_NO_GRAPHICSVIEW
10968 Returns the proxy widget for the corresponding embedded widget in a graphics
10969 view; otherwise returns 0.
10971 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
10972 QGraphicsScene::addWidget()
10974 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
10976 Q_D(const QWidget);
10978 return d->extra->proxyWidget;
10986 \typedef QWidgetList
10989 Synonym for QList<QWidget *>.
10992 #ifndef QT_NO_GESTURES
10994 Subscribes the widget to a given \a gesture with specific \a flags.
10996 \sa ungrabGesture(), QGestureEvent
10999 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11002 d->gestureContext.insert(gesture, flags);
11003 (void)QGestureManager::instance(); // create a gesture manager
11007 Unsubscribes the widget from a given \a gesture type
11009 \sa grabGesture(), QGestureEvent
11012 void QWidget::ungrabGesture(Qt::GestureType gesture)
11015 if (d->gestureContext.remove(gesture)) {
11016 if (QGestureManager *manager = QGestureManager::instance())
11017 manager->cleanupCachedGestures(this, gesture);
11020 #endif // QT_NO_GESTURES
11026 Platform dependent window identifier.
11030 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11032 Frees up window system resources. Destroys the widget window if \a
11033 destroyWindow is true.
11035 destroy() calls itself recursively for all the child widgets,
11036 passing \a destroySubWindows for the \a destroyWindow parameter.
11037 To have more control over destruction of subwidgets, destroy
11038 subwidgets selectively first.
11040 This function is usually called from the QWidget destructor.
11044 \fn QPaintEngine *QWidget::paintEngine() const
11046 Returns the widget's paint engine.
11048 Note that this function should not be called explicitly by the
11049 user, since it's meant for reimplementation purposes only. The
11050 function is called by Qt internally, and the default
11051 implementation may not always return a valid pointer.
11055 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11057 Translates the widget coordinate \a pos to global screen
11058 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11059 the global coordinates of the top-left pixel of the widget.
11061 \sa mapFromGlobal() mapTo() mapToParent()
11065 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11067 Translates the global screen coordinate \a pos to widget
11070 \sa mapToGlobal() mapFrom() mapFromParent()
11074 \fn void QWidget::grabMouse()
11076 Grabs the mouse input.
11078 This widget receives all mouse events until releaseMouse() is
11079 called; other widgets get no mouse events at all. Keyboard
11080 events are not affected. Use grabKeyboard() if you want to grab
11083 \warning Bugs in mouse-grabbing applications very often lock the
11084 terminal. Use this function with extreme caution, and consider
11085 using the \c -nograb command line option while debugging.
11087 It is almost never necessary to grab the mouse when using Qt, as
11088 Qt grabs and releases it sensibly. In particular, Qt grabs the
11089 mouse when a mouse button is pressed and keeps it until the last
11090 button is released.
11092 \note Only visible widgets can grab mouse input. If isVisible()
11093 returns false for a widget, that widget cannot call grabMouse().
11095 \note \b{(Mac OS X developers)} For \e Cocoa, calling
11096 grabMouse() on a widget only works when the mouse is inside the
11097 frame of that widget. For \e Carbon, it works outside the widget's
11098 frame as well, like for Windows and X11.
11100 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11104 \fn void QWidget::grabMouse(const QCursor &cursor)
11105 \overload grabMouse()
11107 Grabs the mouse input and changes the cursor shape.
11109 The cursor will assume shape \a cursor (for as long as the mouse
11110 focus is grabbed) and this widget will be the only one to receive
11111 mouse events until releaseMouse() is called().
11113 \warning Grabbing the mouse might lock the terminal.
11115 \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11117 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11121 \fn void QWidget::releaseMouse()
11123 Releases the mouse grab.
11125 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11129 \fn void QWidget::grabKeyboard()
11131 Grabs the keyboard input.
11133 This widget receives all keyboard events until releaseKeyboard()
11134 is called; other widgets get no keyboard events at all. Mouse
11135 events are not affected. Use grabMouse() if you want to grab that.
11137 The focus widget is not affected, except that it doesn't receive
11138 any keyboard events. setFocus() moves the focus as usual, but the
11139 new focus widget receives keyboard events only after
11140 releaseKeyboard() is called.
11142 If a different widget is currently grabbing keyboard input, that
11143 widget's grab is released first.
11145 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11149 \fn void QWidget::releaseKeyboard()
11151 Releases the keyboard grab.
11153 \sa grabKeyboard(), grabMouse(), releaseMouse()
11157 \fn QWidget *QWidget::mouseGrabber()
11159 Returns the widget that is currently grabbing the mouse input.
11161 If no widget in this application is currently grabbing the mouse,
11164 \sa grabMouse(), keyboardGrabber()
11168 \fn QWidget *QWidget::keyboardGrabber()
11170 Returns the widget that is currently grabbing the keyboard input.
11172 If no widget in this application is currently grabbing the
11173 keyboard, 0 is returned.
11175 \sa grabMouse(), mouseGrabber()
11179 \fn void QWidget::activateWindow()
11181 Sets the top-level widget containing this widget to be the active
11184 An active window is a visible top-level window that has the
11185 keyboard input focus.
11187 This function performs the same operation as clicking the mouse on
11188 the title bar of a top-level window. On X11, the result depends on
11189 the Window Manager. If you want to ensure that the window is
11190 stacked on top as well you should also call raise(). Note that the
11191 window must be visible, otherwise activateWindow() has no effect.
11193 On Windows, if you are calling this when the application is not
11194 currently the active one then it will not make it the active
11195 window. It will change the color of the taskbar entry to indicate
11196 that the window has changed in some way. This is because Microsoft
11197 does not allow an application to interrupt what the user is currently
11198 doing in another application.
11200 \sa isActiveWindow(), window(), show()
11204 \fn int QWidget::metric(PaintDeviceMetric m) const
11206 Internal implementation of the virtual QPaintDevice::metric()
11209 \a m is the metric to get.
11212 void QWidget::init(QPainter *painter) const
11214 const QPalette &pal = palette();
11215 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11216 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11217 QFont f(font(), const_cast<QWidget *>(this));
11218 painter->d_func()->state->deviceFont = f;
11219 painter->d_func()->state->font = f;
11222 QPaintDevice *QWidget::redirected(QPoint *offset) const
11224 return d_func()->redirected(offset);
11227 QPainter *QWidget::sharedPainter() const
11229 // Someone sent a paint event directly to the widget
11230 if (!d_func()->redirectDev)
11233 QPainter *sp = d_func()->sharedPainter();
11234 if (!sp || !sp->isActive())
11237 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11244 \fn void QWidget::setMask(const QRegion ®ion)
11247 Causes only the parts of the widget which overlap \a region to be
11248 visible. If the region includes pixels outside the rect() of the
11249 widget, window system controls in that area may or may not be
11250 visible, depending on the platform.
11252 Note that this effect can be slow if the region is particularly
11257 void QWidget::setMask(const QRegion &newMask)
11262 if (newMask == d->extra->mask)
11265 #ifndef QT_NO_BACKINGSTORE
11266 const QRegion oldMask(d->extra->mask);
11269 d->extra->mask = newMask;
11270 d->extra->hasMask = !newMask.isEmpty();
11273 if (!testAttribute(Qt::WA_WState_Created))
11277 d->setMask_sys(newMask);
11279 #ifndef QT_NO_BACKINGSTORE
11283 if (!d->extra->hasMask) {
11284 // Mask was cleared; update newly exposed area.
11285 QRegion expose(rect());
11287 if (!expose.isEmpty()) {
11288 d->setDirtyOpaqueRegion();
11295 // Update newly exposed area on the parent widget.
11296 QRegion parentExpose(rect());
11297 parentExpose -= newMask;
11298 if (!parentExpose.isEmpty()) {
11299 d->setDirtyOpaqueRegion();
11300 parentExpose.translate(data->crect.topLeft());
11301 parentWidget()->update(parentExpose);
11304 // Update newly exposed area on this widget
11305 if (!oldMask.isEmpty())
11306 update(newMask - oldMask);
11312 \fn void QWidget::setMask(const QBitmap &bitmap)
11314 Causes only the pixels of the widget for which \a bitmap has a
11315 corresponding 1 bit to be visible. If the region includes pixels
11316 outside the rect() of the widget, window system controls in that
11317 area may or may not be visible, depending on the platform.
11319 Note that this effect can be slow if the region is particularly
11322 The following code shows how an image with an alpha channel can be
11323 used to generate a mask for a widget:
11325 \snippet doc/src/snippets/widget-mask/main.cpp 0
11327 The label shown by this code is masked using the image it contains,
11328 giving the appearance that an irregularly-shaped image is being drawn
11329 directly onto the screen.
11331 Masked widgets receive mouse events only on their visible
11334 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11336 void QWidget::setMask(const QBitmap &bitmap)
11338 setMask(QRegion(bitmap));
11342 \fn void QWidget::clearMask()
11344 Removes any mask set by setMask().
11348 void QWidget::clearMask()
11350 setMask(QRegion());
11353 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11354 Returns the X11 Picture handle of the widget for XRender
11355 support. Use of this function is not portable. This function will
11356 return 0 if XRender support is not compiled into Qt, if the
11357 XRender extension is not supported on the X11 display, or if the
11358 handle could not be created.
11362 void QWidgetPrivate::syncUnifiedMode() {
11363 // The whole purpose of this method is to keep the unifiedToolbar in sync.
11364 // That means making sure we either exchange the drawing methods or we let
11365 // the toolbar know that it does not require to draw the baseline.
11367 // This function makes sense only if this is a top level
11370 OSWindowRef window = qt_mac_window_for(q);
11371 if(changeMethods) {
11372 // Ok, we are in documentMode.
11373 if(originalDrawMethod)
11374 qt_mac_replaceDrawRect(window, this);
11376 if(!originalDrawMethod)
11377 qt_mac_replaceDrawRectOriginal(window, this);
11385 #include "moc_qwidget.cpp"