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_windows.h"
67 # include "qt_mac_p.h"
68 # include "qt_cocoa_helpers_mac_p.h"
69 # include "qmainwindow.h"
70 # include "qtoolbar.h"
71 # include <private/qmainwindowlayout_p.h>
73 #include "qplatformwindow_qpa.h"
74 #include "private/qwidgetwindow_qpa_p.h"
77 #include "qwhatsthis.h"
79 #include "private/qstylesheetstyle_p.h"
80 #include "private/qstyle_p.h"
81 #include "qinputcontext.h"
82 #include "qfileinfo.h"
83 #include "private/qsoftkeymanager_p.h"
84 #include <QtGui/qinputpanel.h>
86 #include <private/qgraphicseffect_p.h>
87 #include <qbackingstore.h>
88 #include <private/qwidgetbackingstore_p.h>
90 # include <private/qpaintengine_mac_p.h>
92 #include <private/qpaintengine_raster_p.h>
94 #include "qwidget_p.h"
95 #include "qaction_p.h"
96 #include "qlayout_p.h"
97 #include "QtWidgets/qgraphicsproxywidget.h"
98 #include "QtWidgets/qgraphicsscene.h"
99 #include "private/qgraphicsproxywidget_p.h"
100 #include "QtWidgets/qabstractscrollarea.h"
101 #include "private/qabstractscrollarea_p.h"
102 #include "private/qevent_p.h"
104 #include "private/qgesturemanager_p.h"
106 #ifdef QT_KEYPAD_NAVIGATION
107 #include "qtabwidget.h" // Needed in inTabWidget()
108 #endif // QT_KEYPAD_NAVIGATION
111 #include <aknappui.h>
114 // widget/widget data creation count
115 //#define QWIDGET_EXTRA_DEBUG
116 //#define ALIEN_DEBUG
120 static bool qt_enable_backingstore = true;
122 // for compatibility with Qt 4.0
123 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
125 qt_enable_backingstore = enable;
130 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
133 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
135 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
136 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
139 static inline bool hasBackingStoreSupport()
145 # define QT_NO_PAINT_DEBUG
148 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
149 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
153 \class QWidgetBackingStoreTracker
154 \brief Class which allows tracking of which widgets are using a given backing store
156 QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
157 which maintains a list of the QWidgets which are currently using the backing
158 store. This list is modified via the registerWidget and unregisterWidget functions.
161 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
167 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
174 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
175 widgets using the backing store, then create a new QWidgetBackingStore, providing
178 void QWidgetBackingStoreTracker::create(QWidget *widget)
181 m_ptr = new QWidgetBackingStore(widget);
186 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
187 widgets using the backing store.
189 void QWidgetBackingStoreTracker::destroy()
198 Add the widget to the list of widgets currently using the backing store.
199 If the widget was already in the list, this function is a no-op.
201 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
204 Q_ASSERT(w->internalWinId());
205 Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
211 Remove the widget from the list of widgets currently using the backing store.
212 If the widget was in the list, and removing it causes the list to be empty,
213 the backing store is deleted.
214 If the widget was not in the list, this function is a no-op.
216 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
218 if (m_widgets.remove(w) && m_widgets.isEmpty()) {
226 Recursively remove widget and all of its descendents.
228 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
230 unregisterWidget(widget);
231 foreach (QObject *child, widget->children())
232 if (QWidget *childWidget = qobject_cast<QWidget *>(child))
233 unregisterWidgetSubtree(childWidget);
236 QWidgetPrivate::QWidgetPrivate(int version)
237 : QObjectPrivate(version)
246 , extraPaintEngine(0)
249 #if !defined(QT_NO_IM)
250 , imHints(Qt::ImhNone)
252 , inheritedFontResolveMask(0)
253 , inheritedPaletteResolveMask(0)
258 , leftLayoutItemMargin(0)
259 , topLayoutItemMargin(0)
260 , rightLayoutItemMargin(0)
261 , bottomLayoutItemMargin(0)
263 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
264 , fg_role(QPalette::NoRole)
265 , bg_role(QPalette::NoRole)
266 , dirtyOpaqueChildren(1)
272 , usesDoubleBufferedGLContext(0)
274 , inheritsInputMethodHints(0)
277 #if defined(Q_WS_X11)
279 #elif defined(Q_WS_WIN)
281 #ifndef QT_NO_GESTURES
282 , nativeGesturePanEnabled(0)
284 #elif defined(Q_WS_MAC)
285 , needWindowChange(0)
291 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
295 if (version != QObjectPrivateVersion)
296 qFatal("Cannot mix incompatible Qt libraries");
299 memset(high_attributes, 0, sizeof(high_attributes));
301 drawRectOriginalAdded = false;
302 originalDrawMethod = true;
303 changeMethods = false;
304 isInUnifiedToolbar = false;
306 toolbar_ancestor = 0;
307 flushRequested = false;
308 touchEventsEnabled = false;
310 #ifdef QWIDGET_EXTRA_DEBUG
311 static int count = 0;
312 qDebug() << "widgets" << ++count;
317 QWidgetPrivate::~QWidgetPrivate()
325 #ifndef QT_NO_GRAPHICSEFFECT
326 delete graphicsEffect;
327 #endif //QT_NO_GRAPHICSEFFECT
333 void QWidgetPrivate::scrollChildren(int dx, int dy)
336 if (q->children().size() > 0) { // scroll children
338 QObjectList childObjects = q->children();
339 for (int i = 0; i < childObjects.size(); ++i) { // move all children
340 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
341 if (w && !w->isWindow()) {
342 QPoint oldp = w->pos();
343 QRect r(w->pos() + pd, w->size());
345 if (w->testAttribute(Qt::WA_WState_Created))
346 w->d_func()->setWSGeometry();
347 w->d_func()->setDirtyOpaqueRegion();
348 QMoveEvent e(r.topLeft(), oldp);
349 QApplication::sendEvent(w, &e);
355 void QWidgetPrivate::updateWidgetTransform()
358 if (q == qGuiApp->focusObject()) {
360 QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
361 t.translate(p.x(), p.y());
362 qApp->inputPanel()->setInputItemTransform(t);
367 This function returns the QInputContext for this widget. By
368 default the input context is inherited from the widgets
369 parent. For toplevels it is inherited from QApplication.
371 You can override this and set a special input context for this
372 widget by using the setInputContext() method.
374 \sa setInputContext()
376 QInputContext *QWidget::inputContext()
378 if (!testAttribute(Qt::WA_InputMethodEnabled))
381 return qApp->inputContext();
384 #ifdef QT_KEYPAD_NAVIGATION
385 QPointer<QWidget> QWidgetPrivate::editingWidget;
388 Returns true if this widget currently has edit focus; otherwise false.
390 This feature is only available in Qt for Embedded Linux.
392 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
394 bool QWidget::hasEditFocus() const
396 const QWidget* w = this;
397 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
398 w = w->d_func()->extra->focus_proxy;
399 return QWidgetPrivate::editingWidget == w;
403 \fn void QWidget::setEditFocus(bool enable)
405 If \a enable is true, make this widget have edit focus, in which
406 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
407 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
410 This feature is only available in Qt for Embedded Linux and Qt
413 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
415 void QWidget::setEditFocus(bool on)
418 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
419 f = f->d_func()->extra->focus_proxy;
421 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
422 QWidgetPrivate::editingWidget->setEditFocus(false);
424 if (on && !f->hasFocus())
427 if ((!on && !QWidgetPrivate::editingWidget)
428 || (on && QWidgetPrivate::editingWidget == f)) {
432 if (!on && QWidgetPrivate::editingWidget == f) {
433 QWidgetPrivate::editingWidget = 0;
434 QEvent event(QEvent::LeaveEditFocus);
435 QApplication::sendEvent(f, &event);
436 QApplication::sendEvent(f->style(), &event);
438 QWidgetPrivate::editingWidget = f;
439 QEvent event(QEvent::EnterEditFocus);
440 QApplication::sendEvent(f, &event);
441 QApplication::sendEvent(f->style(), &event);
447 \property QWidget::autoFillBackground
448 \brief whether the widget background is filled automatically
451 If enabled, this property will cause Qt to fill the background of the
452 widget before invoking the paint event. The color used is defined by the
453 QPalette::Window color role from the widget's \l{QPalette}{palette}.
455 In addition, Windows are always filled with QPalette::Window, unless the
456 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
458 This property cannot be turned off (i.e., set to false) if a widget's
459 parent has a static gradient for its background.
461 \warning Use this property with caution in conjunction with
462 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
463 background or a border-image, this property is automatically disabled.
465 By default, this property is false.
467 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
468 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
470 bool QWidget::autoFillBackground() const
473 return d->extra && d->extra->autoFillBackground;
476 void QWidget::setAutoFillBackground(bool enabled)
481 if (d->extra->autoFillBackground == enabled)
484 d->extra->autoFillBackground = enabled;
492 \brief The QWidget class is the base class of all user interface objects.
494 \ingroup basicwidgets
497 The widget is the atom of the user interface: it receives mouse, keyboard
498 and other events from the window system, and paints a representation of
499 itself on the screen. Every widget is rectangular, and they are sorted in a
500 Z-order. A widget is clipped by its parent and by the widgets in front of
503 A widget that is not embedded in a parent widget is called a window.
504 Usually, windows have a frame and a title bar, although it is also possible
505 to create windows without such decoration using suitable
506 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
507 subclasses of QDialog are the most common window types.
509 Every widget's constructor accepts one or two standard arguments:
512 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
513 (the default), the new widget will be a window. If not, it will be
514 a child of \e parent, and be constrained by \e parent's geometry
515 (unless you specify Qt::Window as window flag).
516 \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
517 the default is suitable for almost all widgets, but to get, for
518 example, a window without a window system frame, you must use
522 QWidget has many member functions, but some of them have little direct
523 functionality; for example, QWidget has a font property, but never uses
524 this itself. There are many subclasses which provide real functionality,
525 such as QLabel, QPushButton, QListWidget, and QTabWidget.
528 \section1 Top-Level and Child Widgets
530 A widget without a parent widget is always an independent window (top-level
531 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
532 title bar and icon respectively.
534 Non-window widgets are child widgets, displayed within their parent
535 widgets. Most widgets in Qt are mainly useful as child widgets. For
536 example, it is possible to display a button as a top-level window, but most
537 people prefer to put their buttons inside other widgets, such as QDialog.
539 \image parent-child-widgets.png A parent widget containing various child widgets.
541 The diagram above shows a QGroupBox widget being used to hold various child
542 widgets in a layout provided by QGridLayout. The QLabel child widgets have
543 been outlined to indicate their full sizes.
545 If you want to use a QWidget to hold child widgets you will usually want to
546 add a layout to the parent QWidget. See \l{Layout Management} for more
550 \section1 Composite Widgets
552 When a widget is used as a container to group a number of child widgets, it
553 is known as a composite widget. These can be created by constructing a
554 widget with the required visual properties - a QFrame, for example - and
555 adding child widgets to it, usually managed by a layout. The above diagram
556 shows such a composite widget that was created using \l{Qt Designer}.
558 Composite widgets can also be created by subclassing a standard widget,
559 such as QWidget or QFrame, and adding the necessary layout and child
560 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
561 {examples provided with Qt} use this approach, and it is also covered in
562 the Qt \l{Tutorials}.
565 \section1 Custom Widgets and Painting
567 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
568 display custom content that is composed using a series of painting
569 operations with an instance of the QPainter class. This approach contrasts
570 with the canvas-style approach used by the \l{Graphics View}
571 {Graphics View Framework} where items are added to a scene by the
572 application and are rendered by the framework itself.
574 Each widget performs all painting operations from within its paintEvent()
575 function. This is called whenever the widget needs to be redrawn, either
576 as a result of some external change or when requested by the application.
578 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
579 can handle paint events.
582 \section1 Size Hints and Size Policies
584 When implementing a new widget, it is almost always useful to reimplement
585 sizeHint() to provide a reasonable default size for the widget and to set
586 the correct size policy with setSizePolicy().
588 By default, composite widgets which do not provide a size hint will be
589 sized according to the space requirements of their child widgets.
591 The size policy lets you supply good default behavior for the layout
592 management system, so that other widgets can contain and manage yours
593 easily. The default size policy indicates that the size hint represents
594 the preferred size of the widget, and this is often good enough for many
597 \note The size of top-level widgets are constrained to 2/3 of the desktop's
598 height and width. You can resize() the widget manually if these bounds are
604 Widgets respond to events that are typically caused by user actions. Qt
605 delivers events to widgets by calling specific event handler functions with
606 instances of QEvent subclasses containing information about each event.
608 If your widget only contains child widgets, you probably do not need to
609 implement any event handlers. If you want to detect a mouse click in a
610 child widget call the child's underMouse() function inside the widget's
613 The \l{widgets/scribble}{Scribble example} implements a wider set of
614 events to handle mouse movement, button presses, and window resizing.
616 You will need to supply the behavior and content for your own widgets, but
617 here is a brief overview of the events that are relevant to QWidget,
618 starting with the most common ones:
621 \i paintEvent() is called whenever the widget needs to be repainted.
622 Every widget displaying custom content must implement it. Painting
623 using a QPainter can only take place in a paintEvent() or a
624 function called by a paintEvent().
625 \i resizeEvent() is called when the widget has been resized.
626 \i mousePressEvent() is called when a mouse button is pressed while
627 the mouse cursor is inside the widget, or when the widget has
628 grabbed the mouse using grabMouse(). Pressing the mouse without
629 releasing it is effectively the same as calling grabMouse().
630 \i mouseReleaseEvent() is called when a mouse button is released. A
631 widget receives mouse release events when it has received the
632 corresponding mouse press event. This means that if the user
633 presses the mouse inside \e your widget, then drags the mouse
634 somewhere else before releasing the mouse button, \e your widget
635 receives the release event. There is one exception: if a popup menu
636 appears while the mouse button is held down, this popup immediately
637 steals the mouse events.
638 \i mouseDoubleClickEvent() is called when the user double-clicks in
639 the widget. If the user double-clicks, the widget receives a mouse
640 press event, a mouse release event and finally this event instead
641 of a second mouse press event. (Some mouse move events may also be
642 received if the mouse is not held steady during this operation.) It
643 is \e{not possible} to distinguish a click from a double-click
644 until the second click arrives. (This is one reason why most GUI
645 books recommend that double-clicks be an extension of
646 single-clicks, rather than trigger a different action.)
649 Widgets that accept keyboard input need to reimplement a few more event
653 \i keyPressEvent() is called whenever a key is pressed, and again when
654 a key has been held down long enough for it to auto-repeat. The
655 \key Tab and \key Shift+Tab keys are only passed to the widget if
656 they are not used by the focus-change mechanisms. To force those
657 keys to be processed by your widget, you must reimplement
659 \i focusInEvent() is called when the widget gains keyboard focus
660 (assuming you have called setFocusPolicy()). Well-behaved widgets
661 indicate that they own the keyboard focus in a clear but discreet
663 \i focusOutEvent() is called when the widget loses keyboard focus.
666 You may be required to also reimplement some of the less common event
670 \i mouseMoveEvent() is called whenever the mouse moves while a mouse
671 button is held down. This can be useful during drag and drop
672 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
673 you get mouse move events even when no buttons are held down.
674 (See also the \l{Drag and Drop} guide.)
675 \i keyReleaseEvent() is called whenever a key is released and while it
676 is held down (if the key is auto-repeating). In that case, the
677 widget will receive a pair of key release and key press event for
678 every repeat. The \key Tab and \key Shift+Tab keys are only passed
679 to the widget if they are not used by the focus-change mechanisms.
680 To force those keys to be processed by your widget, you must
681 reimplement QWidget::event().
682 \i wheelEvent() is called whenever the user turns the mouse wheel
683 while the widget has the focus.
684 \i enterEvent() is called when the mouse enters the widget's screen
685 space. (This excludes screen space owned by any of the widget's
687 \i leaveEvent() is called when the mouse leaves the widget's screen
688 space. If the mouse enters a child widget it will not cause a
690 \i moveEvent() is called when the widget has been moved relative to
692 \i closeEvent() is called when the user closes the widget (or when
696 There are also some rather obscure events described in the documentation
697 for QEvent::Type. To handle these events, you need to reimplement event()
700 The default implementation of event() handles \key Tab and \key Shift+Tab
701 (to move the keyboard focus), and passes on most of the other events to
702 one of the more specialized handlers above.
704 Events and the mechanism used to deliver them are covered in
705 \l{The Event System}.
707 \section1 Groups of Functions and Properties
710 \header \i Context \i Functions and Properties
712 \row \i Window functions \i
719 \row \i Top-level windows \i
720 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
721 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
722 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
725 \row \i Window contents \i
731 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
732 \l sizePolicy, sizeHint(), minimumSizeHint(),
733 updateGeometry(), layout(),
734 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
736 mapFromGlobal(), mapToGlobal(),
737 mapFromParent(), mapToParent(),
738 \l maximumSize, \l minimumSize, \l sizeIncrement,
739 \l baseSize, setFixedSize()
742 \l visible, isVisibleTo(),
743 \l enabled, isEnabledTo(),
750 \row \i Look and feel \i
757 backgroundRole(), setBackgroundRole(),
758 fontInfo(), fontMetrics().
760 \row \i Keyboard focus functions \i
761 \l focus, \l focusPolicy,
762 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
763 focusNextChild(), focusPreviousChild().
765 \row \i Mouse and keyboard grabbing \i
766 grabMouse(), releaseMouse(),
767 grabKeyboard(), releaseKeyboard(),
768 mouseGrabber(), keyboardGrabber().
770 \row \i Event handlers \i
774 mouseDoubleClickEvent(),
797 \row \i System functions \i
798 parentWidget(), window(), setParent(), winId(),
801 \row \i Interactive help \i
802 setToolTip(), setWhatsThis()
807 \section1 Widget Style Sheets
809 In addition to the standard widget styles for each platform, widgets can
810 also be styled according to rules specified in a \l{styleSheet}
811 {style sheet}. This feature enables you to customize the appearance of
812 specific widgets to provide visual cues to users about their purpose. For
813 example, a button could be styled in a particular way to indicate that it
814 performs a destructive action.
816 The use of widget style sheets is described in more detail in the
817 \l{Qt Style Sheets} document.
820 \section1 Transparency and Double Buffering
822 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
823 is no need to write double-buffering code in paintEvent() to avoid
826 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
827 deprecated. Instead, the contents of parent widgets are propagated by
828 default to each of their children as long as Qt::WA_PaintOnScreen is not
829 set. Custom widgets can be written to take advantage of this feature by
830 updating irregular regions (to create non-rectangular child widgets), or
831 painting with colors that have less than full alpha component. The
832 following diagram shows how attributes and properties of a custom widget
833 can be fine-tuned to achieve different effects.
835 \image propagation-custom.png
837 In the above diagram, a semi-transparent rectangular child widget with an
838 area removed is constructed and added to a parent widget (a QLabel showing
839 a pixmap). Then, different properties and widget attributes are set to
840 achieve different effects:
843 \i The left widget has no additional properties or widget attributes
844 set. This default state suits most custom widgets using
845 transparency, are irregularly-shaped, or do not paint over their
846 entire area with an opaque brush.
847 \i The center widget has the \l autoFillBackground property set. This
848 property is used with custom widgets that rely on the widget to
849 supply a default background, and do not paint over their entire
850 area with an opaque brush.
851 \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
852 set. This indicates that the widget will paint over its entire area
853 with opaque colors. The widget's area will initially be
854 \e{uninitialized}, represented in the diagram with a red diagonal
855 grid pattern that shines through the overpainted area. The
856 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
857 paint their own specialized contents quickly and do not need a
858 default filled background.
861 To rapidly update custom widgets with simple background colors, such as
862 real-time plotting or graphing widgets, it is better to define a suitable
863 background color (using setBackgroundRole() with the
864 QPalette::Window role), set the \l autoFillBackground property, and only
865 implement the necessary drawing functionality in the widget's paintEvent().
867 To rapidly update custom widgets that constantly paint over their entire
868 areas with opaque content, e.g., video streaming widgets, it is better to
869 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
870 associated with repainting the widget's background.
872 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
873 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
874 attribute takes precedence. Depending on your requirements, you should
875 choose either one of them.
877 Since Qt 4.1, the contents of parent widgets are also propagated to
878 standard Qt widgets. This can lead to some unexpected results if the
879 parent widget is decorated in a non-standard way, as shown in the diagram
882 \image propagation-standard.png
884 The scope for customizing the painting behavior of standard Qt widgets,
885 without resorting to subclassing, is slightly less than that possible for
886 custom widgets. Usually, the desired appearance of a standard widget can be
887 achieved by setting its \l autoFillBackground property.
890 \section1 Creating Translucent Windows
892 Since Qt 4.5, it has been possible to create windows with translucent regions
893 on window systems that support compositing.
895 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
896 attribute with setAttribute() and ensure that its background is painted with
897 non-opaque colors in the regions you want to be partially transparent.
902 \o X11: This feature relies on the use of an X server that supports ARGB visuals
903 and a compositing window manager.
904 \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
905 for the translucency to work.
909 \section1 Native Widgets vs Alien Widgets
911 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
912 system. They do not have a native window handle associated with them. This
913 feature significantly speeds up widget painting, resizing, and removes flicker.
915 Should you require the old behavior with native windows, you can choose
916 one of the following options:
919 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
920 \i Set the Qt::AA_NativeWindows attribute on your application. All
921 widgets will be native widgets.
922 \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
923 and all of its ancestors will become native (unless
924 Qt::WA_DontCreateNativeAncestors is set).
925 \i Call QWidget::winId to enforce a native window (this implies 3).
926 \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
930 \sa QEvent, QPainter, QGridLayout, QBoxLayout
934 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
935 other visual representation on the screen that is generally located next to its
936 physical counterpart. They are most often found on mobile phone platforms. In
937 modern touch based user interfaces it is also possible to have softkeys that do
938 not correspond to any physical keys. Softkeys differ from other onscreen labels
939 in that they are contextual.
941 In Qt, contextual softkeys are added to a widget by calling addAction() and
942 passing a \c QAction with a softkey role set on it. When the widget
943 containing the softkey actions has focus, its softkeys should appear in
944 the user interface. Softkeys are discovered by traversing the widget
945 hierarchy so it is possible to define a single set of softkeys that are
946 present at all times by calling addAction() for a given top level widget.
948 On some platforms, this concept overlaps with \c QMenuBar such that if no
949 other softkeys are found and the top level widget is a QMainWindow containing
950 a QMenuBar, the menubar actions may appear on one of the softkeys.
952 Note: Currently softkeys are only supported on the Symbian Platform.
954 \sa addAction(), QAction, QMenuBar
958 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
959 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
962 /*****************************************************************************
963 QWidget utility functions
964 *****************************************************************************/
966 QRegion qt_dirtyRegion(QWidget *widget)
971 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
975 return bs->dirtyRegion(widget);
978 /*****************************************************************************
979 QWidget member functions
980 *****************************************************************************/
985 \i Qt::WA_WState_Created The widget has a valid winId().
986 \i Qt::WA_WState_Visible The widget is currently visible.
987 \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
988 become visible unless you call show() on it. Qt::WA_WState_Hidden
989 implies !Qt::WA_WState_Visible.
990 \i Qt::WA_WState_CompressKeys Compress keyboard events.
991 \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
992 \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
993 \i Qt::WA_WState_Reparented The widget has been reparented.
994 \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
995 \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
999 struct QWidgetExceptionCleaner
1001 /* this cleans up when the constructor throws an exception */
1002 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
1004 #ifdef QT_NO_EXCEPTIONS
1008 QWidgetPrivate::allWidgets->remove(that);
1009 if (d->focus_next != that) {
1011 d->focus_next->d_func()->focus_prev = d->focus_prev;
1013 d->focus_prev->d_func()->focus_next = d->focus_next;
1020 Constructs a widget which is a child of \a parent, with widget
1023 If \a parent is 0, the new widget becomes a window. If
1024 \a parent is another widget, this widget becomes a child window
1025 inside \a parent. The new widget is deleted when its \a parent is
1028 The widget flags argument, \a f, is normally 0, but it can be set
1029 to customize the frame of a window (i.e. \a
1030 parent must be 0). To customize the frame, use a value composed
1031 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1033 If you add a child widget to an already visible widget you must
1034 explicitly show the child to make it visible.
1036 Note that the X11 version of Qt may not be able to deliver all
1037 combinations of style flags on all systems. This is because on
1038 X11, Qt can only ask the window manager, and the window manager
1039 can override the application's settings. On Windows, Qt can set
1040 whatever flags you want.
1044 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1045 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1048 d_func()->init(parent, f);
1050 QWidgetExceptionCleaner::cleanup(this, d_func());
1058 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1059 : QObject(dd, 0), QPaintDevice()
1065 QWidgetExceptionCleaner::cleanup(this, d_func());
1073 int QWidget::devType() const
1075 return QInternal::Widget;
1079 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1080 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1082 bool customize = (flags & (Qt::CustomizeWindowHint
1083 | Qt::FramelessWindowHint
1084 | Qt::WindowTitleHint
1085 | Qt::WindowSystemMenuHint
1086 | Qt::WindowMinimizeButtonHint
1087 | Qt::WindowMaximizeButtonHint
1088 | Qt::WindowCloseButtonHint
1089 | Qt::WindowContextHelpButtonHint));
1091 uint type = (flags & Qt::WindowType_Mask);
1093 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1095 flags |= Qt::Window;
1098 if (flags & Qt::CustomizeWindowHint) {
1099 // modify window flags to make them consistent.
1100 // Only enable this on non-Mac platforms. Since the old way of doing this would
1101 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1102 // we can't just add this in.
1104 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1105 flags |= Qt::WindowSystemMenuHint;
1107 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1108 | Qt::WindowSystemMenuHint)) {
1110 flags |= Qt::WindowTitleHint;
1111 flags &= ~Qt::FramelessWindowHint;
1113 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1114 // if any of the window hints that affect the titlebar are set
1115 // and the window is supposed to have frame, we add a titlebar
1116 // and system menu by default.
1117 flags |= Qt::WindowSystemMenuHint;
1118 flags |= Qt::WindowTitleHint;
1121 ; // don't modify window flags if the user explicitly set them.
1122 else if (type == Qt::Dialog || type == Qt::Sheet)
1124 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1126 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1128 else if (type == Qt::Tool)
1129 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1131 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1136 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1139 if (QApplication::type() == QApplication::Tty)
1140 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1142 Q_ASSERT(allWidgets);
1144 allWidgets->insert(q);
1146 QWidget *desktopWidget = 0;
1147 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1148 desktopWidget = parentWidget;
1154 #ifndef QT_NO_THREAD
1156 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1157 "Widgets must be created in the GUI thread.");
1161 #if defined(Q_WS_X11)
1162 if (desktopWidget) {
1163 // make sure the widget is created on the same screen as the
1164 // programmer specified desktop widget
1165 xinfo = desktopWidget->d_func()->xinfo;
1168 if (desktopWidget) {
1169 const int screen = desktopWidget->d_func()->topData()->screenIndex;
1170 if (QWindow *window = q->windowHandle())
1171 window->setScreen(QGuiApplication::screens().value(screen, 0));
1174 data.fstrut_dirty = true;
1177 data.widget_attributes = 0;
1178 data.window_flags = f;
1179 data.window_state = 0;
1180 data.focus_policy = 0;
1181 data.context_menu_policy = Qt::DefaultContextMenu;
1182 data.window_modality = Qt::NonModal;
1184 data.sizehint_forced = 0;
1185 data.is_closing = 0;
1187 data.in_set_window_state = 0;
1188 data.in_destructor = false;
1190 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1191 if (f & Qt::MSWindowsOwnDC)
1192 q->setAttribute(Qt::WA_NativeWindow);
1195 // q->setAttribute(Qt::WA_NativeWindow);
1198 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1199 adjustQuitOnCloseAttribute();
1201 q->setAttribute(Qt::WA_WState_Hidden);
1203 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1204 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1205 focus_next = focus_prev = q;
1207 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1209 else if (parentWidget)
1210 q->setParent(parentWidget, data.window_flags);
1212 adjustFlags(data.window_flags, q);
1213 resolveLayoutDirection();
1214 // opaque system background?
1215 const QBrush &background = q->palette().brush(QPalette::Window);
1216 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1218 data.fnt = QFont(data.fnt, q);
1219 #if defined(Q_WS_X11)
1220 data.fnt.x11SetScreen(xinfo.screen());
1223 q->setAttribute(Qt::WA_PendingMoveEvent);
1224 q->setAttribute(Qt::WA_PendingResizeEvent);
1226 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1227 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1229 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1232 QEvent e(QEvent::Create);
1233 QApplication::sendEvent(q, &e);
1234 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1236 extraPaintEngine = 0;
1239 // If we add a child to the unified toolbar, we have to redirect the painting.
1240 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1241 if (parentWidget->d_func()->unifiedSurface) {
1242 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1243 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1251 void QWidgetPrivate::createRecursively()
1254 q->create(0, true, true);
1255 for (int i = 0; i < children.size(); ++i) {
1256 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1257 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1258 child->d_func()->createRecursively();
1266 Creates a new widget window if \a window is 0, otherwise sets the
1267 widget's window to \a window.
1269 Initializes the window (sets the geometry etc.) if \a
1270 initializeWindow is true. If \a initializeWindow is false, no
1271 initialization is performed. This parameter only makes sense if \a
1272 window is a valid window.
1274 Destroys the old window if \a destroyOldWindow is true. If \a
1275 destroyOldWindow is false, you are responsible for destroying the
1276 window yourself (using platform native code).
1278 The QWidget constructor calls create(0,true,true) to create a
1279 window for this widget.
1282 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1285 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1288 if (d->data.in_destructor)
1291 Qt::WindowType type = windowType();
1292 Qt::WindowFlags &flags = data->window_flags;
1294 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1296 flags |= Qt::Window;
1299 if (QWidget *parent = parentWidget()) {
1300 if (type & Qt::Window) {
1301 if (!parent->testAttribute(Qt::WA_WState_Created))
1302 parent->createWinId();
1303 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1304 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1305 // We're about to create a native child widget that doesn't have a native parent;
1306 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1307 // attribute is set.
1308 d->createWinId(window);
1309 // Nothing more to do.
1310 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1311 Q_ASSERT(internalWinId());
1317 static int paintOnScreenEnv = -1;
1318 if (paintOnScreenEnv == -1)
1319 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1320 if (paintOnScreenEnv == 1)
1321 setAttribute(Qt::WA_PaintOnScreen);
1323 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1324 setAttribute(Qt::WA_NativeWindow);
1327 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1328 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1331 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1332 // Unregister the dropsite (if already registered) before we
1333 // re-create the widget with a native window.
1334 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1335 && d->extra && d->extra->dropTarget) {
1336 d->registerDropSite(false);
1338 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1340 d->updateIsOpaque();
1342 setAttribute(Qt::WA_WState_Created); // set created flag
1343 d->create_sys(window, initializeWindow, destroyOldWindow);
1345 // a real toplevel window needs a backing store
1346 if (isWindow() && windowType() != Qt::Desktop) {
1347 d->topData()->backingStoreTracker.destroy();
1348 if (hasBackingStoreSupport())
1349 d->topData()->backingStoreTracker.create(this);
1354 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1355 setAttribute(Qt::WA_DropSiteRegistered, true);
1358 extern void qt_eval_init_widget(QWidget *w);
1359 qt_eval_init_widget(this);
1362 // need to force the resting of the icon after changing parents
1363 if (testAttribute(Qt::WA_SetWindowIcon))
1364 d->setWindowIcon_sys(true);
1365 if (isWindow() && !d->topData()->iconText.isEmpty())
1366 d->setWindowIconText_helper(d->topData()->iconText);
1367 if (isWindow() && !d->topData()->caption.isEmpty())
1368 d->setWindowTitle_helper(d->topData()->caption);
1369 if (windowType() != Qt::Desktop) {
1370 d->updateSystemBackground();
1372 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1373 d->setWindowIcon_sys();
1378 Destroys the widget.
1380 All this widget's children are deleted first. The application
1381 exits if this widget is the main widget.
1387 d->data.in_destructor = true;
1389 #if defined (QT_CHECK_STATE)
1390 if (paintingActive())
1391 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1394 #ifndef QT_NO_GESTURES
1395 foreach (Qt::GestureType type, d->gestureContext.keys())
1396 ungrabGesture(type);
1399 // force acceptDrops false before winId is destroyed.
1400 d->registerDropSite(false);
1402 #ifndef QT_NO_ACTION
1403 // remove all actions from this widget
1404 for (int i = 0; i < d->actions.size(); ++i) {
1405 QActionPrivate *apriv = d->actions.at(i)->d_func();
1406 apriv->widgets.removeAll(this);
1411 #ifndef QT_NO_SHORTCUT
1412 // Remove all shortcuts grabbed by this
1413 // widget, unless application is closing
1414 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1415 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1418 // delete layout while we still are a valid widget
1421 // Remove myself from focus list
1423 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1424 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1426 if (d->focus_next != this) {
1427 d->focus_next->d_func()->focus_prev = d->focus_prev;
1428 d->focus_prev->d_func()->focus_next = d->focus_next;
1429 d->focus_next = d->focus_prev = 0;
1436 // swallow this problem because we are in a destructor
1439 d->setDirtyOpaqueRegion();
1441 if (isWindow() && isVisible() && internalWinId()) {
1443 d->close_helper(QWidgetPrivate::CloseNoEvent);
1445 // if we're out of memory, at least hide the window.
1449 // and if that also doesn't work, then give up
1454 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1455 else if (!internalWinId() && isVisible()) {
1456 qApp->d_func()->sendSyntheticEnterLeave(this);
1459 else if (isVisible()) {
1460 qApp->d_func()->sendSyntheticEnterLeave(this);
1463 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1464 bs->removeDirtyWidget(this);
1465 if (testAttribute(Qt::WA_StaticContents))
1466 bs->removeStaticWidget(this);
1469 delete d->needsFlush;
1472 if (d->declarativeData) {
1473 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1474 d->declarativeData = 0; // don't activate again in ~QObject
1478 // QCocoaView holds a pointer back to this widget. Clear it now
1479 // to make sure it's not followed later on. The lifetime of the
1480 // QCocoaView might exceed the lifetime of this widget in cases
1481 // where Cocoa itself holds references to it.
1482 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1483 qt_mac_clearCocoaViewQWidgetPointers(this);
1486 if (!d->children.isEmpty())
1487 d->deleteChildren();
1489 QApplication::removePostedEvents(this);
1492 destroy(); // platform-dependent cleanup
1494 // if this fails we can't do anything about it but at least we are not allowed to throw.
1496 --QWidgetPrivate::instanceCounter;
1498 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1499 QWidgetPrivate::allWidgets->remove(this);
1502 QEvent e(QEvent::Destroy);
1503 QCoreApplication::sendEvent(this, &e);
1504 } QT_CATCH(const std::exception&) {
1505 // if this fails we can't do anything about it but at least we are not allowed to throw.
1509 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1510 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1512 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1515 // the user might create a widget with Qt::Desktop window
1516 // attribute (or create another QDesktopWidget instance), which
1517 // will have the same windowid (the root window id) as the
1518 // qt_desktopWidget. We should not add the second desktop widget
1520 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1521 if (mapper && data.winid && !userDesktopWidget) {
1522 mapper->remove(data.winid);
1525 const WId oldWinId = data.winid;
1528 #if defined(Q_WS_X11)
1529 hd = id; // X11: hd == ident
1531 if (mapper && id && !userDesktopWidget) {
1532 mapper->insert(data.winid, q);
1535 if(oldWinId != id) {
1536 QEvent e(QEvent::WinIdChange);
1537 QCoreApplication::sendEvent(q, &e);
1541 void QWidgetPrivate::createTLExtra()
1545 if (!extra->topextra) {
1546 QTLWExtra* x = extra->topextra = new QTLWExtra;
1549 x->backingStore = 0;
1550 x->sharedPainter = 0;
1551 x->incw = x->inch = 0;
1552 x->basew = x->baseh = 0;
1553 x->frameStrut.setCoords(0, 0, 0, 0);
1554 x->normalGeometry = QRect(0,0,-1,-1);
1557 x->posFromMove = false;
1558 x->sizeAdjusted = false;
1559 x->inTopLevelResize = false;
1560 x->inRepaint = false;
1563 x->wasMaximized = false;
1566 #ifdef QWIDGET_EXTRA_DEBUG
1567 static int count = 0;
1568 qDebug() << "tlextra" << ++count;
1575 Creates the widget extra data.
1578 void QWidgetPrivate::createExtra()
1580 if (!extra) { // if not exists
1581 extra = new QWExtra;
1582 extra->glContext = 0;
1583 extra->topextra = 0;
1584 #ifndef QT_NO_GRAPHICSVIEW
1585 extra->proxyWidget = 0;
1587 #ifndef QT_NO_CURSOR
1592 extra->maxw = QWIDGETSIZE_MAX;
1593 extra->maxh = QWIDGETSIZE_MAX;
1594 extra->customDpiX = 0;
1595 extra->customDpiY = 0;
1596 extra->explicitMinSize = 0;
1597 extra->explicitMaxSize = 0;
1598 extra->autoFillBackground = 0;
1599 extra->nativeChildrenForced = 0;
1600 extra->inRenderWithPainter = 0;
1603 #ifdef QWIDGET_EXTRA_DEBUG
1604 static int count = 0;
1605 qDebug() << "extra" << ++count;
1613 Deletes the widget extra data.
1616 void QWidgetPrivate::deleteExtra()
1618 if (extra) { // if exists
1619 #ifndef QT_NO_CURSOR
1623 #ifndef QT_NO_STYLE_STYLESHEET
1624 // dereference the stylesheet style
1625 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1628 if (extra->topextra) {
1630 extra->topextra->backingStoreTracker.destroy();
1631 delete extra->topextra->icon;
1632 delete extra->topextra->iconPixmap;
1633 delete extra->topextra->backingStore;
1634 delete extra->topextra;
1637 // extra->xic destroyed in QWidget::destroy()
1643 Returns true if there are widgets above this which overlap with
1644 \a rect, which is in parent's coordinate system (same as crect).
1647 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1651 const QWidget *w = q;
1656 QWidgetPrivate *pd = w->parentWidget()->d_func();
1658 for (int i = 0; i < pd->children.size(); ++i) {
1659 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1660 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1663 above = (sibling == w);
1667 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1668 const QWExtra *siblingExtra = sibling->d_func()->extra;
1669 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1670 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1676 w = w->parentWidget();
1677 r.translate(pd->data.crect.topLeft());
1682 void QWidgetPrivate::syncBackingStore()
1684 if (paintOnScreen()) {
1687 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1692 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1694 if (paintOnScreen())
1695 repaint_sys(region);
1696 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1697 bs->sync(q_func(), region);
1701 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1705 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1706 return; // nothing we can do
1708 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1709 return; // nothing to do
1711 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1715 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1716 for (int i = 0; i < children.size(); ++i) {
1717 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1718 if (w && !w->isWindow() && !w->testAttribute(attribute))
1719 w->d_func()->setUpdatesEnabled_helper(enable);
1726 Propagate this widget's palette to all children, except style sheet
1727 widgets, and windows that don't enable window propagation (palettes don't
1728 normally propagate to windows).
1730 void QWidgetPrivate::propagatePaletteChange()
1733 // Propagate a new inherited mask to all children.
1734 #ifndef QT_NO_GRAPHICSVIEW
1735 if (!q->parentWidget() && extra && extra->proxyWidget) {
1736 QGraphicsProxyWidget *p = extra->proxyWidget;
1737 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1739 #endif //QT_NO_GRAPHICSVIEW
1740 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1741 inheritedPaletteResolveMask = 0;
1743 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1745 QEvent pc(QEvent::PaletteChange);
1746 QApplication::sendEvent(q, &pc);
1747 for (int i = 0; i < children.size(); ++i) {
1748 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1749 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1750 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1751 QWidgetPrivate *wd = w->d_func();
1752 wd->inheritedPaletteResolveMask = mask;
1753 wd->resolvePalette();
1759 Returns the widget's clipping rectangle.
1761 QRect QWidgetPrivate::clipRect() const
1764 const QWidget * w = q;
1765 if (!w->isVisible())
1767 QRect r = effectiveRectFor(q->rect());
1773 && w->parentWidget()) {
1776 w = w->parentWidget();
1777 r &= QRect(ox, oy, w->width(), w->height());
1783 Returns the widget's clipping region (without siblings).
1785 QRegion QWidgetPrivate::clipRegion() const
1788 if (!q->isVisible())
1790 QRegion r(q->rect());
1791 const QWidget * w = q;
1792 const QWidget *ignoreUpTo;
1798 && w->parentWidget()) {
1802 w = w->parentWidget();
1803 r &= QRegion(ox, oy, w->width(), w->height());
1806 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1808 for ( ; i < w->d_func()->children.size(); ++i) {
1809 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1810 if(sibling->isVisible() && !sibling->isWindow()) {
1811 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1812 sibling->width(), sibling->height());
1813 if (qRectIntersects(siblingRect, q->rect()))
1814 r -= QRegion(siblingRect);
1822 #ifndef QT_NO_GRAPHICSEFFECT
1823 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1828 if (w->graphicsEffect()) {
1829 QWidgetEffectSourcePrivate *sourced =
1830 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1831 if (!sourced->updateDueToGraphicsEffect)
1832 w->graphicsEffect()->source()->d_func()->invalidateCache();
1834 w = w->parentWidget();
1837 #endif //QT_NO_GRAPHICSEFFECT
1839 void QWidgetPrivate::setDirtyOpaqueRegion()
1843 dirtyOpaqueChildren = true;
1845 #ifndef QT_NO_GRAPHICSEFFECT
1846 invalidateGraphicsEffectsRecursively();
1847 #endif //QT_NO_GRAPHICSEFFECT
1852 QWidget *parent = q->parentWidget();
1856 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1857 QWidgetPrivate *pd = parent->d_func();
1858 if (!pd->dirtyOpaqueChildren)
1859 pd->setDirtyOpaqueRegion();
1862 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1864 if (!dirtyOpaqueChildren)
1865 return opaqueChildren;
1867 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1868 that->opaqueChildren = QRegion();
1870 for (int i = 0; i < children.size(); ++i) {
1871 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1872 if (!child || !child->isVisible() || child->isWindow())
1875 const QPoint offset = child->geometry().topLeft();
1876 QWidgetPrivate *childd = child->d_func();
1877 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1878 if (childd->extra && childd->extra->hasMask)
1879 r &= childd->extra->mask;
1882 r.translate(offset);
1883 that->opaqueChildren += r;
1886 that->opaqueChildren &= q_func()->rect();
1887 that->dirtyOpaqueChildren = false;
1889 return that->opaqueChildren;
1892 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1894 if (children.isEmpty() || clipRect.isEmpty())
1897 const QRegion &r = getOpaqueChildren();
1899 source -= (r & clipRect);
1902 //subtract any relatives that are higher up than me --- this is too expensive !!!
1903 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1904 bool alsoNonOpaque) const
1907 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1908 if (disableSubtractOpaqueSiblings || q->isWindow())
1912 if (q->d_func()->isInUnifiedToolbar)
1916 QRect clipBoundingRect;
1917 bool dirtyClipBoundingRect = true;
1920 bool dirtyParentClip = true;
1922 QPoint parentOffset = data.crect.topLeft();
1924 const QWidget *w = q;
1929 QWidgetPrivate *pd = w->parentWidget()->d_func();
1930 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1931 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1932 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1933 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1934 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1937 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1938 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1941 if (dirtyClipBoundingRect) {
1942 clipBoundingRect = sourceRegion.boundingRect();
1943 dirtyClipBoundingRect = false;
1946 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1949 if (dirtyParentClip) {
1950 parentClip = sourceRegion.translated(parentOffset);
1951 dirtyParentClip = false;
1954 const QPoint siblingPos(sibling->data->crect.topLeft());
1955 const QRect siblingClipRect(sibling->d_func()->clipRect());
1956 QRegion siblingDirty(parentClip);
1957 siblingDirty &= (siblingClipRect.translated(siblingPos));
1958 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1959 && !sibling->d_func()->graphicsEffect;
1961 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1962 if (siblingDirty.isEmpty())
1965 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1967 siblingDirty.translate(-parentOffset);
1968 sourceRegion -= siblingDirty;
1970 sourceRegion -= siblingGeometry.translated(-parentOffset);
1973 if (hasDirtySiblingsAbove)
1974 *hasDirtySiblingsAbove = true;
1975 if (sibling->d_func()->children.isEmpty())
1977 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1978 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1979 sourceRegion -= opaqueSiblingChildren;
1981 if (sourceRegion.isEmpty())
1984 dirtyClipBoundingRect = true;
1985 dirtyParentClip = true;
1988 w = w->parentWidget();
1989 parentOffset += pd->data.crect.topLeft();
1990 dirtyParentClip = true;
1994 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
1998 const QWidget *w = q;
2001 #ifndef QT_NO_GRAPHICSEFFECT
2002 if (graphicsEffect) {
2003 w = q->parentWidget();
2004 offset -= data.crect.topLeft();
2006 #endif //QT_NO_GRAPHICSEFFECT
2009 const QWidgetPrivate *wd = w->d_func();
2010 if (wd->extra && wd->extra->hasMask)
2011 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2014 offset -= wd->data.crect.topLeft();
2015 w = w->parentWidget();
2019 bool QWidgetPrivate::paintOnScreen() const
2021 #if defined(QT_NO_BACKINGSTORE)
2025 if (q->testAttribute(Qt::WA_PaintOnScreen)
2026 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2030 return !qt_enable_backingstore;
2034 void QWidgetPrivate::updateIsOpaque()
2036 // hw: todo: only needed if opacity actually changed
2037 setDirtyOpaqueRegion();
2039 #ifndef QT_NO_GRAPHICSEFFECT
2040 if (graphicsEffect) {
2041 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2045 #endif //QT_NO_GRAPHICSEFFECT
2049 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2056 if (q->windowType() == Qt::Dialog && q->testAttribute(Qt::WA_TranslucentBackground)
2057 && S60->avkonComponentsSupportTransparency) {
2063 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2068 const QPalette &pal = q->palette();
2070 if (q->autoFillBackground()) {
2071 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2072 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2078 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2079 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2080 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2088 void QWidgetPrivate::setOpaque(bool opaque)
2090 if (isOpaque == opaque)
2094 macUpdateIsOpaque();
2097 x11UpdateIsOpaque();
2100 winUpdateIsOpaque();
2104 void QWidgetPrivate::updateIsTranslucent()
2107 macUpdateIsOpaque();
2110 x11UpdateIsOpaque();
2113 winUpdateIsOpaque();
2117 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2121 if (brush.style() == Qt::TexturePattern) {
2123 // Optimize pattern filling on mac by using HITheme directly
2124 // when filling with the standard widget background.
2125 // Defined in qmacstyle_mac.cpp
2126 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2127 qt_mac_fill_background(painter, rgn, brush);
2129 #if !defined(QT_NO_STYLE_S60)
2130 // Defined in qs60style.cpp
2131 extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2132 if (!qt_s60_fill_background(painter, rgn, brush))
2133 #endif // !defined(QT_NO_STYLE_S60)
2135 const QRect rect(rgn.boundingRect());
2136 painter->setClipRegion(rgn);
2137 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2141 } else if (brush.gradient()
2142 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2144 painter->setClipRegion(rgn);
2145 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2148 const QVector<QRect> &rects = rgn.rects();
2149 for (int i = 0; i < rects.size(); ++i)
2150 painter->fillRect(rects.at(i), brush);
2154 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2158 #ifndef QT_NO_SCROLLAREA
2159 bool resetBrushOrigin = false;
2160 QPointF oldBrushOrigin;
2161 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2162 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2163 if (scrollArea && scrollArea->viewport() == q) {
2164 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2165 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2166 oldBrushOrigin = painter->brushOrigin();
2167 resetBrushOrigin = true;
2168 painter->setBrushOrigin(-priv->contentsOffset());
2171 #endif // QT_NO_SCROLLAREA
2173 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2175 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2176 const QBrush bg = q->palette().brush(QPalette::Window);
2177 fillRegion(painter, rgn, bg);
2180 if (q->autoFillBackground())
2181 fillRegion(painter, rgn, autoFillBrush);
2183 if (q->testAttribute(Qt::WA_StyledBackground)) {
2184 painter->setClipRegion(rgn);
2187 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2190 #ifndef QT_NO_SCROLLAREA
2191 if (resetBrushOrigin)
2192 painter->setBrushOrigin(oldBrushOrigin);
2193 #endif // QT_NO_SCROLLAREA
2198 This function is called when a widget is hidden or destroyed.
2199 It resets some application global pointers that should only refer active,
2204 extern QPointer<QWidget> qt_button_down;
2206 extern QWidget *qt_button_down;
2209 void QWidgetPrivate::deactivateWidgetCleanup()
2212 // If this was the active application window, reset it
2213 if (QApplication::activeWindow() == q)
2214 QApplication::setActiveWindow(0);
2215 // If the is the active mouse press widget, reset it
2216 if (q == qt_button_down)
2222 Returns a pointer to the widget with window identifer/handle \a
2225 The window identifier type depends on the underlying window
2226 system, see \c qwindowdefs.h for the actual definition. If there
2227 is no widget with this identifier, 0 is returned.
2230 QWidget *QWidget::find(WId id)
2232 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2238 \fn WId QWidget::internalWinId() const
2240 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2245 \fn WId QWidget::winId() const
2247 Returns the window system identifier of the widget.
2249 Portable in principle, but if you use it you are probably about to
2250 do something non-portable. Be careful.
2252 If a widget is non-native (alien) and winId() is invoked on it, that widget
2253 will be provided a native handle.
2255 On Mac OS X, the type returned depends on which framework Qt was linked
2256 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2257 is using Cocoa, {WId} is a pointer to an NSView.
2259 This value may change at run-time. An event with type QEvent::WinIdChange
2260 will be sent to the widget following a change in window system identifier.
2264 WId QWidget::winId() const
2266 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2268 qDebug() << "QWidget::winId: creating native window for" << this;
2270 QWidget *that = const_cast<QWidget*>(this);
2271 that->setAttribute(Qt::WA_NativeWindow);
2272 that->d_func()->createWinId();
2273 return that->data->winid;
2279 void QWidgetPrivate::createWinId(WId winid)
2284 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2286 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2287 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2288 if (!q->isWindow()) {
2289 QWidget *parent = q->parentWidget();
2290 QWidgetPrivate *pd = parent->d_func();
2291 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2292 parent->setAttribute(Qt::WA_NativeWindow);
2293 if (!parent->internalWinId()) {
2297 for (int i = 0; i < pd->children.size(); ++i) {
2298 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2299 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2300 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2305 // if the window has already been created, we
2306 // need to raise it to its proper stacking position
2321 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2325 void QWidget::createWinId()
2329 qDebug() << "QWidget::createWinId" << this;
2331 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2338 Returns the effective window system identifier of the widget, i.e. the
2339 native parent's window system identifier.
2341 If the widget is native, this function returns the native widget ID.
2342 Otherwise, the window ID of the first native parent widget, i.e., the
2343 top-level widget that contains this widget, is returned.
2345 \note We recommend that you do not store this value as it is likely to
2348 \sa nativeParentWidget()
2350 WId QWidget::effectiveWinId() const
2352 WId id = internalWinId();
2353 if (id || !testAttribute(Qt::WA_WState_Created))
2355 QWidget *realParent = nativeParentWidget();
2356 if (!realParent && d_func()->inSetParent) {
2357 // In transitional state. This is really just a workaround. The real problem
2358 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2359 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2360 // attribute to false. The correct way is to do it the other way around, and
2361 // in that case the Qt::WA_WState_Created logic above will kick in and
2362 // return 0 whenever the widget is in a transitional state. However, changing
2363 // the original logic for all platforms is far more intrusive and might
2364 // break existing applications.
2365 // Note: The widget can only be in a transitional state when changing its
2366 // parent -- everything else is an internal error -- hence explicitly checking
2367 // against 'inSetParent' rather than doing an unconditional return whenever
2368 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2371 // This widget *must* have a native parent widget.
2372 Q_ASSERT(realParent);
2373 Q_ASSERT(realParent->internalWinId());
2374 return realParent->internalWinId();
2377 #ifndef QT_NO_STYLE_STYLESHEET
2380 \property QWidget::styleSheet
2381 \brief the widget's style sheet
2384 The style sheet contains a textual description of customizations to the
2385 widget's style, as described in the \l{Qt Style Sheets} document.
2387 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2389 \warning Qt style sheets are currently not supported for custom QStyle
2390 subclasses. We plan to address this in some future release.
2392 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2394 QString QWidget::styleSheet() const
2399 return d->extra->styleSheet;
2402 void QWidget::setStyleSheet(const QString& styleSheet)
2407 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2408 d->extra->styleSheet = styleSheet;
2409 if (styleSheet.isEmpty()) { // stylesheet removed
2417 if (proxy) { // style sheet update
2418 proxy->repolish(this);
2422 if (testAttribute(Qt::WA_SetStyle)) {
2423 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2425 d->setStyle_helper(new QStyleSheetStyle(0), true);
2429 #endif // QT_NO_STYLE_STYLESHEET
2432 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2435 QStyle *QWidget::style() const
2439 if (d->extra && d->extra->style)
2440 return d->extra->style;
2441 return QApplication::style();
2445 Sets the widget's GUI style to \a style. The ownership of the style
2446 object is not transferred.
2448 If no style is set, the widget uses the application's style,
2449 QApplication::style() instead.
2451 Setting a widget's style has no effect on existing or future child
2454 \warning This function is particularly useful for demonstration
2455 purposes, where you want to show Qt's styling capabilities. Real
2456 applications should avoid it and use one consistent GUI style
2459 \warning Qt style sheets are currently not supported for custom QStyle
2460 subclasses. We plan to address this in some future release.
2462 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2465 void QWidget::setStyle(QStyle *style)
2468 setAttribute(Qt::WA_SetStyle, style != 0);
2470 #ifndef QT_NO_STYLE_STYLESHEET
2471 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2472 //if for some reason someone try to set a QStyleSheetStyle, ref it
2473 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2475 d->setStyle_helper(style, false);
2476 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2477 // if we have an application stylesheet or have a proxy already, propagate
2478 d->setStyle_helper(new QStyleSheetStyle(style), true);
2481 d->setStyle_helper(style, false);
2484 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2491 QStyle *oldStyle = q->style();
2492 #ifndef QT_NO_STYLE_STYLESHEET
2493 QWeakPointer<QStyle> origStyle;
2497 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2498 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2499 // set when changing that attribute and passes the widget's CURRENT style.
2500 // therefore no need to do a reassignment.
2506 #ifndef QT_NO_STYLE_STYLESHEET
2507 origStyle = extra->style.data();
2509 extra->style = newStyle;
2513 if (q->windowType() != Qt::Desktop) {
2515 oldStyle->unpolish(q);
2518 macUpdateMetalAttribute();
2520 q->style()->polish(q);
2522 } else if (metalHack) {
2523 macUpdateMetalAttribute();
2529 for (int i = 0; i < children.size(); ++i) {
2530 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2532 c->d_func()->inheritStyle();
2536 #ifndef QT_NO_STYLE_STYLESHEET
2537 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2538 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2539 cssStyle->clearWidgetFont(q);
2544 QEvent e(QEvent::StyleChange);
2545 QApplication::sendEvent(q, &e);
2547 #ifndef QT_NO_STYLE_STYLESHEET
2548 // dereference the old stylesheet style
2549 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2554 // Inherits style from the current parent and propagates it as necessary
2555 void QWidgetPrivate::inheritStyle()
2557 #ifndef QT_NO_STYLE_STYLESHEET
2560 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2562 if (!q->styleSheet().isEmpty()) {
2568 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2569 QWidget *parent = q->parentWidget();
2570 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2571 // If we have stylesheet on app or parent has stylesheet style, we need
2572 // to be running a proxy
2573 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2574 QStyle *newStyle = parentStyle;
2575 if (q->testAttribute(Qt::WA_SetStyle))
2576 newStyle = new QStyleSheetStyle(origStyle);
2577 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2580 setStyle_helper(newStyle, true);
2584 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2585 // we just need our original style back
2586 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2589 // We could have inherited the proxy from our parent (which has a custom style)
2590 // In such a case we need to start following the application style (i.e revert
2591 // the propagation behavior of QStyleSheetStyle)
2592 if (!q->testAttribute(Qt::WA_SetStyle))
2595 setStyle_helper(origStyle, true);
2596 #endif // QT_NO_STYLE_STYLESHEET
2601 \fn bool QWidget::isWindow() const
2603 Returns true if the widget is an independent window, otherwise
2606 A window is a widget that isn't visually the child of any other
2607 widget and that usually has a frame and a
2608 \l{QWidget::setWindowTitle()}{window title}.
2610 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2611 It will then be grouped with its parent and deleted when the
2612 parent is deleted, minimized when the parent is minimized etc. If
2613 supported by the window manager, it will also have a common
2614 taskbar entry with its parent.
2616 QDialog and QMainWindow widgets are by default windows, even if a
2617 parent widget is specified in the constructor. This behavior is
2618 specified by the Qt::Window flag.
2620 \sa window(), isModal(), parentWidget()
2624 \property QWidget::modal
2625 \brief whether the widget is a modal widget
2627 This property only makes sense for windows. A modal widget
2628 prevents widgets in all other windows from getting any input.
2630 By default, this property is false.
2632 \sa isWindow(), windowModality, QDialog
2636 \property QWidget::windowModality
2637 \brief which windows are blocked by the modal widget
2640 This property only makes sense for windows. A modal widget
2641 prevents widgets in other windows from getting input. The value of
2642 this property controls which windows are blocked when the widget
2643 is visible. Changing this property while the window is visible has
2644 no effect; you must hide() the widget first, then show() it again.
2646 By default, this property is Qt::NonModal.
2648 \sa isWindow(), QWidget::modal, QDialog
2651 Qt::WindowModality QWidget::windowModality() const
2653 return static_cast<Qt::WindowModality>(data->window_modality);
2656 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2658 data->window_modality = windowModality;
2659 // setModal_sys() will be called by setAttribute()
2660 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2661 setAttribute(Qt::WA_SetWindowModality, true);
2665 \fn bool QWidget::underMouse() const
2667 Returns true if the widget is under the mouse cursor; otherwise
2670 This value is not updated properly during drag and drop
2673 \sa enterEvent(), leaveEvent()
2677 \property QWidget::minimized
2678 \brief whether this widget is minimized (iconified)
2680 This property is only relevant for windows.
2682 By default, this property is false.
2684 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2686 bool QWidget::isMinimized() const
2687 { return data->window_state & Qt::WindowMinimized; }
2690 Shows the widget minimized, as an icon.
2692 Calling this function only affects \l{isWindow()}{windows}.
2694 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2697 void QWidget::showMinimized()
2699 bool isMin = isMinimized();
2700 if (isMin && isVisible())
2706 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2711 \property QWidget::maximized
2712 \brief whether this widget is maximized
2714 This property is only relevant for windows.
2716 \note Due to limitations on some window systems, this does not always
2717 report the expected results (e.g., if the user on X11 maximizes the
2718 window via the window manager, Qt has no way of distinguishing this
2719 from any other resize). This is expected to improve as window manager
2722 By default, this property is false.
2724 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2726 bool QWidget::isMaximized() const
2727 { return data->window_state & Qt::WindowMaximized; }
2732 Returns the current window state. The window state is a OR'ed
2733 combination of Qt::WindowState: Qt::WindowMinimized,
2734 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2736 \sa Qt::WindowState setWindowState()
2738 Qt::WindowStates QWidget::windowState() const
2740 return Qt::WindowStates(data->window_state);
2745 The function sets the window state on child widgets similar to
2746 setWindowState(). The difference is that the window state changed
2747 event has the isOverride() flag set. It exists mainly to keep
2748 Q3Workspace working.
2750 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2752 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2753 data->window_state = newstate;
2754 QApplication::sendEvent(this, &e);
2758 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2760 Sets the window state to \a windowState. The window state is a OR'ed
2761 combination of Qt::WindowState: Qt::WindowMinimized,
2762 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2764 If the window is not visible (i.e. isVisible() returns false), the
2765 window state will take effect when show() is called. For visible
2766 windows, the change is immediate. For example, to toggle between
2767 full-screen and normal mode, use the following code:
2769 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2771 In order to restore and activate a minimized window (while
2772 preserving its maximized and/or full-screen state), use the following:
2774 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2776 Calling this function will hide the widget. You must call show() to make
2777 the widget visible again.
2779 \note On some window systems Qt::WindowActive is not immediate, and may be
2780 ignored in certain cases.
2782 When the window state changes, the widget receives a changeEvent()
2783 of type QEvent::WindowStateChange.
2785 \sa Qt::WindowState windowState()
2789 \property QWidget::fullScreen
2790 \brief whether the widget is shown in full screen mode
2792 A widget in full screen mode occupies the whole screen area and does not
2793 display window decorations, such as a title bar.
2795 By default, this property is false.
2797 \sa windowState(), minimized, maximized
2799 bool QWidget::isFullScreen() const
2800 { return data->window_state & Qt::WindowFullScreen; }
2803 Shows the widget in full-screen mode.
2805 Calling this function only affects \l{isWindow()}{windows}.
2807 To return from full-screen mode, call showNormal().
2809 Full-screen mode works fine under Windows, but has certain
2810 problems under X. These problems are due to limitations of the
2811 ICCCM protocol that specifies the communication between X11
2812 clients and the window manager. ICCCM simply does not understand
2813 the concept of non-decorated full-screen windows. Therefore, the
2814 best we can do is to request a borderless window and place and
2815 resize it to fill the entire screen. Depending on the window
2816 manager, this may or may not work. The borderless window is
2817 requested using MOTIF hints, which are at least partially
2818 supported by virtually all modern window managers.
2820 An alternative would be to bypass the window manager entirely and
2821 create a window with the Qt::X11BypassWindowManagerHint flag. This
2822 has other severe problems though, like totally broken keyboard focus
2823 and very strange effects on desktop changes or when the user raises
2826 X11 window managers that follow modern post-ICCCM specifications
2827 support full-screen mode properly.
2829 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2831 void QWidget::showFullScreen()
2834 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2835 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2836 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2837 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2838 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2839 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2844 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2845 | Qt::WindowFullScreen);
2851 Shows the widget maximized.
2853 Calling this function only affects \l{isWindow()}{windows}.
2855 On X11, this function may not work properly with certain window
2856 managers. See the \l{Window Geometry} documentation for an explanation.
2858 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2860 void QWidget::showMaximized()
2864 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2865 | Qt::WindowMaximized);
2867 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2868 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2871 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2872 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2873 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2874 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2882 Restores the widget after it has been maximized or minimized.
2884 Calling this function only affects \l{isWindow()}{windows}.
2886 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2888 void QWidget::showNormal()
2892 setWindowState(windowState() & ~(Qt::WindowMinimized
2893 | Qt::WindowMaximized
2894 | Qt::WindowFullScreen));
2896 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2897 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2900 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2901 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2902 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2903 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2911 Returns true if this widget would become enabled if \a ancestor is
2912 enabled; otherwise returns false.
2916 This is the case if neither the widget itself nor every parent up
2917 to but excluding \a ancestor has been explicitly disabled.
2919 isEnabledTo(0) is equivalent to isEnabled().
2921 \sa setEnabled() enabled
2924 bool QWidget::isEnabledTo(QWidget* ancestor) const
2926 const QWidget * w = this;
2927 while (!w->testAttribute(Qt::WA_ForceDisabled)
2929 && w->parentWidget()
2930 && w->parentWidget() != ancestor)
2931 w = w->parentWidget();
2932 return !w->testAttribute(Qt::WA_ForceDisabled);
2935 #ifndef QT_NO_ACTION
2937 Appends the action \a action to this widget's list of actions.
2939 All QWidgets have a list of \l{QAction}s, however they can be
2940 represented graphically in many different ways. The default use of
2941 the QAction list (as returned by actions()) is to create a context
2944 A QWidget should only have one of each action and adding an action
2945 it already has will not cause the same action to be in the widget twice.
2947 The ownership of \a action is not transferred to this QWidget.
2949 \sa removeAction(), insertAction(), actions(), QMenu
2951 void QWidget::addAction(QAction *action)
2953 insertAction(0, action);
2957 Appends the actions \a actions to this widget's list of actions.
2959 \sa removeAction(), QMenu, addAction()
2961 void QWidget::addActions(QList<QAction*> actions)
2963 for(int i = 0; i < actions.count(); i++)
2964 insertAction(0, actions.at(i));
2968 Inserts the action \a action to this widget's list of actions,
2969 before the action \a before. It appends the action if \a before is 0 or
2970 \a before is not a valid action for this widget.
2972 A QWidget should only have one of each action.
2974 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2976 void QWidget::insertAction(QAction *before, QAction *action)
2979 qWarning("QWidget::insertAction: Attempt to insert null action");
2984 if(d->actions.contains(action))
2985 removeAction(action);
2987 int pos = d->actions.indexOf(before);
2990 pos = d->actions.size();
2992 d->actions.insert(pos, action);
2994 QActionPrivate *apriv = action->d_func();
2995 apriv->widgets.append(this);
2997 QActionEvent e(QEvent::ActionAdded, action, before);
2998 QApplication::sendEvent(this, &e);
3002 Inserts the actions \a actions to this widget's list of actions,
3003 before the action \a before. It appends the action if \a before is 0 or
3004 \a before is not a valid action for this widget.
3006 A QWidget can have at most one of each action.
3008 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
3010 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
3012 for(int i = 0; i < actions.count(); ++i)
3013 insertAction(before, actions.at(i));
3017 Removes the action \a action from this widget's list of actions.
3018 \sa insertAction(), actions(), insertAction()
3020 void QWidget::removeAction(QAction *action)
3027 QActionPrivate *apriv = action->d_func();
3028 apriv->widgets.removeAll(this);
3030 if (d->actions.removeAll(action)) {
3031 QActionEvent e(QEvent::ActionRemoved, action);
3032 QApplication::sendEvent(this, &e);
3037 Returns the (possibly empty) list of this widget's actions.
3039 \sa contextMenuPolicy, insertAction(), removeAction()
3041 QList<QAction*> QWidget::actions() const
3046 #endif // QT_NO_ACTION
3049 \fn bool QWidget::isEnabledToTLW() const
3052 This function is deprecated. It is equivalent to isEnabled()
3056 \property QWidget::enabled
3057 \brief whether the widget is enabled
3059 An enabled widget handles keyboard and mouse events; a disabled
3062 Some widgets display themselves differently when they are
3063 disabled. For example a button might draw its label grayed out. If
3064 your widget needs to know when it becomes enabled or disabled, you
3065 can use the changeEvent() with type QEvent::EnabledChange.
3067 Disabling a widget implicitly disables all its children. Enabling
3068 respectively enables all child widgets unless they have been
3069 explicitly disabled.
3071 By default, this property is true.
3073 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3075 void QWidget::setEnabled(bool enable)
3078 setAttribute(Qt::WA_ForceDisabled, !enable);
3079 d->setEnabled_helper(enable);
3082 void QWidgetPrivate::setEnabled_helper(bool enable)
3086 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3087 return; // nothing we can do
3089 if (enable != q->testAttribute(Qt::WA_Disabled))
3090 return; // nothing to do
3092 q->setAttribute(Qt::WA_Disabled, !enable);
3093 updateSystemBackground();
3095 if (!enable && q->window()->focusWidget() == q) {
3096 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3097 if (!parentIsEnabled || !q->focusNextChild())
3101 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3102 for (int i = 0; i < children.size(); ++i) {
3103 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3104 if (w && !w->testAttribute(attribute))
3105 w->d_func()->setEnabled_helper(enable);
3107 #if defined(Q_WS_X11)
3108 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3109 // enforce the windows behavior of clearing the cursor on
3111 qt_x11_enforce_cursor(q);
3114 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3115 // enforce the windows behavior of clearing the cursor on
3117 qt_qpa_set_cursor(q, false);
3119 #if defined(Q_WS_MAC)
3120 setEnabled_helper_sys(enable);
3123 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3124 QWidget *focusWidget = effectiveFocusWidget();
3127 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3128 qApp->inputPanel()->update(Qt::ImEnabled);
3130 qApp->inputPanel()->reset();
3131 qApp->inputPanel()->update(Qt::ImEnabled);
3135 QEvent e(QEvent::EnabledChange);
3136 QApplication::sendEvent(q, &e);
3140 \property QWidget::acceptDrops
3141 \brief whether drop events are enabled for this widget
3143 Setting this property to true announces to the system that this
3144 widget \e may be able to accept drop events.
3146 If the widget is the desktop (windowType() == Qt::Desktop), this may
3147 fail if another application is using the desktop; you can call
3148 acceptDrops() to test if this occurs.
3150 \warning Do not modify this property in a drag and drop event handler.
3152 By default, this property is false.
3156 bool QWidget::acceptDrops() const
3158 return testAttribute(Qt::WA_AcceptDrops);
3161 void QWidget::setAcceptDrops(bool on)
3163 setAttribute(Qt::WA_AcceptDrops, on);
3169 Disables widget input events if \a disable is true; otherwise
3170 enables input events.
3172 See the \l enabled documentation for more information.
3174 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3176 void QWidget::setDisabled(bool disable)
3178 setEnabled(!disable);
3182 \property QWidget::frameGeometry
3183 \brief geometry of the widget relative to its parent including any
3186 See the \l{Window Geometry} documentation for an overview of geometry
3187 issues with windows.
3189 By default, this property contains a value that depends on the user's
3190 platform and screen geometry.
3192 \sa geometry() x() y() pos()
3194 QRect QWidget::frameGeometry() const
3197 if (isWindow() && ! (windowType() == Qt::Popup)) {
3198 QRect fs = d->frameStrut();
3199 return QRect(data->crect.x() - fs.left(),
3200 data->crect.y() - fs.top(),
3201 data->crect.width() + fs.left() + fs.right(),
3202 data->crect.height() + fs.top() + fs.bottom());
3208 \property QWidget::x
3210 \brief the x coordinate of the widget relative to its parent including
3213 See the \l{Window Geometry} documentation for an overview of geometry
3214 issues with windows.
3216 By default, this property has a value of 0.
3218 \sa frameGeometry, y, pos
3220 int QWidget::x() const
3223 if (isWindow() && ! (windowType() == Qt::Popup))
3224 return data->crect.x() - d->frameStrut().left();
3225 return data->crect.x();
3229 \property QWidget::y
3230 \brief the y coordinate of the widget relative to its parent and
3231 including any window frame
3233 See the \l{Window Geometry} documentation for an overview of geometry
3234 issues with windows.
3236 By default, this property has a value of 0.
3238 \sa frameGeometry, x, pos
3240 int QWidget::y() const
3243 if (isWindow() && ! (windowType() == Qt::Popup))
3244 return data->crect.y() - d->frameStrut().top();
3245 return data->crect.y();
3249 \property QWidget::pos
3250 \brief the position of the widget within its parent widget
3252 If the widget is a window, the position is that of the widget on
3253 the desktop, including its frame.
3255 When changing the position, the widget, if visible, receives a
3256 move event (moveEvent()) immediately. If the widget is not
3257 currently visible, it is guaranteed to receive an event before it
3260 By default, this property contains a position that refers to the
3263 \warning Calling move() or setGeometry() inside moveEvent() can
3264 lead to infinite recursion.
3266 See the \l{Window Geometry} documentation for an overview of geometry
3267 issues with windows.
3269 \sa frameGeometry, size x(), y()
3271 QPoint QWidget::pos() const
3274 if (isWindow() && ! (windowType() == Qt::Popup)) {
3275 QRect fs = d->frameStrut();
3276 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3278 return data->crect.topLeft();
3282 \property QWidget::geometry
3283 \brief the geometry of the widget relative to its parent and
3284 excluding the window frame
3286 When changing the geometry, the widget, if visible, receives a
3287 move event (moveEvent()) and/or a resize event (resizeEvent())
3288 immediately. If the widget is not currently visible, it is
3289 guaranteed to receive appropriate events before it is shown.
3291 The size component is adjusted if it lies outside the range
3292 defined by minimumSize() and maximumSize().
3294 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3295 can lead to infinite recursion.
3297 See the \l{Window Geometry} documentation for an overview of geometry
3298 issues with windows.
3300 By default, this property contains a value that depends on the user's
3301 platform and screen geometry.
3303 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3304 resizeEvent(), minimumSize(), maximumSize()
3308 \property QWidget::normalGeometry
3310 \brief the geometry of the widget as it will appear when shown as
3311 a normal (not maximized or full screen) top-level widget
3313 For child widgets this property always holds an empty rectangle.
3315 By default, this property contains an empty rectangle.
3317 \sa QWidget::windowState(), QWidget::geometry
3321 \property QWidget::size
3322 \brief the size of the widget excluding any window frame
3324 If the widget is visible when it is being resized, it receives a resize event
3325 (resizeEvent()) immediately. If the widget is not currently
3326 visible, it is guaranteed to receive an event before it is shown.
3328 The size is adjusted if it lies outside the range defined by
3329 minimumSize() and maximumSize().
3331 By default, this property contains a value that depends on the user's
3332 platform and screen geometry.
3334 \warning Calling resize() or setGeometry() inside resizeEvent() can
3335 lead to infinite recursion.
3337 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3338 appear on screen. This also applies to windows.
3340 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3344 \property QWidget::width
3345 \brief the width of the widget excluding any window frame
3347 See the \l{Window Geometry} documentation for an overview of geometry
3348 issues with windows.
3350 \note Do not use this function to find the width of a screen on
3351 a \l{QDesktopWidget}{multiple screen desktop}. Read
3352 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3354 By default, this property contains a value that depends on the user's
3355 platform and screen geometry.
3357 \sa geometry, height, size
3361 \property QWidget::height
3362 \brief the height of the widget excluding any window frame
3364 See the \l{Window Geometry} documentation for an overview of geometry
3365 issues with windows.
3367 \note Do not use this function to find the height of a screen
3368 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3369 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3371 By default, this property contains a value that depends on the user's
3372 platform and screen geometry.
3374 \sa geometry, width, size
3378 \property QWidget::rect
3379 \brief the internal geometry of the widget excluding any window
3382 The rect property equals QRect(0, 0, width(), height()).
3384 See the \l{Window Geometry} documentation for an overview of geometry
3385 issues with windows.
3387 By default, this property contains a value that depends on the user's
3388 platform and screen geometry.
3394 QRect QWidget::normalGeometry() const
3397 if (!d->extra || !d->extra->topextra)
3400 if (!isMaximized() && !isFullScreen())
3403 return d->topData()->normalGeometry;
3408 \property QWidget::childrenRect
3409 \brief the bounding rectangle of the widget's children
3411 Hidden children are excluded.
3413 By default, for a widget with no children, this property contains a
3414 rectangle with zero width and height located at the origin.
3416 \sa childrenRegion() geometry()
3419 QRect QWidget::childrenRect() const
3422 QRect r(0, 0, 0, 0);
3423 for (int i = 0; i < d->children.size(); ++i) {
3424 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3425 if (w && !w->isWindow() && !w->isHidden())
3432 \property QWidget::childrenRegion
3433 \brief the combined region occupied by the widget's children
3435 Hidden children are excluded.
3437 By default, for a widget with no children, this property contains an
3440 \sa childrenRect() geometry() mask()
3443 QRegion QWidget::childrenRegion() const
3447 for (int i = 0; i < d->children.size(); ++i) {
3448 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3449 if (w && !w->isWindow() && !w->isHidden()) {
3450 QRegion mask = w->mask();
3454 r |= mask.translated(w->pos());
3462 \property QWidget::minimumSize
3463 \brief the widget's minimum size
3465 The widget cannot be resized to a smaller size than the minimum
3466 widget size. The widget's size is forced to the minimum size if
3467 the current size is smaller.
3469 The minimum size set by this function will override the minimum size
3470 defined by QLayout. In order to unset the minimum size, use a
3471 value of \c{QSize(0, 0)}.
3473 By default, this property contains a size with zero width and height.
3475 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3478 QSize QWidget::minimumSize() const
3481 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3485 \property QWidget::maximumSize
3486 \brief the widget's maximum size in pixels
3488 The widget cannot be resized to a larger size than the maximum
3491 By default, this property contains a size in which both width and height
3492 have values of 16777215.
3494 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3497 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3500 QSize QWidget::maximumSize() const
3503 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3504 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3509 \property QWidget::minimumWidth
3510 \brief the widget's minimum width in pixels
3512 This property corresponds to the width held by the \l minimumSize property.
3514 By default, this property has a value of 0.
3516 \sa minimumSize, minimumHeight
3520 \property QWidget::minimumHeight
3521 \brief the widget's minimum height in pixels
3523 This property corresponds to the height held by the \l minimumSize property.
3525 By default, this property has a value of 0.
3527 \sa minimumSize, minimumWidth
3531 \property QWidget::maximumWidth
3532 \brief the widget's maximum width in pixels
3534 This property corresponds to the width held by the \l maximumSize property.
3536 By default, this property contains a value of 16777215.
3538 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3541 \sa maximumSize, maximumHeight
3545 \property QWidget::maximumHeight
3546 \brief the widget's maximum height in pixels
3548 This property corresponds to the height held by the \l maximumSize property.
3550 By default, this property contains a value of 16777215.
3552 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3555 \sa maximumSize, maximumWidth
3559 \property QWidget::sizeIncrement
3560 \brief the size increment of the widget
3562 When the user resizes the window, the size will move in steps of
3563 sizeIncrement().width() pixels horizontally and
3564 sizeIncrement.height() pixels vertically, with baseSize() as the
3565 basis. Preferred widget sizes are for non-negative integers \e i
3567 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3569 Note that while you can set the size increment for all widgets, it
3570 only affects windows.
3572 By default, this property contains a size with zero width and height.
3574 \warning The size increment has no effect under Windows, and may
3575 be disregarded by the window manager on X11.
3577 \sa size, minimumSize, maximumSize
3579 QSize QWidget::sizeIncrement() const
3582 return (d->extra && d->extra->topextra)
3583 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3588 \property QWidget::baseSize
3589 \brief the base size of the widget
3591 The base size is used to calculate a proper widget size if the
3592 widget defines sizeIncrement().
3594 By default, for a newly-created widget, this property contains a size with
3595 zero width and height.
3597 \sa setSizeIncrement()
3600 QSize QWidget::baseSize() const
3603 return (d->extra != 0 && d->extra->topextra != 0)
3604 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3608 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3612 int mw = minw, mh = minh;
3613 if (mw == QWIDGETSIZE_MAX)
3615 if (mh == QWIDGETSIZE_MAX)
3617 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3618 qWarning("QWidget::setMinimumSize: (%s/%s) "
3619 "The largest allowed size is (%d,%d)",
3620 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3622 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3623 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3625 if (minw < 0 || minh < 0) {
3626 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3628 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3629 minw = mw = qMax(minw, 0);
3630 minh = mh = qMax(minh, 0);
3633 if (extra->minw == mw && extra->minh == mh)
3637 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3644 This function corresponds to setMinimumSize(QSize(minw, minh)).
3645 Sets the minimum width to \a minw and the minimum height to \a
3649 void QWidget::setMinimumSize(int minw, int minh)
3652 if (!d->setMinimumSize_helper(minw, minh))
3656 d->setConstraints_sys();
3657 if (minw > width() || minh > height()) {
3658 bool resized = testAttribute(Qt::WA_Resized);
3659 bool maximized = isMaximized();
3660 resize(qMax(minw,width()), qMax(minh,height()));
3661 setAttribute(Qt::WA_Resized, resized); //not a user resize
3663 data->window_state = data->window_state | Qt::WindowMaximized;
3665 #ifndef QT_NO_GRAPHICSVIEW
3667 if (d->extra->proxyWidget)
3668 d->extra->proxyWidget->setMinimumSize(minw, minh);
3671 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3674 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3677 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3678 qWarning("QWidget::setMaximumSize: (%s/%s) "
3679 "The largest allowed size is (%d,%d)",
3680 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3682 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3683 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3685 if (maxw < 0 || maxh < 0) {
3686 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3688 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3689 maxw = qMax(maxw, 0);
3690 maxh = qMax(maxh, 0);
3693 if (extra->maxw == maxw && extra->maxh == maxh)
3697 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3698 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3705 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3706 maxh)). Sets the maximum width to \a maxw and the maximum height
3709 void QWidget::setMaximumSize(int maxw, int maxh)
3712 if (!d->setMaximumSize_helper(maxw, maxh))
3716 d->setConstraints_sys();
3717 if (maxw < width() || maxh < height()) {
3718 bool resized = testAttribute(Qt::WA_Resized);
3719 resize(qMin(maxw,width()), qMin(maxh,height()));
3720 setAttribute(Qt::WA_Resized, resized); //not a user resize
3723 #ifndef QT_NO_GRAPHICSVIEW
3725 if (d->extra->proxyWidget)
3726 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3730 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3736 Sets the x (width) size increment to \a w and the y (height) size
3739 void QWidget::setSizeIncrement(int w, int h)
3743 QTLWExtra* x = d->topData();
3744 if (x->incw == w && x->inch == h)
3749 d->setConstraints_sys();
3755 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3756 the widgets base size to width \a basew and height \a baseh.
3758 void QWidget::setBaseSize(int basew, int baseh)
3762 QTLWExtra* x = d->topData();
3763 if (x->basew == basew && x->baseh == baseh)
3768 d->setConstraints_sys();
3772 Sets both the minimum and maximum sizes of the widget to \a s,
3773 thereby preventing it from ever growing or shrinking.
3775 This will override the default size constraints set by QLayout.
3777 To remove constraints, set the size to QWIDGETSIZE_MAX.
3779 Alternatively, if you want the widget to have a
3780 fixed size based on its contents, you can call
3781 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3783 \sa maximumSize, minimumSize
3786 void QWidget::setFixedSize(const QSize & s)
3788 setFixedSize(s.width(), s.height());
3793 \fn void QWidget::setFixedSize(int w, int h)
3796 Sets the width of the widget to \a w and the height to \a h.
3799 void QWidget::setFixedSize(int w, int h)
3802 bool minSizeSet = d->setMinimumSize_helper(w, h);
3803 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3804 if (!minSizeSet && !maxSizeSet)
3808 d->setConstraints_sys();
3810 d->updateGeometry_helper(true);
3812 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3816 void QWidget::setMinimumWidth(int w)
3820 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3821 setMinimumSize(w, minimumSize().height());
3822 d->extra->explicitMinSize = expl;
3825 void QWidget::setMinimumHeight(int h)
3829 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3830 setMinimumSize(minimumSize().width(), h);
3831 d->extra->explicitMinSize = expl;
3834 void QWidget::setMaximumWidth(int w)
3838 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3839 setMaximumSize(w, maximumSize().height());
3840 d->extra->explicitMaxSize = expl;
3843 void QWidget::setMaximumHeight(int h)
3847 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3848 setMaximumSize(maximumSize().width(), h);
3849 d->extra->explicitMaxSize = expl;
3853 Sets both the minimum and maximum width of the widget to \a w
3854 without changing the heights. Provided for convenience.
3856 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3859 void QWidget::setFixedWidth(int w)
3863 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3864 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3865 setMinimumSize(w, minimumSize().height());
3866 setMaximumSize(w, maximumSize().height());
3867 d->extra->explicitMinSize = explMin;
3868 d->extra->explicitMaxSize = explMax;
3873 Sets both the minimum and maximum heights of the widget to \a h
3874 without changing the widths. Provided for convenience.
3876 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3879 void QWidget::setFixedHeight(int h)
3883 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3884 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3885 setMinimumSize(minimumSize().width(), h);
3886 setMaximumSize(maximumSize().width(), h);
3887 d->extra->explicitMinSize = explMin;
3888 d->extra->explicitMaxSize = explMax;
3893 Translates the widget coordinate \a pos to the coordinate system
3894 of \a parent. The \a parent must not be 0 and must be a parent
3895 of the calling widget.
3897 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3900 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3904 const QWidget * w = this;
3905 while (w != parent) {
3906 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3907 "parent must be in parent hierarchy");
3908 p = w->mapToParent(p);
3909 w = w->parentWidget();
3917 Translates the widget coordinate \a pos from the coordinate system
3918 of \a parent to this widget's coordinate system. The \a parent
3919 must not be 0 and must be a parent of the calling widget.
3921 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3924 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3928 const QWidget * w = this;
3929 while (w != parent) {
3930 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3931 "parent must be in parent hierarchy");
3933 p = w->mapFromParent(p);
3934 w = w->parentWidget();
3942 Translates the widget coordinate \a pos to a coordinate in the
3945 Same as mapToGlobal() if the widget has no parent.
3947 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3950 QPoint QWidget::mapToParent(const QPoint &pos) const
3952 return pos + data->crect.topLeft();
3956 Translates the parent widget coordinate \a pos to widget
3959 Same as mapFromGlobal() if the widget has no parent.
3961 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3964 QPoint QWidget::mapFromParent(const QPoint &pos) const
3966 return pos - data->crect.topLeft();
3971 Returns the window for this widget, i.e. the next ancestor widget
3972 that has (or could have) a window-system frame.
3974 If the widget is a window, the widget itself is returned.
3976 Typical usage is changing the window title:
3978 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3983 QWidget *QWidget::window() const
3985 QWidget *w = (QWidget *)this;
3986 QWidget *p = w->parentWidget();
3987 while (!w->isWindow() && p) {
3989 p = p->parentWidget();
3997 Returns the native parent for this widget, i.e. the next ancestor widget
3998 that has a system identifier, or 0 if it does not have any native parent.
4000 \sa effectiveWinId()
4002 QWidget *QWidget::nativeParentWidget() const
4004 QWidget *parent = parentWidget();
4005 while (parent && !parent->internalWinId())
4006 parent = parent->parentWidget();
4010 /*! \fn QWidget *QWidget::topLevelWidget() const
4013 Use window() instead.
4019 Returns the background role of the widget.
4021 The background role defines the brush from the widget's \l palette that
4022 is used to render the background.
4024 If no explicit background role is set, the widget inherts its parent
4025 widget's background role.
4027 \sa setBackgroundRole(), foregroundRole()
4029 QPalette::ColorRole QWidget::backgroundRole() const
4032 const QWidget *w = this;
4034 QPalette::ColorRole role = w->d_func()->bg_role;
4035 if (role != QPalette::NoRole)
4037 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4039 w = w->parentWidget();
4041 return QPalette::Window;
4045 Sets the background role of the widget to \a role.
4047 The background role defines the brush from the widget's \l palette that
4048 is used to render the background.
4050 If \a role is QPalette::NoRole, then the widget inherits its
4051 parent's background role.
4053 Note that styles are free to choose any color from the palette.
4054 You can modify the palette or set a style sheet if you don't
4055 achieve the result you want with setBackgroundRole().
4057 \sa backgroundRole(), foregroundRole()
4060 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4064 d->updateSystemBackground();
4065 d->propagatePaletteChange();
4066 d->updateIsOpaque();
4070 Returns the foreground role.
4072 The foreground role defines the color from the widget's \l palette that
4073 is used to draw the foreground.
4075 If no explicit foreground role is set, the function returns a role
4076 that contrasts with the background role.
4078 \sa setForegroundRole(), backgroundRole()
4080 QPalette::ColorRole QWidget::foregroundRole() const
4083 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4084 if (rl != QPalette::NoRole)
4086 QPalette::ColorRole role = QPalette::WindowText;
4087 switch (backgroundRole()) {
4088 case QPalette::Button:
4089 role = QPalette::ButtonText;
4091 case QPalette::Base:
4092 role = QPalette::Text;
4094 case QPalette::Dark:
4095 case QPalette::Shadow:
4096 role = QPalette::Light;
4098 case QPalette::Highlight:
4099 role = QPalette::HighlightedText;
4101 case QPalette::ToolTipBase:
4102 role = QPalette::ToolTipText;
4111 Sets the foreground role of the widget to \a role.
4113 The foreground role defines the color from the widget's \l palette that
4114 is used to draw the foreground.
4116 If \a role is QPalette::NoRole, the widget uses a foreground role
4117 that contrasts with the background role.
4119 Note that styles are free to choose any color from the palette.
4120 You can modify the palette or set a style sheet if you don't
4121 achieve the result you want with setForegroundRole().
4123 \sa foregroundRole(), backgroundRole()
4125 void QWidget::setForegroundRole(QPalette::ColorRole role)
4129 d->updateSystemBackground();
4130 d->propagatePaletteChange();
4134 \property QWidget::palette
4135 \brief the widget's palette
4137 This property describes the widget's palette. The palette is used by the
4138 widget's style when rendering standard components, and is available as a
4139 means to ensure that custom widgets can maintain consistency with the
4140 native platform's look and feel. It's common that different platforms, or
4141 different styles, have different palettes.
4143 When you assign a new palette to a widget, the color roles from this
4144 palette are combined with the widget's default palette to form the
4145 widget's final palette. The palette entry for the widget's background role
4146 is used to fill the widget's background (see QWidget::autoFillBackground),
4147 and the foreground role initializes QPainter's pen.
4149 The default depends on the system environment. QApplication maintains a
4150 system/theme palette which serves as a default for all widgets. There may
4151 also be special palette defaults for certain types of widgets (e.g., on
4152 Windows XP and Vista, all classes that derive from QMenuBar have a special
4153 default palette). You can also define default palettes for widgets
4154 yourself by passing a custom palette and the name of a widget to
4155 QApplication::setPalette(). Finally, the style always has the option of
4156 polishing the palette as it's assigned (see QStyle::polish()).
4158 QWidget propagates explicit palette roles from parent to child. If you
4159 assign a brush or color to a specific role on a palette and assign that
4160 palette to a widget, that role will propagate to all the widget's
4161 children, overriding any system defaults for that role. Note that palettes
4162 by default don't propagate to windows (see isWindow()) unless the
4163 Qt::WA_WindowPropagation attribute is enabled.
4165 QWidget's palette propagation is similar to its font propagation.
4167 The current style, which is used to render the content of all standard Qt
4168 widgets, is free to choose colors and brushes from the widget palette, or
4169 in some cases, to ignore the palette (partially, or completely). In
4170 particular, certain styles like GTK style, Mac style, Windows XP, and
4171 Vista style, depend on third party APIs to render the content of widgets,
4172 and these styles typically do not follow the palette. Because of this,
4173 assigning roles to a widget's palette is not guaranteed to change the
4174 appearance of the widget. Instead, you may choose to apply a \l
4175 styleSheet. You can refer to our Knowledge Base article
4176 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4179 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4180 When using style sheets, the palette of a widget can be customized using
4181 the "color", "background-color", "selection-color",
4182 "selection-background-color" and "alternate-background-color".
4184 \sa QApplication::palette(), QWidget::font()
4186 const QPalette &QWidget::palette() const
4189 data->pal.setCurrentColorGroup(QPalette::Disabled);
4190 } else if ((!isVisible() || isActiveWindow())
4191 #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
4192 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4195 data->pal.setCurrentColorGroup(QPalette::Active);
4198 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4199 if (qt_mac_can_clickThrough(this))
4200 data->pal.setCurrentColorGroup(QPalette::Active);
4203 data->pal.setCurrentColorGroup(QPalette::Inactive);
4208 void QWidget::setPalette(const QPalette &palette)
4211 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4213 // Determine which palette is inherited from this widget's ancestors and
4214 // QApplication::palette, resolve this against \a palette (attributes from
4215 // the inherited palette are copied over this widget's palette). Then
4216 // propagate this palette to this widget's children.
4217 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4218 QPalette resolvedPalette = palette.resolve(naturalPalette);
4219 d->setPalette_helper(resolvedPalette);
4225 Returns the palette that the widget \a w inherits from its ancestors and
4226 QApplication::palette. \a inheritedMask is the combination of the widget's
4227 ancestors palette request masks (i.e., which attributes from the parent
4228 widget's palette are implicitly imposed on this widget by the user). Note
4229 that this font does not take into account the palette set on \a w itself.
4231 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4234 QPalette naturalPalette = QApplication::palette(q);
4235 if (!q->testAttribute(Qt::WA_StyleSheet)
4236 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4237 #ifndef QT_NO_GRAPHICSVIEW
4238 || (extra && extra->proxyWidget)
4239 #endif //QT_NO_GRAPHICSVIEW
4241 if (QWidget *p = q->parentWidget()) {
4242 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4243 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4244 QPalette inheritedPalette = p->palette();
4245 inheritedPalette.resolve(inheritedMask);
4246 naturalPalette = inheritedPalette.resolve(naturalPalette);
4248 naturalPalette = p->palette();
4252 #ifndef QT_NO_GRAPHICSVIEW
4253 else if (extra && extra->proxyWidget) {
4254 QPalette inheritedPalette = extra->proxyWidget->palette();
4255 inheritedPalette.resolve(inheritedMask);
4256 naturalPalette = inheritedPalette.resolve(naturalPalette);
4258 #endif //QT_NO_GRAPHICSVIEW
4260 naturalPalette.resolve(0);
4261 return naturalPalette;
4266 Determine which palette is inherited from this widget's ancestors and
4267 QApplication::palette, resolve this against this widget's palette
4268 (attributes from the inherited palette are copied over this widget's
4269 palette). Then propagate this palette to this widget's children.
4271 void QWidgetPrivate::resolvePalette()
4273 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4274 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4275 setPalette_helper(resolvedPalette);
4278 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4281 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4284 updateSystemBackground();
4285 propagatePaletteChange();
4292 \property QWidget::font
4293 \brief the font currently set for the widget
4295 This property describes the widget's requested font. The font is used by
4296 the widget's style when rendering standard components, and is available as
4297 a means to ensure that custom widgets can maintain consistency with the
4298 native platform's look and feel. It's common that different platforms, or
4299 different styles, define different fonts for an application.
4301 When you assign a new font to a widget, the properties from this font are
4302 combined with the widget's default font to form the widget's final
4303 font. You can call fontInfo() to get a copy of the widget's final
4304 font. The final font is also used to initialize QPainter's font.
4306 The default depends on the system environment. QApplication maintains a
4307 system/theme font which serves as a default for all widgets. There may
4308 also be special font defaults for certain types of widgets. You can also
4309 define default fonts for widgets yourself by passing a custom font and the
4310 name of a widget to QApplication::setFont(). Finally, the font is matched
4311 against Qt's font database to find the best match.
4313 QWidget propagates explicit font properties from parent to child. If you
4314 change a specific property on a font and assign that font to a widget,
4315 that property will propagate to all the widget's children, overriding any
4316 system defaults for that property. Note that fonts by default don't
4317 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4318 attribute is enabled.
4320 QWidget's font propagation is similar to its palette propagation.
4322 The current style, which is used to render the content of all standard Qt
4323 widgets, is free to choose to use the widget font, or in some cases, to
4324 ignore it (partially, or completely). In particular, certain styles like
4325 GTK style, Mac style, Windows XP, and Vista style, apply special
4326 modifications to the widget font to match the platform's native look and
4327 feel. Because of this, assigning properties to a widget's font is not
4328 guaranteed to change the appearance of the widget. Instead, you may choose
4329 to apply a \l styleSheet.
4331 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4332 style sheets will take precedence if the settings conflict.
4334 \sa fontInfo(), fontMetrics()
4337 void QWidget::setFont(const QFont &font)
4341 #ifndef QT_NO_STYLE_STYLESHEET
4342 const QStyleSheetStyle* style;
4343 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4344 style->saveWidgetFont(this, font);
4348 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4350 // Determine which font is inherited from this widget's ancestors and
4351 // QApplication::font, resolve this against \a font (attributes from the
4352 // inherited font are copied over). Then propagate this font to this
4353 // widget's children.
4354 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4355 QFont resolvedFont = font.resolve(naturalFont);
4356 d->setFont_helper(resolvedFont);
4362 Returns the font that the widget \a w inherits from its ancestors and
4363 QApplication::font. \a inheritedMask is the combination of the widget's
4364 ancestors font request masks (i.e., which attributes from the parent
4365 widget's font are implicitly imposed on this widget by the user). Note
4366 that this font does not take into account the font set on \a w itself.
4368 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4369 is applied, fonts are not propagated anymore
4371 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4374 QFont naturalFont = QApplication::font(q);
4375 if (!q->testAttribute(Qt::WA_StyleSheet)
4376 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4377 #ifndef QT_NO_GRAPHICSVIEW
4378 || (extra && extra->proxyWidget)
4379 #endif //QT_NO_GRAPHICSVIEW
4381 if (QWidget *p = q->parentWidget()) {
4382 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4383 if (!naturalFont.isCopyOf(QApplication::font())) {
4384 QFont inheritedFont = p->font();
4385 inheritedFont.resolve(inheritedMask);
4386 naturalFont = inheritedFont.resolve(naturalFont);
4388 naturalFont = p->font();
4392 #ifndef QT_NO_GRAPHICSVIEW
4393 else if (extra && extra->proxyWidget) {
4394 QFont inheritedFont = extra->proxyWidget->font();
4395 inheritedFont.resolve(inheritedMask);
4396 naturalFont = inheritedFont.resolve(naturalFont);
4398 #endif //QT_NO_GRAPHICSVIEW
4400 naturalFont.resolve(0);
4407 Determine which font is implicitly imposed on this widget by its ancestors
4408 and QApplication::font, resolve this against its own font (attributes from
4409 the implicit font are copied over). Then propagate this font to this
4412 void QWidgetPrivate::resolveFont()
4414 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4415 QFont resolvedFont = data.fnt.resolve(naturalFont);
4416 setFont_helper(resolvedFont);
4422 Assign \a font to this widget, and propagate it to all children, except
4423 style sheet widgets (handled differently) and windows that don't enable
4424 window propagation. \a implicitMask is the union of all ancestor widgets'
4425 font request masks, and determines which attributes from this widget's
4426 font should propagate.
4428 void QWidgetPrivate::updateFont(const QFont &font)
4431 #ifndef QT_NO_STYLE_STYLESHEET
4432 const QStyleSheetStyle* cssStyle;
4433 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4436 data.fnt = QFont(font, q);
4437 #if defined(Q_WS_X11)
4438 // make sure the font set on this widget is associated with the correct screen
4439 data.fnt.x11SetScreen(xinfo.screen());
4441 // Combine new mask with natural mask and propagate to children.
4442 #ifndef QT_NO_GRAPHICSVIEW
4443 if (!q->parentWidget() && extra && extra->proxyWidget) {
4444 QGraphicsProxyWidget *p = extra->proxyWidget;
4445 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4447 #endif //QT_NO_GRAPHICSVIEW
4448 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4449 inheritedFontResolveMask = 0;
4451 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4453 for (int i = 0; i < children.size(); ++i) {
4454 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4457 #ifndef QT_NO_STYLE_STYLESHEET
4458 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4459 // Style sheets follow a different font propagation scheme.
4461 cssStyle->updateStyleSheetFont(w);
4463 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4464 // Propagate font changes.
4465 QWidgetPrivate *wd = w->d_func();
4466 wd->inheritedFontResolveMask = newMask;
4472 #ifndef QT_NO_STYLE_STYLESHEET
4474 cssStyle->updateStyleSheetFont(q);
4478 QEvent e(QEvent::FontChange);
4479 QApplication::sendEvent(q, &e);
4482 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4486 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4488 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4489 if (!children.isEmpty()) {
4490 for (int i = 0; i < children.size(); ++i) {
4491 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4492 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4493 w->d_func()->setLayoutDirection_helper(direction);
4496 QEvent e(QEvent::LayoutDirectionChange);
4497 QApplication::sendEvent(q, &e);
4500 void QWidgetPrivate::resolveLayoutDirection()
4503 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4504 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4508 \property QWidget::layoutDirection
4510 \brief the layout direction for this widget
4512 By default, this property is set to Qt::LeftToRight.
4514 When the layout direction is set on a widget, it will propagate to
4515 the widget's children, but not to a child that is a window and not
4516 to a child for which setLayoutDirection() has been explicitly
4517 called. Also, child widgets added \e after setLayoutDirection()
4518 has been called for the parent do not inherit the parent's layout
4521 This method no longer affects text layout direction since Qt 4.7.
4523 \sa QApplication::layoutDirection
4525 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4529 if (direction == Qt::LayoutDirectionAuto) {
4530 unsetLayoutDirection();
4534 setAttribute(Qt::WA_SetLayoutDirection);
4535 d->setLayoutDirection_helper(direction);
4538 Qt::LayoutDirection QWidget::layoutDirection() const
4540 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4543 void QWidget::unsetLayoutDirection()
4546 setAttribute(Qt::WA_SetLayoutDirection, false);
4547 d->resolveLayoutDirection();
4551 \fn QFontMetrics QWidget::fontMetrics() const
4553 Returns the font metrics for the widget's current font.
4554 Equivalent to QFontMetrics(widget->font()).
4556 \sa font(), fontInfo(), setFont()
4560 \fn QFontInfo QWidget::fontInfo() const
4562 Returns the font info for the widget's current font.
4563 Equivalent to QFontInto(widget->font()).
4565 \sa font(), fontMetrics(), setFont()
4570 \property QWidget::cursor
4571 \brief the cursor shape for this widget
4573 The mouse cursor will assume this shape when it's over this
4574 widget. See the \link Qt::CursorShape list of predefined cursor
4575 objects\endlink for a range of useful shapes.
4577 An editor widget might use an I-beam cursor:
4578 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4580 If no cursor has been set, or after a call to unsetCursor(), the
4581 parent's cursor is used.
4583 By default, this property contains a cursor with the Qt::ArrowCursor
4586 Some underlying window implementations will reset the cursor if it
4587 leaves a widget even if the mouse is grabbed. If you want to have
4588 a cursor set for all widgets, even when outside the window, consider
4589 QApplication::setOverrideCursor().
4591 \sa QApplication::setOverrideCursor()
4594 #ifndef QT_NO_CURSOR
4595 QCursor QWidget::cursor() const
4598 if (testAttribute(Qt::WA_SetCursor))
4599 return (d->extra && d->extra->curs)
4601 : QCursor(Qt::ArrowCursor);
4602 if (isWindow() || !parentWidget())
4603 return QCursor(Qt::ArrowCursor);
4604 return parentWidget()->cursor();
4607 void QWidget::setCursor(const QCursor &cursor)
4610 // On Mac we must set the cursor even if it is the ArrowCursor.
4611 #if !defined(Q_WS_MAC)
4612 if (cursor.shape() != Qt::ArrowCursor
4613 || (d->extra && d->extra->curs))
4617 QCursor *newCursor = new QCursor(cursor);
4618 delete d->extra->curs;
4619 d->extra->curs = newCursor;
4621 setAttribute(Qt::WA_SetCursor);
4622 d->setCursor_sys(cursor);
4624 QEvent event(QEvent::CursorChange);
4625 QApplication::sendEvent(this, &event);
4628 void QWidget::unsetCursor()
4632 delete d->extra->curs;
4636 setAttribute(Qt::WA_SetCursor, false);
4637 d->unsetCursor_sys();
4639 QEvent event(QEvent::CursorChange);
4640 QApplication::sendEvent(this, &event);
4646 \enum QWidget::RenderFlag
4648 This enum describes how to render the widget when calling QWidget::render().
4650 \value DrawWindowBackground If you enable this option, the widget's background
4651 is rendered into the target even if autoFillBackground is not set. By default,
4652 this option is enabled.
4654 \value DrawChildren If you enable this option, the widget's children
4655 are rendered recursively into the target. By default, this option is enabled.
4657 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4658 is ignored when rendering into the target. By default, this option is disabled.
4666 Renders the \a sourceRegion of this widget into the \a target
4667 using \a renderFlags to determine how to render. Rendering
4668 starts at \a targetOffset in the \a target. For example:
4670 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4672 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4673 the region, i.e. the entire widget.
4675 Ensure that you call QPainter::end() for the \a target device's
4676 active painter (if any) before rendering. For example:
4678 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4680 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4681 or QGLWidget::renderPixmap() instead.
4683 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4684 const QRegion &sourceRegion, RenderFlags renderFlags)
4686 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4692 Renders the widget into the \a painter's QPainter::device().
4694 Transformations and settings applied to the \a painter will be used
4697 \note The \a painter must be active. On Mac OS X the widget will be
4698 rendered into a QPixmap and then drawn by the \a painter.
4700 \sa QPainter::device()
4702 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4703 const QRegion &sourceRegion, RenderFlags renderFlags)
4706 qWarning("QWidget::render: Null pointer to painter");
4710 if (!painter->isActive()) {
4711 qWarning("QWidget::render: Cannot render with an inactive painter");
4715 const qreal opacity = painter->opacity();
4716 if (qFuzzyIsNull(opacity))
4717 return; // Fully transparent.
4720 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4721 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4723 if (toBePainted.isEmpty())
4728 d->extra->inRenderWithPainter = true;
4731 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4733 QPaintEngine *engine = painter->paintEngine();
4735 QPaintEnginePrivate *enginePriv = engine->d_func();
4736 Q_ASSERT(enginePriv);
4737 QPaintDevice *target = engine->paintDevice();
4740 // Render via a pixmap when dealing with non-opaque painters or printers.
4741 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4742 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4743 d->extra->inRenderWithPainter = false;
4747 // Set new shared painter.
4748 QPainter *oldPainter = d->sharedPainter();
4749 d->setSharedPainter(painter);
4751 // Save current system clip, viewport and transform,
4752 const QTransform oldTransform = enginePriv->systemTransform;
4753 const QRegion oldSystemClip = enginePriv->systemClip;
4754 const QRegion oldSystemViewport = enginePriv->systemViewport;
4756 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4757 if (painter->hasClipping()) {
4758 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4759 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4761 enginePriv->setSystemViewport(oldSystemClip);
4764 render(target, targetOffset, toBePainted, renderFlags);
4766 // Restore system clip, viewport and transform.
4767 enginePriv->systemClip = oldSystemClip;
4768 enginePriv->setSystemViewport(oldSystemViewport);
4769 enginePriv->setSystemTransform(oldTransform);
4771 // Restore shared painter.
4772 d->setSharedPainter(oldPainter);
4775 d->extra->inRenderWithPainter = false;
4778 static void sendResizeEvents(QWidget *target)
4780 QResizeEvent e(target->size(), QSize());
4781 QApplication::sendEvent(target, &e);
4783 const QObjectList children = target->children();
4784 for (int i = 0; i < children.size(); ++i) {
4785 QWidget *child = static_cast<QWidget*>(children.at(i));
4786 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4787 sendResizeEvents(child);
4794 Renders the widget into a pixmap restricted by the
4795 given \a rectangle. If the \a widget has any children, then
4796 they are also painted in the appropriate positions.
4798 If no rectangle is specified (the default) the entire widget is
4801 Replacement for Qt 4's QPixmap::grabWidget().
4803 \sa render(), QPixmap
4806 /* INVOKABLE since used by QPixmap::grabWidget(). */
4807 QPixmap QWidget::grab(const QRect &rectangle)
4810 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4811 sendResizeEvents(this);
4817 r.setWidth(width() - rectangle.x());
4819 r.setHeight(height() - rectangle.y());
4821 if (!r.intersects(rect()))
4824 QPixmap res(r.size());
4826 res.fill(Qt::transparent);
4827 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4828 | QWidget::DrawChildren | QWidget::IgnoreMask);
4833 \brief The graphicsEffect function returns a pointer to the
4834 widget's graphics effect.
4836 If the widget has no graphics effect, 0 is returned.
4840 \sa setGraphicsEffect()
4842 #ifndef QT_NO_GRAPHICSEFFECT
4843 QGraphicsEffect *QWidget::graphicsEffect() const
4846 return d->graphicsEffect;
4848 #endif //QT_NO_GRAPHICSEFFECT
4852 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4854 Sets \a effect as the widget's effect. If there already is an effect installed
4855 on this widget, QWidget will delete the existing effect before installing
4858 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4859 the effect from the widget and install it on this widget.
4861 QWidget takes ownership of \a effect.
4863 \note This function will apply the effect on itself and all its children.
4867 \sa graphicsEffect()
4869 #ifndef QT_NO_GRAPHICSEFFECT
4870 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4873 if (d->graphicsEffect == effect)
4876 if (d->graphicsEffect) {
4877 d->invalidateBuffer(rect());
4878 delete d->graphicsEffect;
4879 d->graphicsEffect = 0;
4884 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4885 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4886 d->graphicsEffect = effect;
4887 effect->d_func()->setGraphicsEffectSource(source);
4891 d->updateIsOpaque();
4893 #endif //QT_NO_GRAPHICSEFFECT
4895 bool QWidgetPrivate::isAboutToShow() const
4904 // The widget will be shown if any of its ancestors are about to show.
4905 QWidget *parent = q->parentWidget();
4906 return parent ? parent->d_func()->isAboutToShow() : false;
4909 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4912 const bool isVisible = q->isVisible();
4914 // Make sure the widget is laid out correctly.
4915 if (!isVisible && !isAboutToShow()) {
4916 QWidget *topLevel = q->window();
4917 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4918 topLevel->ensurePolished();
4920 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4921 // they're not explicitly hidden.
4922 QWidget *widget = q;
4923 QWidgetList hiddenWidgets;
4925 if (widget->isHidden()) {
4926 widget->setAttribute(Qt::WA_WState_Hidden, false);
4927 hiddenWidgets.append(widget);
4928 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4929 widget->d_func()->updateGeometry_helper(true);
4931 widget = widget->parentWidget();
4934 // Activate top-level layout.
4935 if (topLevel->d_func()->layout)
4936 topLevel->d_func()->layout->activate();
4938 // Adjust size if necessary.
4939 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4940 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4941 && !topLevel->testAttribute(Qt::WA_Resized)) {
4942 topLevel->adjustSize();
4943 topLevel->setAttribute(Qt::WA_Resized, false);
4946 // Activate child layouts.
4947 topLevel->d_func()->activateChildLayoutsRecursively();
4949 // We're not cheating with WA_WState_Hidden anymore.
4950 for (int i = 0; i < hiddenWidgets.size(); ++i) {
4951 QWidget *widget = hiddenWidgets.at(i);
4952 widget->setAttribute(Qt::WA_WState_Hidden);
4953 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4954 widget->parentWidget()->d_func()->layout->invalidate();
4956 } else if (isVisible) {
4957 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4960 // Calculate the region to be painted.
4961 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4962 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4963 toBePainted &= extra->mask;
4967 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4968 QWidget::RenderFlags renderFlags)
4971 Q_ASSERT(!toBePainted.isEmpty());
4975 const QTransform originalTransform = painter->worldTransform();
4976 const bool useDeviceCoordinates = originalTransform.isScaling();
4977 if (!useDeviceCoordinates) {
4979 // Render via a pixmap.
4980 const QRect rect = toBePainted.boundingRect();
4981 const QSize size = rect.size();
4985 QPixmap pixmap(size);
4986 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4987 pixmap.fill(Qt::transparent);
4988 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4990 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4991 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4993 painter->drawPixmap(targetOffset, pixmap);
4996 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
5000 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
5001 QTransform transform = originalTransform;
5002 transform.translate(targetOffset.x(), targetOffset.y());
5004 QPaintDevice *device = painter->device();
5007 // Calculate device rect.
5008 const QRectF rect(toBePainted.boundingRect());
5009 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
5010 deviceRect &= QRect(0, 0, device->width(), device->height());
5012 QPixmap pixmap(deviceRect.size());
5013 pixmap.fill(Qt::transparent);
5015 // Create a pixmap device coordinate painter.
5016 QPainter pixmapPainter(&pixmap);
5017 pixmapPainter.setRenderHints(painter->renderHints());
5018 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
5019 pixmapPainter.setTransform(transform);
5021 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
5022 pixmapPainter.end();
5024 // And then draw the pixmap.
5025 painter->setTransform(QTransform());
5026 painter->drawPixmap(deviceRect.topLeft(), pixmap);
5027 painter->setTransform(originalTransform);
5032 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5033 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5039 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5040 dirtyOnWidget = QRegion();
5042 // We disable the rendering of QToolBar in the backingStore if
5043 // it's supposed to be in the unified toolbar on Mac OS X.
5044 if (backingStore && isInUnifiedToolbar)
5050 #ifndef QT_NO_GRAPHICSEFFECT
5051 if (graphicsEffect && graphicsEffect->isEnabled()) {
5052 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5053 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5055 if (!sourced->context) {
5056 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5057 sourced->context = &context;
5058 if (!sharedPainter) {
5059 QPaintEngine *paintEngine = pdev->paintEngine();
5060 paintEngine->d_func()->systemClip = rgn.translated(offset);
5062 p.translate(offset);
5063 context.painter = &p;
5064 graphicsEffect->draw(&p);
5065 paintEngine->d_func()->systemClip = QRegion();
5067 context.painter = sharedPainter;
5068 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5069 sourced->invalidateCache();
5070 sourced->lastEffectTransform = sharedPainter->worldTransform();
5072 sharedPainter->save();
5073 sharedPainter->translate(offset);
5074 graphicsEffect->draw(sharedPainter);
5075 sharedPainter->restore();
5077 sourced->context = 0;
5081 #endif //QT_NO_GRAFFICSEFFECT
5083 const bool asRoot = flags & DrawAsRoot;
5084 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5085 const bool recursive = flags & DrawRecursive;
5086 const bool alsoInvisible = flags & DrawInvisible;
5088 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5090 QRegion toBePainted(rgn);
5091 if (asRoot && !alsoInvisible)
5092 toBePainted &= clipRect(); //(rgn & visibleRegion());
5093 if (!(flags & DontSubtractOpaqueChildren))
5094 subtractOpaqueChildren(toBePainted, q->rect());
5096 if (!toBePainted.isEmpty()) {
5097 bool onScreen = paintOnScreen();
5098 if (!onScreen || alsoOnScreen) {
5099 //update the "in paint event" flag
5100 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5101 qWarning("QWidget::repaint: Recursive repaint detected");
5102 q->setAttribute(Qt::WA_WState_InPaintEvent);
5104 //clip away the new area
5105 #ifndef QT_NO_PAINT_DEBUG
5106 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5108 QPaintEngine *paintEngine = pdev->paintEngine();
5110 setRedirected(pdev, -offset);
5113 // (Alien support) Special case for Mac when redirecting: If the paint device
5114 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5115 // outside the paint event is not supported on QWidgets. The attributeis
5116 // restored further down.
5117 if (pdev->devType() == QInternal::Widget)
5118 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5122 paintEngine->d_func()->systemClip = toBePainted;
5124 paintEngine->d_func()->systemRect = q->data->crect;
5126 //paint the background
5127 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5128 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5130 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5134 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5136 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5138 QColor tint = q->palette().window().color();
5139 tint.setAlphaF(qreal(.6));
5140 p.fillRect(toBePainted.boundingRect(), tint);
5145 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5146 qDebug() << "clipping to" << toBePainted << "location == " << offset
5147 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5150 //actually send the paint event
5151 QPaintEvent e(toBePainted);
5152 QCoreApplication::sendSpontaneousEvent(q, &e);
5157 if (pdev->devType() == QInternal::Widget)
5158 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5160 restoreRedirected();
5162 paintEngine->d_func()->systemRect = QRect();
5164 paintEngine->d_func()->currentClipDevice = 0;
5165 paintEngine->d_func()->systemClip = QRegion();
5167 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5168 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5169 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5171 if (paintEngine && paintEngine->autoDestruct()) {
5175 #ifndef QT_NO_PAINT_DEBUG
5177 QWidgetBackingStore::unflushPaint(q, toBePainted);
5179 } else if (q->isWindow()) {
5180 QPaintEngine *engine = pdev->paintEngine();
5183 p.setClipRegion(toBePainted);
5184 const QBrush bg = q->palette().brush(QPalette::Window);
5185 if (bg.style() == Qt::TexturePattern)
5186 p.drawTiledPixmap(q->rect(), bg.texture());
5188 p.fillRect(q->rect(), bg);
5190 if (engine->autoDestruct())
5196 if (recursive && !children.isEmpty()) {
5197 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5198 , sharedPainter, backingStore);
5202 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5203 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5207 qWarning("QWidget::render: null pointer to paint device");
5211 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5212 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5213 ? prepareToRender(sourceRegion, renderFlags)
5215 if (paintRegion.isEmpty())
5219 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5221 // Use the target's shared painter if set (typically set when doing
5222 // "other->render(widget);" in the widget's paintEvent.
5223 if (target->devType() == QInternal::Widget) {
5224 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5225 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5226 QPainter *targetPainter = targetPrivate->sharedPainter();
5227 if (targetPainter && targetPainter->isActive())
5228 setSharedPainter(targetPainter);
5233 // Use the target's redirected device if set and adjust offset and paint
5234 // region accordingly. This is typically the case when people call render
5235 // from the paintEvent.
5236 QPoint offset = targetOffset;
5237 offset -= paintRegion.boundingRect().topLeft();
5238 QPoint redirectionOffset;
5239 QPaintDevice *redirected = 0;
5241 if (target->devType() == QInternal::Widget)
5242 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5244 redirected = QPainter::redirected(target, &redirectionOffset);
5247 target = redirected;
5248 offset -= redirectionOffset;
5251 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5252 if (QPaintEngine *targetEngine = target->paintEngine()) {
5253 const QRegion targetSystemClip = targetEngine->systemClip();
5254 if (!targetSystemClip.isEmpty())
5255 paintRegion &= targetSystemClip.translated(-offset);
5259 // Set backingstore flags.
5260 int flags = DrawPaintOnScreen | DrawInvisible;
5261 if (renderFlags & QWidget::DrawWindowBackground)
5262 flags |= DrawAsRoot;
5264 if (renderFlags & QWidget::DrawChildren)
5265 flags |= DrawRecursive;
5267 flags |= DontSubtractOpaqueChildren;
5269 if (target->devType() == QInternal::Printer) {
5271 render_helper(&p, targetOffset, paintRegion, renderFlags);
5276 // Render via backingstore.
5277 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5279 // Restore shared painter.
5280 if (oldSharedPainter)
5281 setSharedPainter(oldSharedPainter);
5283 // Render via backingstore (no shared painter).
5284 drawWidget(target, paintRegion, offset, flags, 0);
5288 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5289 const QPoint &offset, int flags
5290 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5294 bool dirtyBoundingRect = true;
5295 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5296 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5299 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5300 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5301 && !(excludeNativeChildren && x->internalWinId())) {
5302 if (dirtyBoundingRect) {
5303 boundingRect = rgn.boundingRect();
5304 dirtyBoundingRect = false;
5307 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5313 } while (index >= 0);
5318 QWidgetPrivate *wd = w->d_func();
5319 const QPoint widgetPos(w->data->crect.topLeft());
5320 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5324 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5325 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5326 , sharedPainter, backingStore);
5329 if (w->updatesEnabled()
5330 #ifndef QT_NO_GRAPHICSVIEW
5331 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5332 #endif //QT_NO_GRAPHICSVIEW
5334 QRegion wRegion(rgn);
5335 wRegion &= wd->effectiveRectFor(w->data->crect);
5336 wRegion.translate(-widgetPos);
5338 wRegion &= wd->extra->mask;
5339 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5343 #ifndef QT_NO_GRAPHICSEFFECT
5344 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5346 if (system != Qt::DeviceCoordinates)
5347 return m_widget->rect();
5350 // Device coordinates without context not yet supported.
5351 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5355 return context->painter->worldTransform().mapRect(m_widget->rect());
5358 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5360 if (!context || context->painter != painter) {
5361 m_widget->render(painter);
5365 // The region saved in the context is neither clipped to the rect
5366 // nor the mask, so we have to clip it here before calling drawWidget.
5367 QRegion toBePainted = context->rgn;
5368 toBePainted &= m_widget->rect();
5369 QWidgetPrivate *wd = qt_widget_private(m_widget);
5370 if (wd->extra && wd->extra->hasMask)
5371 toBePainted &= wd->extra->mask;
5373 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5374 context->sharedPainter, context->backingStore);
5377 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5378 QGraphicsEffect::PixmapPadMode mode) const
5380 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5381 if (!context && deviceCoordinates) {
5382 // Device coordinates without context not yet supported.
5383 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5387 QPoint pixmapOffset;
5388 QRectF sourceRect = m_widget->rect();
5390 if (deviceCoordinates) {
5391 const QTransform &painterTransform = context->painter->worldTransform();
5392 sourceRect = painterTransform.mapRect(sourceRect);
5393 pixmapOffset = painterTransform.map(pixmapOffset);
5398 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5399 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5400 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5401 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5403 effectRect = sourceRect.toAlignedRect();
5406 *offset = effectRect.topLeft();
5408 pixmapOffset -= effectRect.topLeft();
5410 QPixmap pixmap(effectRect.size());
5411 pixmap.fill(Qt::transparent);
5412 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5415 #endif //QT_NO_GRAPHICSEFFECT
5417 #ifndef QT_NO_GRAPHICSVIEW
5421 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5422 widget and its ancestors. The search starts at \a origin (inclusive).
5423 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5426 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5429 QWExtra *extra = origin->d_func()->extra;
5430 if (extra && extra->proxyWidget)
5431 return extra->proxyWidget;
5432 return nearestGraphicsProxyWidget(origin->parentWidget());
5439 \property QWidget::locale
5440 \brief the widget's locale
5443 As long as no special locale has been set, this is either
5444 the parent's locale or (if this widget is a top level widget),
5447 If the widget displays dates or numbers, these should be formatted
5448 using the widget's locale.
5450 \sa QLocale QLocale::setDefault()
5453 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5456 if (locale == loc && !forceUpdate)
5461 if (!children.isEmpty()) {
5462 for (int i = 0; i < children.size(); ++i) {
5463 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5466 if (w->testAttribute(Qt::WA_SetLocale))
5468 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5470 w->d_func()->setLocale_helper(loc, forceUpdate);
5473 QEvent e(QEvent::LocaleChange);
5474 QApplication::sendEvent(q, &e);
5477 void QWidget::setLocale(const QLocale &locale)
5481 setAttribute(Qt::WA_SetLocale);
5482 d->setLocale_helper(locale);
5485 QLocale QWidget::locale() const
5492 void QWidgetPrivate::resolveLocale()
5496 if (!q->testAttribute(Qt::WA_SetLocale)) {
5497 setLocale_helper(q->isWindow()
5499 : q->parentWidget()->locale());
5503 void QWidget::unsetLocale()
5506 setAttribute(Qt::WA_SetLocale, false);
5510 static QString constructWindowTitleFromFilePath(const QString &filePath)
5512 QFileInfo fi(filePath);
5513 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5515 QString appName = QApplication::applicationName();
5516 if (!appName.isEmpty())
5517 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5523 \property QWidget::windowTitle
5524 \brief the window title (caption)
5526 This property only makes sense for top-level widgets, such as
5527 windows and dialogs. If no caption has been set, the title is based of the
5528 \l windowFilePath. If neither of these is set, then the title is
5531 If you use the \l windowModified mechanism, the window title must
5532 contain a "[*]" placeholder, which indicates where the '*' should
5533 appear. Normally, it should appear right after the file name
5534 (e.g., "document1.txt[*] - Text Editor"). If the \l
5535 windowModified property is false (the default), the placeholder
5538 \sa windowIcon, windowIconText, windowModified, windowFilePath
5540 QString QWidget::windowTitle() const
5543 if (d->extra && d->extra->topextra) {
5544 if (!d->extra->topextra->caption.isEmpty())
5545 return d->extra->topextra->caption;
5546 if (!d->extra->topextra->filePath.isEmpty())
5547 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5553 Returns a modified window title with the [*] place holder
5554 replaced according to the rules described in QWidget::setWindowTitle
5556 This function assumes that "[*]" can be quoted by another
5557 "[*]", so it will replace two place holders by one and
5558 a single last one by either "*" or nothing depending on
5563 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5568 extern QString qt_eval_adapt_window_title(const QString &title);
5569 QString cap = qt_eval_adapt_window_title(title);
5571 QString cap = title;
5577 QLatin1String placeHolder("[*]");
5578 int placeHolderLength = 3; // QLatin1String doesn't have length()
5580 int index = cap.indexOf(placeHolder);
5582 // here the magic begins
5583 while (index != -1) {
5584 index += placeHolderLength;
5586 while (cap.indexOf(placeHolder, index) == index) {
5588 index += placeHolderLength;
5591 if (count%2) { // odd number of [*] -> replace last one
5592 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5593 if (widget->isWindowModified()
5594 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5595 cap.replace(lastIndex, 3, QWidget::tr("*"));
5597 cap.remove(lastIndex, 3);
5600 index = cap.indexOf(placeHolder, index);
5603 cap.replace(QLatin1String("[*][*]"), placeHolder);
5608 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5611 if (q->testAttribute(Qt::WA_WState_Created))
5612 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5615 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5618 if (q->testAttribute(Qt::WA_WState_Created))
5619 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5622 void QWidget::setWindowIconText(const QString &iconText)
5624 if (QWidget::windowIconText() == iconText)
5628 d->topData()->iconText = iconText;
5629 d->setWindowIconText_helper(iconText);
5631 QEvent e(QEvent::IconTextChange);
5632 QApplication::sendEvent(this, &e);
5635 void QWidget::setWindowTitle(const QString &title)
5637 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5641 d->topData()->caption = title;
5642 d->setWindowTitle_helper(title);
5644 QEvent e(QEvent::WindowTitleChange);
5645 QApplication::sendEvent(this, &e);
5650 \property QWidget::windowIcon
5651 \brief the widget's icon
5653 This property only makes sense for windows. If no icon
5654 has been set, windowIcon() returns the application icon
5655 (QApplication::windowIcon()).
5657 \sa windowIconText, windowTitle
5659 QIcon QWidget::windowIcon() const
5661 const QWidget *w = this;
5663 const QWidgetPrivate *d = w->d_func();
5664 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5665 return *d->extra->topextra->icon;
5666 w = w->parentWidget();
5668 return QApplication::windowIcon();
5671 void QWidgetPrivate::setWindowIcon_helper()
5673 QEvent e(QEvent::WindowIconChange);
5674 QApplication::sendEvent(q_func(), &e);
5675 for (int i = 0; i < children.size(); ++i) {
5676 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5677 if (w && !w->isWindow())
5678 QApplication::sendEvent(w, &e);
5682 void QWidget::setWindowIcon(const QIcon &icon)
5686 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5689 if (!d->extra->topextra->icon)
5690 d->extra->topextra->icon = new QIcon();
5691 *d->extra->topextra->icon = icon;
5693 delete d->extra->topextra->iconPixmap;
5694 d->extra->topextra->iconPixmap = 0;
5696 d->setWindowIcon_sys();
5697 d->setWindowIcon_helper();
5702 \property QWidget::windowIconText
5703 \brief the widget's icon text
5705 This property only makes sense for windows. If no icon
5706 text has been set, this functions returns an empty string.
5708 \sa windowIcon, windowTitle
5711 QString QWidget::windowIconText() const
5714 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5718 \property QWidget::windowFilePath
5720 \brief the file path associated with a widget
5722 This property only makes sense for windows. It associates a file path with
5723 a window. If you set the file path, but have not set the window title, Qt
5724 sets the window title to contain a string created using the following
5730 \o The file name of the specified path, obtained using QFileInfo::fileName().
5736 \o The file name of the specified path, obtained using QFileInfo::fileName().
5737 \o An optional \c{*} character, if the \l windowModified property is set.
5738 \o The \c{0x2014} unicode character, padded either side by spaces.
5739 \o The application name, obtained from the application's
5740 \l{QCoreApplication::}{applicationName} property.
5743 If the window title is set at any point, then the window title takes precedence and
5744 will be shown instead of the file path string.
5746 Additionally, on Mac OS X, this has an added benefit that it sets the
5747 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5748 for the window, assuming that the file path exists.
5750 If no file path is set, this property contains an empty string.
5752 By default, this property contains an empty string.
5754 \sa windowTitle, windowIcon
5757 QString QWidget::windowFilePath() const
5760 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5763 void QWidget::setWindowFilePath(const QString &filePath)
5765 if (filePath == windowFilePath())
5771 d->extra->topextra->filePath = filePath;
5772 d->setWindowFilePath_helper(filePath);
5775 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5777 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5779 setWindowTitle_helper(QFileInfo(filePath).fileName());
5783 setWindowTitle_helper(q->windowTitle());
5787 setWindowFilePath_sys(filePath);
5792 Returns the window's role, or an empty string.
5794 \sa windowIcon, windowTitle
5797 QString QWidget::windowRole() const
5800 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5804 Sets the window's role to \a role. This only makes sense for
5807 void QWidget::setWindowRole(const QString &role)
5809 #if defined(Q_WS_X11)
5811 d->topData()->role = role;
5819 \property QWidget::mouseTracking
5820 \brief whether mouse tracking is enabled for the widget
5822 If mouse tracking is disabled (the default), the widget only
5823 receives mouse move events when at least one mouse button is
5824 pressed while the mouse is being moved.
5826 If mouse tracking is enabled, the widget receives mouse move
5827 events even if no buttons are pressed.
5829 \sa mouseMoveEvent()
5834 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5835 function resets this widget to have no focus proxy.
5837 Some widgets can "have focus", but create a child widget, such as
5838 QLineEdit, to actually handle the focus. In this case, the widget
5839 can set the line edit to be its focus proxy.
5841 setFocusProxy() sets the widget which will actually get focus when
5842 "this widget" gets it. If there is a focus proxy, setFocus() and
5843 hasFocus() operate on the focus proxy.
5848 void QWidget::setFocusProxy(QWidget * w)
5851 if (!w && !d->extra)
5854 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5856 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5862 d->extra->focus_proxy = w;
5867 Returns the focus proxy, or 0 if there is no focus proxy.
5872 QWidget * QWidget::focusProxy() const
5875 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5880 \property QWidget::focus
5881 \brief whether this widget (or its focus proxy) has the keyboard
5884 By default, this property is false.
5886 \note Obtaining the value of this property for a widget is effectively equivalent
5887 to checking whether QApplication::focusWidget() refers to the widget.
5889 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5891 bool QWidget::hasFocus() const
5893 const QWidget* w = this;
5894 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5895 w = w->d_func()->extra->focus_proxy;
5896 if (QWidget *window = w->window()) {
5897 #ifndef QT_NO_GRAPHICSVIEW
5898 QWExtra *e = window->d_func()->extra;
5899 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5903 return (QApplication::focusWidget() == w);
5907 Gives the keyboard input focus to this widget (or its focus
5908 proxy) if this widget or one of its parents is the \link
5909 isActiveWindow() active window\endlink. The \a reason argument will
5910 be passed into any focus event sent from this function, it is used
5911 to give an explanation of what caused the widget to get focus.
5912 If the window is not active, the widget will be given the focus when
5913 the window becomes active.
5915 First, a focus out event is sent to the focus widget (if any) to
5916 tell it that it is about to lose the focus. Then a focus in event
5917 is sent to this widget to tell it that it just received the focus.
5918 (Nothing happens if the focus in and focus out widgets are the
5921 \note On embedded platforms, setFocus() will not cause an input panel
5922 to be opened by the input method. If you want this to happen, you
5923 have to send a QEvent::RequestSoftwareInputPanel event to the
5926 setFocus() gives focus to a widget regardless of its focus policy,
5927 but does not clear any keyboard grab (see grabKeyboard()).
5929 Be aware that if the widget is hidden, it will not accept focus
5932 \warning If you call setFocus() in a function which may itself be
5933 called from focusOutEvent() or focusInEvent(), you may get an
5936 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5937 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5938 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5941 void QWidget::setFocus(Qt::FocusReason reason)
5947 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5948 f = f->d_func()->extra->focus_proxy;
5950 if (QApplication::focusWidget() == f
5951 #if defined(Q_WS_WIN)
5952 && GetFocus() == f->internalWinId()
5957 #ifndef QT_NO_GRAPHICSVIEW
5958 QWidget *previousProxyFocus = 0;
5959 if (QWExtra *topData = window()->d_func()->extra) {
5960 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5961 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5962 if (previousProxyFocus && previousProxyFocus->focusProxy())
5963 previousProxyFocus = previousProxyFocus->focusProxy();
5964 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5972 while (w && w->isHidden()) {
5973 w->d_func()->focus_child = f;
5974 w = w->isWindow() ? 0 : w->parentWidget();
5978 w->d_func()->focus_child = f;
5979 w = w->isWindow() ? 0 : w->parentWidget();
5983 #ifndef QT_NO_GRAPHICSVIEW
5984 // Update proxy state
5985 if (QWExtra *topData = window()->d_func()->extra) {
5986 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5987 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5988 topData->proxyWidget->setFocus(reason);
5989 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5994 if (f->isActiveWindow()) {
5995 QApplicationPrivate::setFocusWidget(f, reason);
5996 #ifndef QT_NO_ACCESSIBILITY
5998 // The negation of the condition in setFocus_sys
5999 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
6000 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
6003 // menus update the focus manually and this would create bogus events
6004 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
6006 QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
6008 #ifndef QT_NO_GRAPHICSVIEW
6009 if (QWExtra *topData = window()->d_func()->extra) {
6010 if (topData->proxyWidget) {
6011 if (previousProxyFocus && previousProxyFocus != f) {
6012 // Send event to self
6013 QFocusEvent event(QEvent::FocusOut, reason);
6014 QPointer<QWidget> that = previousProxyFocus;
6015 QApplication::sendEvent(previousProxyFocus, &event);
6017 QApplication::sendEvent(that->style(), &event);
6020 #ifndef QT_NO_GRAPHICSVIEW
6021 // Update proxy state
6022 if (QWExtra *topData = window()->d_func()->extra)
6023 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
6024 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
6026 // Send event to self
6027 QFocusEvent event(QEvent::FocusIn, reason);
6028 QPointer<QWidget> that = f;
6029 QApplication::sendEvent(f, &event);
6031 QApplication::sendEvent(that->style(), &event);
6040 \fn void QWidget::setFocus()
6043 Gives the keyboard input focus to this widget (or its focus
6044 proxy) if this widget or one of its parents is the
6045 \l{isActiveWindow()}{active window}.
6049 Takes keyboard input focus from the widget.
6051 If the widget has active focus, a \link focusOutEvent() focus out
6052 event\endlink is sent to this widget to tell it that it is about
6055 This widget must enable focus setting in order to get the keyboard
6056 input focus, i.e. it must call setFocusPolicy().
6058 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6059 setFocusPolicy(), QApplication::focusWidget()
6062 void QWidget::clearFocus()
6066 if (w->d_func()->focus_child == this)
6067 w->d_func()->focus_child = 0;
6068 w = w->parentWidget();
6070 #ifndef QT_NO_GRAPHICSVIEW
6071 QWExtra *topData = d_func()->extra;
6072 if (topData && topData->proxyWidget)
6073 topData->proxyWidget->clearFocus();
6077 // Update proxy state
6078 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6079 #if defined(Q_WS_WIN)
6080 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6085 #ifndef QT_NO_ACCESSIBILITY
6086 QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
6094 \fn bool QWidget::focusNextChild()
6096 Finds a new widget to give the keyboard focus to, as appropriate
6097 for \key Tab, and returns true if it can find a new widget, or
6100 \sa focusPreviousChild()
6104 \fn bool QWidget::focusPreviousChild()
6106 Finds a new widget to give the keyboard focus to, as appropriate
6107 for \key Shift+Tab, and returns true if it can find a new widget,
6108 or false if it can't.
6110 \sa focusNextChild()
6114 Finds a new widget to give the keyboard focus to, as appropriate
6115 for Tab and Shift+Tab, and returns true if it can find a new
6116 widget, or false if it can't.
6118 If \a next is true, this function searches forward, if \a next
6119 is false, it searches backward.
6121 Sometimes, you will want to reimplement this function. For
6122 example, a web browser might reimplement it to move its "current
6123 active link" forward or backward, and call
6124 focusNextPrevChild() only when it reaches the last or
6125 first link on the "page".
6127 Child widgets call focusNextPrevChild() on their parent widgets,
6128 but only the window that contains the child widgets decides where
6129 to redirect focus. By reimplementing this function for an object,
6130 you thus gain control of focus traversal for all child widgets.
6132 \sa focusNextChild(), focusPreviousChild()
6135 bool QWidget::focusNextPrevChild(bool next)
6138 QWidget* p = parentWidget();
6139 bool isSubWindow = (windowType() == Qt::SubWindow);
6140 if (!isWindow() && !isSubWindow && p)
6141 return p->focusNextPrevChild(next);
6142 #ifndef QT_NO_GRAPHICSVIEW
6143 if (d->extra && d->extra->proxyWidget)
6144 return d->extra->proxyWidget->focusNextPrevChild(next);
6146 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6147 if (!w) return false;
6149 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6154 Returns the last child of this widget that setFocus had been
6155 called on. For top level widgets this is the widget that will get
6156 focus in case this window gets activated
6158 This is not the same as QApplication::focusWidget(), which returns
6159 the focus widget in the currently active window.
6162 QWidget *QWidget::focusWidget() const
6164 return const_cast<QWidget *>(d_func()->focus_child);
6168 Returns the next widget in this widget's focus chain.
6170 \sa previousInFocusChain()
6172 QWidget *QWidget::nextInFocusChain() const
6174 return const_cast<QWidget *>(d_func()->focus_next);
6178 \brief The previousInFocusChain function returns the previous
6179 widget in this widget's focus chain.
6181 \sa nextInFocusChain()
6185 QWidget *QWidget::previousInFocusChain() const
6187 return const_cast<QWidget *>(d_func()->focus_prev);
6191 \property QWidget::isActiveWindow
6192 \brief whether this widget's window is the active window
6194 The active window is the window that contains the widget that has
6195 keyboard focus (The window may still have focus if it has no
6196 widgets or none of its widgets accepts keyboard focus).
6198 When popup windows are visible, this property is true for both the
6199 active window \e and for the popup.
6201 By default, this property is false.
6203 \sa activateWindow(), QApplication::activeWindow()
6205 bool QWidget::isActiveWindow() const
6207 QWidget *tlw = window();
6208 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6211 #ifndef QT_NO_GRAPHICSVIEW
6212 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6213 if (isVisible() && tlwExtra->proxyWidget)
6214 return tlwExtra->proxyWidget->isActiveWindow();
6219 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6220 if(qt_mac_is_macdrawer(tlw) &&
6221 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6224 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6225 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6228 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6229 if(tlw->windowType() == Qt::Tool &&
6231 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6233 QWidget *w = QApplication::activeWindow();
6234 while(w && tlw->windowType() == Qt::Tool &&
6235 !w->isModal() && w->parentWidget()) {
6236 w = w->parentWidget()->window();
6241 #if defined(Q_WS_WIN32)
6242 HWND active = GetActiveWindow();
6243 if (!tlw->testAttribute(Qt::WA_WState_Created))
6245 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6252 Puts the \a second widget after the \a first widget in the focus order.
6254 Note that since the tab order of the \a second widget is changed, you
6255 should order a chain like this:
6257 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6261 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6263 If \a first or \a second has a focus proxy, setTabOrder()
6264 correctly substitutes the proxy.
6266 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6268 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6270 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6273 if (first->window() != second->window()) {
6274 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6278 QWidget *fp = first->focusProxy();
6280 // If first is redirected, set first to the last child of first
6281 // that can take keyboard focus so that second is inserted after
6282 // that last child, and the focus order within first is (more
6283 // likely to be) preserved.
6284 QList<QWidget *> l = first->findChildren<QWidget *>();
6285 for (int i = l.size()-1; i >= 0; --i) {
6286 QWidget * next = l.at(i);
6287 if (next->window() == fp->window()) {
6289 if (fp->focusPolicy() != Qt::NoFocus)
6299 if (QWidget *sp = second->focusProxy())
6302 // QWidget *fp = first->d_func()->focus_prev;
6303 QWidget *fn = first->d_func()->focus_next;
6305 if (fn == second || first == second)
6308 QWidget *sp = second->d_func()->focus_prev;
6309 QWidget *sn = second->d_func()->focus_next;
6311 fn->d_func()->focus_prev = second;
6312 first->d_func()->focus_next = second;
6314 second->d_func()->focus_next = fn;
6315 second->d_func()->focus_prev = first;
6317 sp->d_func()->focus_next = sn;
6318 sn->d_func()->focus_prev = sp;
6321 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6322 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6324 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6325 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6330 Moves the relevant subwidgets of this widget from the \a oldtlw's
6331 tab chain to that of the new parent, if there's anything to move and
6334 This function is called from QWidget::reparent() *after* the widget
6335 has been reparented.
6340 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6343 if (oldtlw == q->window())
6344 return; // nothing to do
6347 focus_child->clearFocus();
6349 // separate the focus chain into new (children of myself) and old (the rest)
6350 QWidget *firstOld = 0;
6351 //QWidget *firstNew = q; //invariant
6352 QWidget *o = 0; // last in the old list
6353 QWidget *n = q; // last in the new list
6355 bool prevWasNew = true;
6356 QWidget *w = focus_next;
6358 //Note: for efficiency, we do not maintain the list invariant inside the loop
6359 //we append items to the relevant list, and we optimize by not changing pointers
6360 //when subsequent items are going into the same list.
6362 bool currentIsNew = q->isAncestorOf(w);
6365 //prev was old -- append to new list
6366 n->d_func()->focus_next = w;
6367 w->d_func()->focus_prev = n;
6372 //prev was new -- append to old list, if there is one
6374 o->d_func()->focus_next = w;
6375 w->d_func()->focus_prev = o;
6377 // "create" the old list
6383 w = w->d_func()->focus_next;
6384 prevWasNew = currentIsNew;
6387 //repair the old list:
6389 o->d_func()->focus_next = firstOld;
6390 firstOld->d_func()->focus_prev = o;
6393 if (!q->isWindow()) {
6394 QWidget *topLevel = q->window();
6395 //insert new chain into toplevel's chain
6397 QWidget *prev = topLevel->d_func()->focus_prev;
6399 topLevel->d_func()->focus_prev = n;
6400 prev->d_func()->focus_next = q;
6403 n->d_func()->focus_next = topLevel;
6405 //repair the new list
6406 n->d_func()->focus_next = q;
6414 Measures the shortest distance from a point to a rect.
6416 This function is called from QDesktopwidget::screen(QPoint) to find the
6417 closest screen for a point.
6418 In directional KeypadNavigation, it is called to find the closest
6419 widget to the current focus widget center.
6421 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6425 if (p.x() < r.left())
6426 dx = r.left() - p.x();
6427 else if (p.x() > r.right())
6428 dx = p.x() - r.right();
6429 if (p.y() < r.top())
6430 dy = r.top() - p.y();
6431 else if (p.y() > r.bottom())
6432 dy = p.y() - r.bottom();
6437 \property QWidget::frameSize
6438 \brief the size of the widget including any window frame
6440 By default, this property contains a value that depends on the user's
6441 platform and screen geometry.
6443 QSize QWidget::frameSize() const
6446 if (isWindow() && !(windowType() == Qt::Popup)) {
6447 QRect fs = d->frameStrut();
6448 return QSize(data->crect.width() + fs.left() + fs.right(),
6449 data->crect.height() + fs.top() + fs.bottom());
6451 return data->crect.size();
6454 /*! \fn void QWidget::move(int x, int y)
6458 This corresponds to move(QPoint(\a x, \a y)).
6461 void QWidget::move(const QPoint &p)
6464 setAttribute(Qt::WA_Moved);
6466 d->topData()->posFromMove = true;
6467 if (testAttribute(Qt::WA_WState_Created)) {
6468 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6469 p.y() + geometry().y() - QWidget::y(),
6470 width(), height(), true);
6471 d->setDirtyOpaqueRegion();
6473 data->crect.moveTopLeft(p); // no frame yet
6474 setAttribute(Qt::WA_PendingMoveEvent);
6478 /*! \fn void QWidget::resize(int w, int h)
6481 This corresponds to resize(QSize(\a w, \a h)).
6484 void QWidget::resize(const QSize &s)
6487 setAttribute(Qt::WA_Resized);
6488 if (testAttribute(Qt::WA_WState_Created)) {
6489 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6490 d->setDirtyOpaqueRegion();
6492 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6493 setAttribute(Qt::WA_PendingResizeEvent);
6497 void QWidget::setGeometry(const QRect &r)
6500 setAttribute(Qt::WA_Resized);
6501 setAttribute(Qt::WA_Moved);
6503 d->topData()->posFromMove = false;
6504 if (testAttribute(Qt::WA_WState_Created)) {
6505 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6506 d->setDirtyOpaqueRegion();
6508 data->crect.setTopLeft(r.topLeft());
6509 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6510 setAttribute(Qt::WA_PendingMoveEvent);
6511 setAttribute(Qt::WA_PendingResizeEvent);
6517 Saves the current geometry and state for top-level widgets.
6519 To save the geometry when the window closes, you can
6520 implement a close event like this:
6522 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6524 See the \l{Window Geometry} documentation for an overview of geometry
6525 issues with windows.
6527 Use QMainWindow::saveState() to save the geometry and the state of
6528 toolbars and dock widgets.
6530 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6532 QByteArray QWidget::saveGeometry() const
6535 // We check if the window was maximized during this invocation. If so, we need to record the
6536 // starting position as 0,0.
6538 QRect newFramePosition = frameGeometry();
6539 QRect newNormalPosition = normalGeometry();
6540 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6541 // Change the starting position
6542 newFramePosition.moveTo(0, 0);
6543 newNormalPosition.moveTo(0, 0);
6547 QDataStream stream(&array, QIODevice::WriteOnly);
6548 stream.setVersion(QDataStream::Qt_4_0);
6549 const quint32 magicNumber = 0x1D9D0CB;
6550 quint16 majorVersion = 1;
6551 quint16 minorVersion = 0;
6552 stream << magicNumber
6557 << newNormalPosition
6562 << qint32(QApplication::desktop()->screenNumber(this))
6563 << quint8(windowState() & Qt::WindowMaximized)
6564 << quint8(windowState() & Qt::WindowFullScreen);
6571 Restores the geometry and state top-level widgets stored in the
6572 byte array \a geometry. Returns true on success; otherwise
6575 If the restored geometry is off-screen, it will be modified to be
6576 inside the available screen geometry.
6578 To restore geometry saved using QSettings, you can use code like
6581 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6583 See the \l{Window Geometry} documentation for an overview of geometry
6584 issues with windows.
6586 Use QMainWindow::restoreState() to restore the geometry and the
6587 state of toolbars and dock widgets.
6589 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6591 bool QWidget::restoreGeometry(const QByteArray &geometry)
6593 if (geometry.size() < 4)
6595 QDataStream stream(geometry);
6596 stream.setVersion(QDataStream::Qt_4_0);
6598 const quint32 magicNumber = 0x1D9D0CB;
6599 quint32 storedMagicNumber;
6600 stream >> storedMagicNumber;
6601 if (storedMagicNumber != magicNumber)
6604 const quint16 currentMajorVersion = 1;
6605 quint16 majorVersion = 0;
6606 quint16 minorVersion = 0;
6608 stream >> majorVersion >> minorVersion;
6610 if (majorVersion != currentMajorVersion)
6612 // (Allow all minor versions.)
6614 QRect restoredFrameGeometry;
6615 QRect restoredNormalGeometry;
6616 qint32 restoredScreenNumber;
6620 stream >> restoredFrameGeometry
6621 >> restoredNormalGeometry
6622 >> restoredScreenNumber
6626 const int frameHeight = 20;
6627 if (!restoredFrameGeometry.isValid())
6628 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6630 if (!restoredNormalGeometry.isValid())
6631 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6632 if (!restoredNormalGeometry.isValid()) {
6633 // use the widget's adjustedSize if the sizeHint() doesn't help
6634 restoredNormalGeometry.setSize(restoredNormalGeometry
6636 .expandedTo(d_func()->adjustedSize()));
6639 const QDesktopWidget * const desktop = QApplication::desktop();
6640 if (restoredScreenNumber >= desktop->numScreens())
6641 restoredScreenNumber = desktop->primaryScreen();
6643 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6645 // Modify the restored geometry if we are about to restore to coordinates
6646 // that would make the window "lost". This happens if:
6647 // - The restored geometry is completely oustside the available geometry
6648 // - The title bar is outside the available geometry.
6649 // - (Mac only) The window is higher than the available geometry. It must
6650 // be possible to bring the size grip on screen by moving the window.
6652 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6653 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6656 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6657 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6658 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6659 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6661 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6663 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6664 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6665 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6666 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6668 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6670 if (maximized || fullScreen) {
6671 // set geomerty before setting the window state to make
6672 // sure the window is maximized to the right screen.
6673 // Skip on windows: the window is restored into a broken
6674 // half-maximized state.
6676 setGeometry(restoredNormalGeometry);
6678 Qt::WindowStates ws = windowState();
6680 ws |= Qt::WindowMaximized;
6682 ws |= Qt::WindowFullScreen;
6684 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6689 offset = d_func()->topData()->fullScreenOffset;
6691 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6692 move(restoredFrameGeometry.topLeft() + offset);
6693 resize(restoredNormalGeometry.size());
6698 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6701 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6705 Sets the margins around the contents of the widget to have the sizes
6706 \a left, \a top, \a right, and \a bottom. The margins are used by
6707 the layout system, and may be used by subclasses to specify the area
6708 to draw in (e.g. excluding the frame).
6710 Changing the margins will trigger a resizeEvent().
6712 \sa contentsRect(), getContentsMargins()
6714 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6717 if (left == d->leftmargin && top == d->topmargin
6718 && right == d->rightmargin && bottom == d->bottommargin)
6720 d->leftmargin = left;
6722 d->rightmargin = right;
6723 d->bottommargin = bottom;
6725 if (QLayout *l=d->layout)
6726 l->update(); //force activate; will do updateGeometry
6730 // ### Qt 5: compat, remove
6733 QResizeEvent e(data->crect.size(), data->crect.size());
6734 QApplication::sendEvent(this, &e);
6736 setAttribute(Qt::WA_PendingResizeEvent, true);
6739 QEvent e(QEvent::ContentsRectChange);
6740 QApplication::sendEvent(this, &e);
6747 \brief The setContentsMargins function sets the margins around the
6750 Sets the margins around the contents of the widget to have the
6751 sizes determined by \a margins. The margins are
6752 used by the layout system, and may be used by subclasses to
6753 specify the area to draw in (e.g. excluding the frame).
6755 Changing the margins will trigger a resizeEvent().
6757 \sa contentsRect(), getContentsMargins()
6759 void QWidget::setContentsMargins(const QMargins &margins)
6761 setContentsMargins(margins.left(), margins.top(),
6762 margins.right(), margins.bottom());
6766 Returns the widget's contents margins for \a left, \a top, \a
6767 right, and \a bottom.
6769 \sa setContentsMargins(), contentsRect()
6771 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6775 *left = d->leftmargin;
6777 *top = d->topmargin;
6779 *right = d->rightmargin;
6781 *bottom = d->bottommargin;
6787 \brief The contentsMargins function returns the widget's contents margins.
6789 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6791 QMargins QWidget::contentsMargins() const
6794 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6799 Returns the area inside the widget's margins.
6801 \sa setContentsMargins(), getContentsMargins()
6803 QRect QWidget::contentsRect() const
6806 return QRect(QPoint(d->leftmargin, d->topmargin),
6807 QPoint(data->crect.width() - 1 - d->rightmargin,
6808 data->crect.height() - 1 - d->bottommargin));
6815 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6817 This signal is emitted when the widget's \l contextMenuPolicy is
6818 Qt::CustomContextMenu, and the user has requested a context menu on
6819 the widget. The position \a pos is the position of the context menu
6820 event that the widget receives. Normally this is in widget
6821 coordinates. The exception to this rule is QAbstractScrollArea and
6822 its subclasses that map the context menu event to coordinates of the
6823 \link QAbstractScrollArea::viewport() viewport() \endlink .
6826 \sa mapToGlobal() QMenu contextMenuPolicy
6831 \property QWidget::contextMenuPolicy
6832 \brief how the widget shows a context menu
6834 The default value of this property is Qt::DefaultContextMenu,
6835 which means the contextMenuEvent() handler is called. Other values
6836 are Qt::NoContextMenu, Qt::PreventContextMenu,
6837 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6838 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6841 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6844 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6846 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6849 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6851 data->context_menu_policy = (uint) policy;
6855 \property QWidget::focusPolicy
6856 \brief the way the widget accepts keyboard focus
6858 The policy is Qt::TabFocus if the widget accepts keyboard
6859 focus by tabbing, Qt::ClickFocus if the widget accepts
6860 focus by clicking, Qt::StrongFocus if it accepts both, and
6861 Qt::NoFocus (the default) if it does not accept focus at
6864 You must enable keyboard focus for a widget if it processes
6865 keyboard events. This is normally done from the widget's
6866 constructor. For instance, the QLineEdit constructor calls
6867 setFocusPolicy(Qt::StrongFocus).
6869 If the widget has a focus proxy, then the focus policy will
6870 be propagated to it.
6872 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6876 Qt::FocusPolicy QWidget::focusPolicy() const
6878 return (Qt::FocusPolicy)data->focus_policy;
6881 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6883 data->focus_policy = (uint) policy;
6885 if (d->extra && d->extra->focus_proxy)
6886 d->extra->focus_proxy->setFocusPolicy(policy);
6890 \property QWidget::updatesEnabled
6891 \brief whether updates are enabled
6893 An updates enabled widget receives paint events and has a system
6894 background; a disabled widget does not. This also implies that
6895 calling update() and repaint() has no effect if updates are
6898 By default, this property is true.
6900 setUpdatesEnabled() is normally used to disable updates for a
6901 short period of time, for instance to avoid screen flicker during
6902 large changes. In Qt, widgets normally do not generate screen
6903 flicker, but on X11 the server might erase regions on the screen
6904 when widgets get hidden before they can be replaced by other
6905 widgets. Disabling updates solves this.
6908 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6910 Disabling a widget implicitly disables all its children. Enabling a widget
6911 enables all child widgets \e except top-level widgets or those that
6912 have been explicitly disabled. Re-enabling updates implicitly calls
6913 update() on the widget.
6917 void QWidget::setUpdatesEnabled(bool enable)
6920 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6921 d->setUpdatesEnabled_helper(enable);
6924 /*! \fn void QWidget::show()
6926 Shows the widget and its child widgets. This function is
6927 equivalent to setVisible(true).
6929 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6930 showNormal(), isVisible()
6936 Makes the widget visible in the isVisible() meaning of the word.
6937 It is only called for toplevels or widgets with visible parents.
6939 void QWidgetPrivate::show_recursive()
6942 // polish if necessary
6944 if (!q->testAttribute(Qt::WA_WState_Created))
6945 createRecursively();
6946 q->ensurePolished();
6948 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6949 q->parentWidget()->d_func()->layout->activate();
6950 // activate our layout before we and our children become visible
6957 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6961 disableUpdates = disableUpdates && q->updatesEnabled();
6963 q->setAttribute(Qt::WA_UpdatesDisabled);
6965 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6966 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6967 QApplication::sendEvent(q, &e);
6968 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6971 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6972 QResizeEvent e(data.crect.size(), QSize());
6973 QApplication::sendEvent(q, &e);
6974 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6978 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6983 for (int i = 0; i < children.size(); ++i) {
6984 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6985 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6989 void QWidgetPrivate::activateChildLayoutsRecursively()
6991 sendPendingMoveAndResizeEvents(false, true);
6993 for (int i = 0; i < children.size(); ++i) {
6994 QWidget *child = qobject_cast<QWidget *>(children.at(i));
6995 if (!child || child->isHidden() || child->isWindow())
6998 child->ensurePolished();
7000 // Activate child's layout
7001 QWidgetPrivate *childPrivate = child->d_func();
7002 if (childPrivate->layout)
7003 childPrivate->layout->activate();
7005 // Pretend we're visible.
7006 const bool wasVisible = child->isVisible();
7008 child->setAttribute(Qt::WA_WState_Visible);
7010 // Do the same for all my children.
7011 childPrivate->activateChildLayoutsRecursively();
7013 // We're not cheating anymore.
7015 child->setAttribute(Qt::WA_WState_Visible, false);
7019 void QWidgetPrivate::show_helper()
7022 data.in_show = true; // qws optimization
7023 // make sure we receive pending move and resize events
7024 sendPendingMoveAndResizeEvents();
7026 // become visible before showing all children
7027 q->setAttribute(Qt::WA_WState_Visible);
7029 // finally show all children recursively
7030 showChildren(false);
7034 // popup handling: new popups and tools need to be raised, and
7035 // existing popups must be closed. Also propagate the current
7036 // windows's KeyboardFocusChange status.
7037 if (q->isWindow()) {
7038 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7040 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7041 q->setAttribute(Qt::WA_KeyboardFocusChange);
7043 while (QApplication::activePopupWidget()) {
7044 if (!QApplication::activePopupWidget()->close())
7050 // Automatic embedding of child windows of widgets already embedded into
7051 // QGraphicsProxyWidget when they are shown the first time.
7052 bool isEmbedded = false;
7053 #ifndef QT_NO_GRAPHICSVIEW
7054 if (q->isWindow()) {
7055 isEmbedded = q->graphicsProxyWidget() ? true : false;
7056 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7057 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7058 if (ancestorProxy) {
7060 ancestorProxy->d_func()->embedSubWindow(q);
7065 Q_UNUSED(isEmbedded);
7068 // On Windows, show the popup now so that our own focus handling
7069 // stores the correct old focus widget even if it's stolen in the
7071 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7072 if (!isEmbedded && q->windowType() == Qt::Popup)
7073 qApp->d_func()->openPopup(q);
7076 // send the show event before showing the window
7077 QShowEvent showEvent;
7078 QApplication::sendEvent(q, &showEvent);
7080 if (!isEmbedded && q->isModal() && q->isWindow())
7081 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7082 // stacking might be wrong
7083 QApplicationPrivate::enterModal(q);
7088 if (!isEmbedded && q->windowType() == Qt::Popup)
7089 qApp->d_func()->openPopup(q);
7091 #ifndef QT_NO_ACCESSIBILITY
7092 if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
7093 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
7096 if (QApplicationPrivate::hidden_focus_widget == q) {
7097 QApplicationPrivate::hidden_focus_widget = 0;
7098 q->setFocus(Qt::OtherFocusReason);
7101 // Process events when showing a Qt::SplashScreen widget before the event loop
7102 // is spinnning; otherwise it might not show up on particular platforms.
7103 // This makes QSplashScreen behave the same on all platforms.
7104 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7105 QApplication::processEvents();
7107 data.in_show = false; // reset qws optimization
7110 /*! \fn void QWidget::hide()
7112 Hides the widget. This function is equivalent to
7116 \note If you are working with QDialog or its subclasses and you invoke
7117 the show() function after this function, the dialog will be displayed in
7118 its original position.
7120 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7125 void QWidgetPrivate::hide_helper()
7129 bool isEmbedded = false;
7130 #if !defined QT_NO_GRAPHICSVIEW
7131 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7133 Q_UNUSED(isEmbedded);
7136 if (!isEmbedded && (q->windowType() == Qt::Popup))
7137 qApp->d_func()->closePopup(q);
7139 // Move test modal here. Otherwise, a modal dialog could get
7140 // destroyed and we lose all access to its parent because we haven't
7141 // left modality. (Eg. modal Progress Dialog)
7142 if (!isEmbedded && q->isModal() && q->isWindow())
7143 QApplicationPrivate::leaveModal(q);
7145 #if defined(Q_WS_WIN)
7146 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7147 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7148 q->parentWidget()->activateWindow(); // Activate parent
7151 q->setAttribute(Qt::WA_Mapped, false);
7154 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7157 q->setAttribute(Qt::WA_WState_Visible, false);
7161 QHideEvent hideEvent;
7162 QApplication::sendEvent(q, &hideEvent);
7163 hideChildren(false);
7165 // next bit tries to move the focus if the focus widget is now
7168 qApp->d_func()->sendSyntheticEnterLeave(q);
7169 QWidget *fw = QApplication::focusWidget();
7170 while (fw && !fw->isWindow()) {
7172 q->focusNextPrevChild(true);
7175 fw = fw->parentWidget();
7179 if (QWidgetBackingStore *bs = maybeBackingStore())
7180 bs->removeDirtyWidget(q);
7182 #ifndef QT_NO_ACCESSIBILITY
7184 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
7189 \fn bool QWidget::isHidden() const
7191 Returns true if the widget is hidden, otherwise returns false.
7193 A hidden widget will only become visible when show() is called on
7194 it. It will not be automatically shown when the parent is shown.
7196 To check visibility, use !isVisible() instead (notice the exclamation mark).
7198 isHidden() implies !isVisible(), but a widget can be not visible
7199 and not hidden at the same time. This is the case for widgets that are children of
7200 widgets that are not visible.
7203 Widgets are hidden if:
7205 \o they were created as independent windows,
7206 \o they were created as children of visible widgets,
7207 \o hide() or setVisible(false) was called.
7212 void QWidget::setVisible(bool visible)
7214 if (visible) { // show
7215 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7220 // Designer uses a trick to make grabWidget work without showing
7221 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7222 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7223 parentWidget()->window()->d_func()->createRecursively();
7225 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7226 //but not children of non-visible parents
7227 QWidget *pw = parentWidget();
7228 if (!testAttribute(Qt::WA_WState_Created)
7229 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7233 #if defined(Q_WS_X11)
7234 if (windowType() == Qt::Window)
7235 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7238 bool wasResized = testAttribute(Qt::WA_Resized);
7239 Qt::WindowStates initialWindowState = windowState();
7241 // polish if necessary
7244 // remember that show was called explicitly
7245 setAttribute(Qt::WA_WState_ExplicitShowHide);
7246 // whether we need to inform the parent widget immediately
7247 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7248 // we are no longer hidden
7249 setAttribute(Qt::WA_WState_Hidden, false);
7251 if (needUpdateGeometry)
7252 d->updateGeometry_helper(true);
7254 // activate our layout before we and our children become visible
7256 d->layout->activate();
7259 QWidget *parent = parentWidget();
7260 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7261 parent->d_func()->layout->activate();
7262 if (parent->isWindow())
7264 parent = parent->parentWidget();
7267 parent->d_func()->setDirtyOpaqueRegion();
7270 // adjust size if necessary
7272 && (isWindow() || !parentWidget()->d_func()->layout)) {
7275 if (windowState() != initialWindowState)
7276 setWindowState(initialWindowState);
7280 setAttribute(Qt::WA_Resized, false);
7283 setAttribute(Qt::WA_KeyboardFocusChange, false);
7285 if (isWindow() || parentWidget()->isVisible()) {
7286 // remove posted quit events when showing a new window
7287 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
7291 qApp->d_func()->sendSyntheticEnterLeave(this);
7294 QEvent showToParentEvent(QEvent::ShowToParent);
7295 QApplication::sendEvent(this, &showToParentEvent);
7297 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7299 #if defined(Q_WS_WIN)
7300 // reset WS_DISABLED style in a Blocked window
7301 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7302 && QApplicationPrivate::isBlockedByModal(this))
7304 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7305 dwStyle &= ~WS_DISABLED;
7306 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7309 if (QApplicationPrivate::hidden_focus_widget == this)
7310 QApplicationPrivate::hidden_focus_widget = 0;
7314 // hw: The test on getOpaqueRegion() needs to be more intelligent
7315 // currently it doesn't work if the widget is hidden (the region will
7316 // be clipped). The real check should be testing the cached region
7317 // (and dirty flag) directly.
7318 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7319 parentWidget()->d_func()->setDirtyOpaqueRegion();
7321 setAttribute(Qt::WA_WState_Hidden);
7322 setAttribute(Qt::WA_WState_ExplicitShowHide);
7323 if (testAttribute(Qt::WA_WState_Created))
7326 // invalidate layout similar to updateGeometry()
7327 if (!isWindow() && parentWidget()) {
7328 if (parentWidget()->d_func()->layout)
7329 parentWidget()->d_func()->layout->invalidate();
7330 else if (parentWidget()->isVisible())
7331 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7334 QEvent hideToParentEvent(QEvent::HideToParent);
7335 QApplication::sendEvent(this, &hideToParentEvent);
7339 /*!\fn void QWidget::setHidden(bool hidden)
7341 Convenience function, equivalent to setVisible(!\a hidden).
7345 void QWidgetPrivate::_q_showIfNotHidden()
7348 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7349 q->setVisible(true);
7352 void QWidgetPrivate::showChildren(bool spontaneous)
7354 QList<QObject*> childList = children;
7355 for (int i = 0; i < childList.size(); ++i) {
7356 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7358 || widget->isWindow()
7359 || widget->testAttribute(Qt::WA_WState_Hidden))
7362 widget->setAttribute(Qt::WA_Mapped);
7363 widget->d_func()->showChildren(true);
7365 QApplication::sendSpontaneousEvent(widget, &e);
7367 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7368 widget->d_func()->show_recursive();
7375 void QWidgetPrivate::hideChildren(bool spontaneous)
7377 QList<QObject*> childList = children;
7378 for (int i = 0; i < childList.size(); ++i) {
7379 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7380 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7383 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7384 // When hiding a widget we need to make sure that no mouse_down events are active, because
7385 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7386 // The solution is simple, before going through with this we check if there are any mouse_down events in
7387 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7388 // then we continue.
7389 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7390 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7391 // mouse release event. There are two ways to interpret this:
7392 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7393 // might be waiting for a release event that will never arrive.
7394 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7395 // supposed to trigger because it is not visible.
7396 if(widget == qt_button_down)
7400 widget->setAttribute(Qt::WA_Mapped, false);
7402 widget->setAttribute(Qt::WA_WState_Visible, false);
7403 widget->d_func()->hideChildren(spontaneous);
7406 QApplication::sendSpontaneousEvent(widget, &e);
7408 QApplication::sendEvent(widget, &e);
7409 if (widget->internalWinId()
7410 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7411 // hide_sys() on an ancestor won't have any affect on this
7412 // widget, so it needs an explicit hide_sys() of its own
7413 widget->d_func()->hide_sys();
7416 qApp->d_func()->sendSyntheticEnterLeave(widget);
7417 #ifndef QT_NO_ACCESSIBILITY
7419 QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
7424 bool QWidgetPrivate::close_helper(CloseMode mode)
7426 if (data.is_closing)
7430 data.is_closing = 1;
7432 QPointer<QWidget> that = q;
7433 QPointer<QWidget> parentWidget = q->parentWidget();
7435 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7436 if (mode != CloseNoEvent) {
7438 if (mode == CloseWithSpontaneousEvent)
7439 QApplication::sendSpontaneousEvent(q, &e);
7441 QApplication::sendEvent(q, &e);
7442 if (!that.isNull() && !e.isAccepted()) {
7443 data.is_closing = 0;
7448 if (!that.isNull() && !q->isHidden())
7451 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7452 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7455 /* if there is no non-withdrawn primary window left (except
7456 the ones without QuitOnClose), we emit the lastWindowClosed
7458 QWidgetList list = QApplication::topLevelWidgets();
7459 bool lastWindowClosed = true;
7460 for (int i = 0; i < list.size(); ++i) {
7461 QWidget *w = list.at(i);
7462 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7464 lastWindowClosed = false;
7467 if (lastWindowClosed)
7468 QApplicationPrivate::emitLastWindowClosed();
7471 if (!that.isNull()) {
7472 data.is_closing = 0;
7473 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7474 q->setAttribute(Qt::WA_DeleteOnClose, false);
7483 Closes this widget. Returns true if the widget was closed;
7484 otherwise returns false.
7486 First it sends the widget a QCloseEvent. The widget is \link
7487 hide() hidden\endlink if it \link QCloseEvent::accept()
7488 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7489 ignores\endlink the event, nothing happens. The default
7490 implementation of QWidget::closeEvent() accepts the close event.
7492 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7493 is also deleted. A close events is delivered to the widget no
7494 matter if the widget is visible or not.
7496 The \l QApplication::lastWindowClosed() signal is emitted when the
7497 last visible primary window (i.e. window with no parent) with the
7498 Qt::WA_QuitOnClose attribute set is closed. By default this
7499 attribute is set for all widgets except transient windows such as
7500 splash screens, tool windows, and popup menus.
7504 bool QWidget::close()
7506 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7510 \property QWidget::visible
7511 \brief whether the widget is visible
7513 Calling setVisible(true) or show() sets the widget to visible
7514 status if all its parent widgets up to the window are visible. If
7515 an ancestor is not visible, the widget won't become visible until
7516 all its ancestors are shown. If its size or position has changed,
7517 Qt guarantees that a widget gets move and resize events just
7518 before it is shown. If the widget has not been resized yet, Qt
7519 will adjust the widget's size to a useful default using
7522 Calling setVisible(false) or hide() hides a widget explicitly. An
7523 explicitly hidden widget will never become visible, even if all
7524 its ancestors become visible, unless you show it.
7526 A widget receives show and hide events when its visibility status
7527 changes. Between a hide and a show event, there is no need to
7528 waste CPU cycles preparing or displaying information to the user.
7529 A video application, for example, might simply stop generating new
7532 A widget that happens to be obscured by other windows on the
7533 screen is considered to be visible. The same applies to iconified
7534 windows and windows that exist on another virtual
7535 desktop (on platforms that support this concept). A widget
7536 receives spontaneous show and hide events when its mapping status
7537 is changed by the window system, e.g. a spontaneous hide event
7538 when the user minimizes the window, and a spontaneous show event
7539 when the window is restored again.
7541 You almost never have to reimplement the setVisible() function. If
7542 you need to change some settings before a widget is shown, use
7543 showEvent() instead. If you need to do some delayed initialization
7544 use the Polish event delivered to the event() function.
7546 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7547 showEvent(), hideEvent()
7552 Returns true if this widget would become visible if \a ancestor is
7553 shown; otherwise returns false.
7555 The true case occurs if neither the widget itself nor any parent
7556 up to but excluding \a ancestor has been explicitly hidden.
7558 This function will still return true if the widget is obscured by
7559 other windows on the screen, but could be physically visible if it
7560 or they were to be moved.
7562 isVisibleTo(0) is identical to isVisible().
7564 \sa show() hide() isVisible()
7567 bool QWidget::isVisibleTo(QWidget* ancestor) const
7571 const QWidget * w = this;
7572 while (!w->isHidden()
7574 && w->parentWidget()
7575 && w->parentWidget() != ancestor)
7576 w = w->parentWidget();
7577 return !w->isHidden();
7582 Returns the unobscured region where paint events can occur.
7584 For visible widgets, this is an approximation of the area not
7585 covered by other widgets; otherwise, this is an empty region.
7587 The repaint() function calls this function if necessary, so in
7588 general you do not need to call it.
7591 QRegion QWidget::visibleRegion() const
7595 QRect clipRect = d->clipRect();
7596 if (clipRect.isEmpty())
7598 QRegion r(clipRect);
7599 d->subtractOpaqueChildren(r, clipRect);
7600 d->subtractOpaqueSiblings(r);
7605 QSize QWidgetPrivate::adjustedSize() const
7609 QSize s = q->sizeHint();
7611 if (q->isWindow()) {
7612 Qt::Orientations exp;
7614 if (layout->hasHeightForWidth())
7615 s.setHeight(layout->totalHeightForWidth(s.width()));
7616 exp = layout->expandingDirections();
7619 if (q->sizePolicy().hasHeightForWidth())
7620 s.setHeight(q->heightForWidth(s.width()));
7621 exp = q->sizePolicy().expandingDirections();
7623 if (exp & Qt::Horizontal)
7624 s.setWidth(qMax(s.width(), 200));
7625 if (exp & Qt::Vertical)
7626 s.setHeight(qMax(s.height(), 100));
7627 #if defined(Q_WS_X11)
7628 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7630 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7632 #if defined (Q_WS_WINCE)
7633 s.setWidth(qMin(s.width(), screen.width()));
7634 s.setHeight(qMin(s.height(), screen.height()));
7636 s.setWidth(qMin(s.width(), screen.width()*2/3));
7637 s.setHeight(qMin(s.height(), screen.height()*2/3));
7639 if (QTLWExtra *extra = maybeTopData())
7640 extra->sizeAdjusted = true;
7644 QRect r = q->childrenRect(); // get children rectangle
7647 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7654 Adjusts the size of the widget to fit its contents.
7656 This function uses sizeHint() if it is valid, i.e., the size hint's width
7657 and height are \>= 0. Otherwise, it sets the size to the children
7658 rectangle that covers all child widgets (the union of all child widget
7661 For windows, the screen size is also taken into account. If the sizeHint()
7662 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7663 {expanding}, the window will be at least (200, 100). The maximum size of
7664 a window is 2/3 of the screen's width and height.
7666 \sa sizeHint(), childrenRect()
7669 void QWidget::adjustSize()
7673 QSize s = d->adjustedSize();
7676 d->layout->activate();
7684 \property QWidget::sizeHint
7685 \brief the recommended size for the widget
7687 If the value of this property is an invalid size, no size is
7690 The default implementation of sizeHint() returns an invalid size
7691 if there is no layout for this widget, and returns the layout's
7692 preferred size otherwise.
7694 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7695 setMinimumSize(), updateGeometry()
7698 QSize QWidget::sizeHint() const
7702 return d->layout->totalSizeHint();
7703 return QSize(-1, -1);
7707 \property QWidget::minimumSizeHint
7708 \brief the recommended minimum size for the widget
7710 If the value of this property is an invalid size, no minimum size
7713 The default implementation of minimumSizeHint() returns an invalid
7714 size if there is no layout for this widget, and returns the
7715 layout's minimum size otherwise. Most built-in widgets reimplement
7718 \l QLayout will never resize a widget to a size smaller than the
7719 minimum size hint unless minimumSize() is set or the size policy is
7720 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7721 size hint will be ignored.
7723 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7725 QSize QWidget::minimumSizeHint() const
7729 return d->layout->totalMinimumSize();
7730 return QSize(-1, -1);
7735 \fn QWidget *QWidget::parentWidget() const
7737 Returns the parent of this widget, or 0 if it does not have any
7743 Returns true if this widget is a parent, (or grandparent and so on
7744 to any level), of the given \a child, and both widgets are within
7745 the same window; otherwise returns false.
7748 bool QWidget::isAncestorOf(const QWidget *child) const
7753 if (child->isWindow())
7755 child = child->parentWidget();
7760 #if defined(Q_WS_WIN)
7761 inline void setDisabledStyle(QWidget *w, bool setStyle)
7763 // set/reset WS_DISABLED style.
7764 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7765 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7766 LONG newStyle = dwStyle;
7768 newStyle |= WS_DISABLED;
7770 newStyle &= ~WS_DISABLED;
7771 if (newStyle != dwStyle) {
7772 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7773 // we might need to repaint in some situations (eg. menu)
7780 /*****************************************************************************
7781 QWidget event handling
7782 *****************************************************************************/
7785 This is the main event handler; it handles event \a event. You can
7786 reimplement this function in a subclass, but we recommend using
7787 one of the specialized event handlers instead.
7789 Key press and release events are treated differently from other
7790 events. event() checks for Tab and Shift+Tab and tries to move the
7791 focus appropriately. If there is no widget to move the focus to
7792 (or the key press is not Tab or Shift+Tab), event() calls
7795 Mouse and tablet event handling is also slightly special: only
7796 when the widget is \l enabled, event() will call the specialized
7797 handlers such as mousePressEvent(); otherwise it will discard the
7800 This function returns true if the event was recognized, otherwise
7801 it returns false. If the recognized event was accepted (see \l
7802 QEvent::accepted), any further processing such as event
7803 propagation to the parent widget stops.
7805 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7806 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7807 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7808 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7809 QObject::event(), QObject::timerEvent()
7812 bool QWidget::event(QEvent *event)
7816 // ignore mouse events when disabled
7818 switch(event->type()) {
7819 case QEvent::TabletPress:
7820 case QEvent::TabletRelease:
7821 case QEvent::TabletMove:
7822 case QEvent::MouseButtonPress:
7823 case QEvent::MouseButtonRelease:
7824 case QEvent::MouseButtonDblClick:
7825 case QEvent::MouseMove:
7826 case QEvent::TouchBegin:
7827 case QEvent::TouchUpdate:
7828 case QEvent::TouchEnd:
7829 case QEvent::ContextMenu:
7830 #ifndef QT_NO_WHEELEVENT
7838 switch (event->type()) {
7839 case QEvent::MouseMove:
7840 mouseMoveEvent((QMouseEvent*)event);
7843 case QEvent::MouseButtonPress:
7844 mousePressEvent((QMouseEvent*)event);
7847 case QEvent::MouseButtonRelease:
7848 mouseReleaseEvent((QMouseEvent*)event);
7851 case QEvent::MouseButtonDblClick:
7852 mouseDoubleClickEvent((QMouseEvent*)event);
7854 #ifndef QT_NO_WHEELEVENT
7856 wheelEvent((QWheelEvent*)event);
7859 #ifndef QT_NO_TABLETEVENT
7860 case QEvent::TabletMove:
7861 case QEvent::TabletPress:
7862 case QEvent::TabletRelease:
7863 tabletEvent((QTabletEvent*)event);
7866 case QEvent::KeyPress: {
7867 QKeyEvent *k = (QKeyEvent *)event;
7869 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7870 if (k->key() == Qt::Key_Backtab
7871 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7872 res = focusNextPrevChild(false);
7873 else if (k->key() == Qt::Key_Tab)
7874 res = focusNextPrevChild(true);
7879 #ifdef QT_KEYPAD_NAVIGATION
7880 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7881 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7882 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7883 if (k->key() == Qt::Key_Up)
7884 res = focusNextPrevChild(false);
7885 else if (k->key() == Qt::Key_Down)
7886 res = focusNextPrevChild(true);
7887 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7888 if (k->key() == Qt::Key_Up)
7889 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7890 else if (k->key() == Qt::Key_Right)
7891 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7892 else if (k->key() == Qt::Key_Down)
7893 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7894 else if (k->key() == Qt::Key_Left)
7895 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7903 #ifndef QT_NO_WHATSTHIS
7904 if (!k->isAccepted()
7905 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7906 && d->whatsThis.size()) {
7907 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7914 case QEvent::KeyRelease:
7915 keyReleaseEvent((QKeyEvent*)event);
7917 case QEvent::ShortcutOverride:
7920 case QEvent::InputMethod:
7921 inputMethodEvent((QInputMethodEvent *) event);
7924 case QEvent::InputMethodQuery:
7925 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7926 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7927 Qt::InputMethodQueries queries = query->queries();
7928 for (uint i = 0; i < 32; ++i) {
7929 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7931 QVariant v = inputMethodQuery(q);
7932 if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7933 v = QVariant(true); // special case for Qt4 compatibility
7934 query->setValue(q, v);
7941 case QEvent::PolishRequest:
7945 case QEvent::Polish: {
7946 style()->polish(this);
7947 setAttribute(Qt::WA_WState_Polished);
7948 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7950 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7951 d->resolvePalette();
7955 case QEvent::ApplicationWindowIconChange:
7956 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7957 d->setWindowIcon_sys();
7958 d->setWindowIcon_helper();
7961 case QEvent::FocusIn:
7962 #ifdef QT_SOFTKEYS_ENABLED
7963 QSoftKeyManager::updateSoftKeys();
7965 focusInEvent((QFocusEvent*)event);
7966 d->updateWidgetTransform();
7969 case QEvent::FocusOut:
7970 focusOutEvent((QFocusEvent*)event);
7974 #ifndef QT_NO_STATUSTIP
7975 if (d->statusTip.size()) {
7976 QStatusTipEvent tip(d->statusTip);
7977 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7984 #ifndef QT_NO_STATUSTIP
7985 if (d->statusTip.size()) {
7987 QStatusTipEvent tip(empty);
7988 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7994 case QEvent::HoverEnter:
7995 case QEvent::HoverLeave:
8000 // At this point the event has to be delivered, regardless
8001 // whether the widget isVisible() or not because it
8002 // already went through the filters
8003 paintEvent((QPaintEvent*)event);
8007 moveEvent((QMoveEvent*)event);
8008 d->updateWidgetTransform();
8011 case QEvent::Resize:
8012 resizeEvent((QResizeEvent*)event);
8013 d->updateWidgetTransform();
8017 closeEvent((QCloseEvent *)event);
8020 #ifndef QT_NO_CONTEXTMENU
8021 case QEvent::ContextMenu:
8022 switch (data->context_menu_policy) {
8023 case Qt::PreventContextMenu:
8025 case Qt::DefaultContextMenu:
8026 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8028 case Qt::CustomContextMenu:
8029 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8032 case Qt::ActionsContextMenu:
8033 if (d->actions.count()) {
8034 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8045 #endif // QT_NO_CONTEXTMENU
8047 #ifndef QT_NO_DRAGANDDROP
8049 dropEvent((QDropEvent*) event);
8052 case QEvent::DragEnter:
8053 dragEnterEvent((QDragEnterEvent*) event);
8056 case QEvent::DragMove:
8057 dragMoveEvent((QDragMoveEvent*) event);
8060 case QEvent::DragLeave:
8061 dragLeaveEvent((QDragLeaveEvent*) event);
8066 showEvent((QShowEvent*) event);
8070 hideEvent((QHideEvent*) event);
8073 case QEvent::ShowWindowRequest:
8078 case QEvent::ApplicationFontChange:
8081 case QEvent::ApplicationPaletteChange:
8082 if (!(windowType() == Qt::Desktop))
8083 d->resolvePalette();
8086 case QEvent::ToolBarChange:
8087 case QEvent::ActivationChange:
8088 case QEvent::EnabledChange:
8089 case QEvent::FontChange:
8090 case QEvent::StyleChange:
8091 case QEvent::PaletteChange:
8092 case QEvent::WindowTitleChange:
8093 case QEvent::IconTextChange:
8094 case QEvent::ModifiedChange:
8095 case QEvent::MouseTrackingChange:
8096 case QEvent::ParentChange:
8097 case QEvent::WindowStateChange:
8098 case QEvent::LocaleChange:
8099 case QEvent::MacSizeChange:
8100 case QEvent::ContentsRectChange:
8104 case QEvent::WindowActivate:
8105 case QEvent::WindowDeactivate: {
8106 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8108 QList<QObject*> childList = d->children;
8109 for (int i = 0; i < childList.size(); ++i) {
8110 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8111 if (w && w->isVisible() && !w->isWindow())
8112 QApplication::sendEvent(w, event);
8115 #ifdef QT_SOFTKEYS_ENABLED
8117 QSoftKeyManager::updateSoftKeys();
8122 case QEvent::LanguageChange:
8125 QList<QObject*> childList = d->children;
8126 for (int i = 0; i < childList.size(); ++i) {
8127 QObject *o = childList.at(i);
8129 QApplication::sendEvent(o, event);
8135 case QEvent::ApplicationLayoutDirectionChange:
8136 d->resolveLayoutDirection();
8139 case QEvent::LayoutDirectionChange:
8141 d->layout->invalidate();
8145 case QEvent::UpdateRequest:
8146 d->syncBackingStore();
8148 case QEvent::UpdateLater:
8149 update(static_cast<QUpdateLaterEvent*>(event)->region());
8152 case QEvent::WindowBlocked:
8153 case QEvent::WindowUnblocked:
8155 QList<QObject*> childList = d->children;
8156 for (int i = 0; i < childList.size(); ++i) {
8157 QObject *o = childList.at(i);
8158 if (o && o != QApplication::activeModalWidget()) {
8159 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8160 // do not forward the event to child windows,
8161 // QApplication does this for us
8164 QApplication::sendEvent(o, event);
8167 #if defined(Q_WS_WIN)
8168 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8172 #ifndef QT_NO_TOOLTIP
8173 case QEvent::ToolTip:
8174 if (!d->toolTip.isEmpty())
8175 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8180 #ifndef QT_NO_WHATSTHIS
8181 case QEvent::WhatsThis:
8182 if (d->whatsThis.size())
8183 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8187 case QEvent::QueryWhatsThis:
8188 if (d->whatsThis.isEmpty())
8192 case QEvent::EmbeddingControl:
8193 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8194 data->fstrut_dirty = false;
8195 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8196 d->topData()->embedded = 1;
8199 #ifndef QT_NO_ACTION
8200 case QEvent::ActionAdded:
8201 case QEvent::ActionRemoved:
8202 case QEvent::ActionChanged:
8203 #ifdef QT_SOFTKEYS_ENABLED
8204 QSoftKeyManager::updateSoftKeys();
8206 actionEvent((QActionEvent*)event);
8210 case QEvent::KeyboardLayoutChange:
8214 // inform children of the change
8215 QList<QObject*> childList = d->children;
8216 for (int i = 0; i < childList.size(); ++i) {
8217 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8218 if (w && w->isVisible() && !w->isWindow())
8219 QApplication::sendEvent(w, event);
8224 case QEvent::MacGLWindowChange:
8225 d->needWindowChange = false;
8228 case QEvent::TouchBegin:
8229 case QEvent::TouchUpdate:
8230 case QEvent::TouchEnd:
8235 #ifndef QT_NO_GESTURES
8236 case QEvent::Gesture:
8240 #ifndef QT_NO_PROPERTIES
8241 case QEvent::DynamicPropertyChange: {
8242 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8243 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8244 uint value = property(propName.constData()).toUInt();
8247 const char axis = propName.at(12);
8249 d->extra->customDpiX = value;
8250 else if (axis == 'Y')
8251 d->extra->customDpiY = value;
8252 d->updateFont(d->data.fnt);
8258 return QObject::event(event);
8264 This event handler can be reimplemented to handle state changes.
8266 The state being changed in this event can be retrieved through the \a event
8269 Change events include: QEvent::ToolBarChange,
8270 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8271 QEvent::StyleChange, QEvent::PaletteChange,
8272 QEvent::WindowTitleChange, QEvent::IconTextChange,
8273 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8274 QEvent::ParentChange, QEvent::WindowStateChange,
8275 QEvent::LanguageChange, QEvent::LocaleChange,
8276 QEvent::LayoutDirectionChange.
8279 void QWidget::changeEvent(QEvent * event)
8281 switch(event->type()) {
8282 case QEvent::EnabledChange:
8284 #ifndef QT_NO_ACCESSIBILITY
8285 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
8289 case QEvent::FontChange:
8290 case QEvent::StyleChange: {
8295 d->layout->invalidate();
8299 case QEvent::PaletteChange:
8304 case QEvent::MacSizeChange:
8307 case QEvent::ToolTipChange:
8308 case QEvent::MouseTrackingChange:
8309 qt_mac_update_mouseTracking(this);
8319 This event handler, for event \a event, can be reimplemented in a
8320 subclass to receive mouse move events for the widget.
8322 If mouse tracking is switched off, mouse move events only occur if
8323 a mouse button is pressed while the mouse is being moved. If mouse
8324 tracking is switched on, mouse move events occur even if no mouse
8327 QMouseEvent::pos() reports the position of the mouse cursor,
8328 relative to this widget. For press and release events, the
8329 position is usually the same as the position of the last mouse
8330 move event, but it might be different if the user's hand shakes.
8331 This is a feature of the underlying window system, not Qt.
8333 If you want to show a tooltip immediately, while the mouse is
8334 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8335 and show them as a tooltip), you must first enable mouse tracking
8336 as described above. Then, to ensure that the tooltip is updated
8337 immediately, you must call QToolTip::showText() instead of
8338 setToolTip() in your implementation of mouseMoveEvent().
8340 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8341 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8344 void QWidget::mouseMoveEvent(QMouseEvent *event)
8350 This event handler, for event \a event, can be reimplemented in a
8351 subclass to receive mouse press events for the widget.
8353 If you create new widgets in the mousePressEvent() the
8354 mouseReleaseEvent() may not end up where you expect, depending on
8355 the underlying window system (or X11 window manager), the widgets'
8356 location and maybe more.
8358 The default implementation implements the closing of popup widgets
8359 when you click outside the window. For other widget types it does
8362 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8363 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8366 void QWidget::mousePressEvent(QMouseEvent *event)
8369 if ((windowType() == Qt::Popup)) {
8372 while ((w = QApplication::activePopupWidget()) && w != this){
8374 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8375 w->hide(); // hide at least
8377 if (!rect().contains(event->pos())){
8384 This event handler, for event \a event, can be reimplemented in a
8385 subclass to receive mouse release events for the widget.
8387 \sa mousePressEvent(), mouseDoubleClickEvent(),
8388 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8391 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8397 This event handler, for event \a event, can be reimplemented in a
8398 subclass to receive mouse double click events for the widget.
8400 The default implementation generates a normal mouse press event.
8402 \note The widget will also receive mouse press and mouse release
8403 events in addition to the double click event. It is up to the
8404 developer to ensure that the application interprets these events
8407 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8408 event(), QMouseEvent
8411 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8413 mousePressEvent(event); // try mouse press event
8416 #ifndef QT_NO_WHEELEVENT
8418 This event handler, for event \a event, can be reimplemented in a
8419 subclass to receive wheel events for the widget.
8421 If you reimplement this handler, it is very important that you
8422 \link QWheelEvent ignore()\endlink the event if you do not handle
8423 it, so that the widget's parent can interpret it.
8425 The default implementation ignores the event.
8427 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8431 void QWidget::wheelEvent(QWheelEvent *event)
8435 #endif // QT_NO_WHEELEVENT
8437 #ifndef QT_NO_TABLETEVENT
8439 This event handler, for event \a event, can be reimplemented in a
8440 subclass to receive tablet events for the widget.
8442 If you reimplement this handler, it is very important that you
8443 \link QTabletEvent ignore()\endlink the event if you do not handle
8444 it, so that the widget's parent can interpret it.
8446 The default implementation ignores the event.
8448 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8452 void QWidget::tabletEvent(QTabletEvent *event)
8456 #endif // QT_NO_TABLETEVENT
8459 This event handler, for event \a event, can be reimplemented in a
8460 subclass to receive key press events for the widget.
8462 A widget must call setFocusPolicy() to accept focus initially and
8463 have focus in order to receive a key press event.
8465 If you reimplement this handler, it is very important that you
8466 call the base class implementation if you do not act upon the key.
8468 The default implementation closes popup widgets if the user
8469 presses Esc. Otherwise the event is ignored, so that the widget's
8470 parent can interpret it.
8472 Note that QKeyEvent starts with isAccepted() == true, so you do not
8473 need to call QKeyEvent::accept() - just do not call the base class
8474 implementation if you act upon the key.
8476 \sa keyReleaseEvent(), setFocusPolicy(),
8477 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8480 void QWidget::keyPressEvent(QKeyEvent *event)
8482 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8491 This event handler, for event \a event, can be reimplemented in a
8492 subclass to receive key release events for the widget.
8494 A widget must \link setFocusPolicy() accept focus\endlink
8495 initially and \link hasFocus() have focus\endlink in order to
8496 receive a key release event.
8498 If you reimplement this handler, it is very important that you
8499 call the base class implementation if you do not act upon the key.
8501 The default implementation ignores the event, so that the widget's
8502 parent can interpret it.
8504 Note that QKeyEvent starts with isAccepted() == true, so you do not
8505 need to call QKeyEvent::accept() - just do not call the base class
8506 implementation if you act upon the key.
8508 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8509 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8512 void QWidget::keyReleaseEvent(QKeyEvent *event)
8518 \fn void QWidget::focusInEvent(QFocusEvent *event)
8520 This event handler can be reimplemented in a subclass to receive
8521 keyboard focus events (focus received) for the widget. The event
8522 is passed in the \a event parameter
8524 A widget normally must setFocusPolicy() to something other than
8525 Qt::NoFocus in order to receive focus events. (Note that the
8526 application programmer can call setFocus() on any widget, even
8527 those that do not normally accept focus.)
8529 The default implementation updates the widget (except for windows
8530 that do not specify a focusPolicy()).
8532 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8533 keyReleaseEvent(), event(), QFocusEvent
8536 void QWidget::focusInEvent(QFocusEvent *)
8538 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8544 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8546 This event handler can be reimplemented in a subclass to receive
8547 keyboard focus events (focus lost) for the widget. The events is
8548 passed in the \a event parameter.
8550 A widget normally must setFocusPolicy() to something other than
8551 Qt::NoFocus in order to receive focus events. (Note that the
8552 application programmer can call setFocus() on any widget, even
8553 those that do not normally accept focus.)
8555 The default implementation updates the widget (except for windows
8556 that do not specify a focusPolicy()).
8558 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8559 keyReleaseEvent(), event(), QFocusEvent
8562 void QWidget::focusOutEvent(QFocusEvent *)
8564 if (focusPolicy() != Qt::NoFocus || !isWindow())
8569 \fn void QWidget::enterEvent(QEvent *event)
8571 This event handler can be reimplemented in a subclass to receive
8572 widget enter events which are passed in the \a event parameter.
8574 An event is sent to the widget when the mouse cursor enters the
8577 \sa leaveEvent(), mouseMoveEvent(), event()
8580 void QWidget::enterEvent(QEvent *)
8585 \fn void QWidget::leaveEvent(QEvent *event)
8587 This event handler can be reimplemented in a subclass to receive
8588 widget leave events which are passed in the \a event parameter.
8590 A leave event is sent to the widget when the mouse cursor leaves
8593 \sa enterEvent(), mouseMoveEvent(), event()
8596 void QWidget::leaveEvent(QEvent *)
8601 \fn void QWidget::paintEvent(QPaintEvent *event)
8603 This event handler can be reimplemented in a subclass to receive paint
8604 events passed in \a event.
8606 A paint event is a request to repaint all or part of a widget. It can
8607 happen for one of the following reasons:
8610 \o repaint() or update() was invoked,
8611 \o the widget was obscured and has now been uncovered, or
8612 \o many other reasons.
8615 Many widgets can simply repaint their entire surface when asked to, but
8616 some slow widgets need to optimize by painting only the requested region:
8617 QPaintEvent::region(). This speed optimization does not change the result,
8618 as painting is clipped to that region during event processing. QListView
8619 and QTableView do this, for example.
8621 Qt also tries to speed up painting by merging multiple paint events into
8622 one. When update() is called several times or the window system sends
8623 several paint events, Qt merges these events into one event with a larger
8624 region (see QRegion::united()). The repaint() function does not permit this
8625 optimization, so we suggest using update() whenever possible.
8627 When the paint event occurs, the update region has normally been erased, so
8628 you are painting on the widget's background.
8630 The background can be set using setBackgroundRole() and setPalette().
8632 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8633 is no need to write double-buffering code in paintEvent() to avoid flicker.
8635 \bold{Note for the X11 platform}: It is possible to toggle global double
8636 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8638 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8640 \note Generally, you should refrain from calling update() or repaint()
8641 \bold{inside} a paintEvent(). For example, calling update() or repaint() on
8642 children inside a paintevent() results in undefined behavior; the child may
8643 or may not get a paint event.
8645 \warning If you are using a custom paint engine without Qt's backingstore,
8646 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8647 never be called; the backingstore will be used instead.
8649 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8650 {Analog Clock Example}
8653 void QWidget::paintEvent(QPaintEvent *)
8659 \fn void QWidget::moveEvent(QMoveEvent *event)
8661 This event handler can be reimplemented in a subclass to receive
8662 widget move events which are passed in the \a event parameter.
8663 When the widget receives this event, it is already at the new
8666 The old position is accessible through QMoveEvent::oldPos().
8668 \sa resizeEvent(), event(), move(), QMoveEvent
8671 void QWidget::moveEvent(QMoveEvent *)
8677 This event handler can be reimplemented in a subclass to receive
8678 widget resize events which are passed in the \a event parameter.
8679 When resizeEvent() is called, the widget already has its new
8680 geometry. The old size is accessible through
8681 QResizeEvent::oldSize().
8683 The widget will be erased and receive a paint event immediately
8684 after processing the resize event. No drawing need be (or should
8685 be) done inside this handler.
8688 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8692 void QWidget::resizeEvent(QResizeEvent * /* event */)
8696 #ifndef QT_NO_ACTION
8698 \fn void QWidget::actionEvent(QActionEvent *event)
8700 This event handler is called with the given \a event whenever the
8701 widget's actions are changed.
8703 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8705 void QWidget::actionEvent(QActionEvent *)
8712 This event handler is called with the given \a event when Qt receives a window
8713 close request for a top-level widget from the window system.
8715 By default, the event is accepted and the widget is closed. You can reimplement
8716 this function to change the way the widget responds to window close requests.
8717 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8720 Main window applications typically use reimplementations of this function to check
8721 whether the user's work has been saved and ask for permission before closing.
8722 For example, the \l{Application Example} uses a helper function to determine whether
8723 or not to close the window:
8725 \snippet mainwindows/application/mainwindow.cpp 3
8726 \snippet mainwindows/application/mainwindow.cpp 4
8728 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8731 void QWidget::closeEvent(QCloseEvent *event)
8736 #ifndef QT_NO_CONTEXTMENU
8738 This event handler, for event \a event, can be reimplemented in a
8739 subclass to receive widget context menu events.
8741 The handler is called when the widget's \l contextMenuPolicy is
8742 Qt::DefaultContextMenu.
8744 The default implementation ignores the context event.
8745 See the \l QContextMenuEvent documentation for more details.
8747 \sa event(), QContextMenuEvent customContextMenuRequested()
8750 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8754 #endif // QT_NO_CONTEXTMENU
8758 This event handler, for event \a event, can be reimplemented in a
8759 subclass to receive Input Method composition events. This handler
8760 is called when the state of the input method changes.
8762 Note that when creating custom text editing widgets, the
8763 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8764 (using the setAttribute() function) in order to receive input
8767 The default implementation calls event->ignore(), which rejects the
8768 Input Method event. See the \l QInputMethodEvent documentation for more
8771 \sa event(), QInputMethodEvent
8773 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8779 This method is only relevant for input widgets. It is used by the
8780 input method to query a set of properties of the widget to be
8781 able to support complex input method operations as support for
8782 surrounding text and reconversions.
8784 \a query specifies which property is queried.
8786 \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
8788 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8791 case Qt::ImCursorRectangle:
8792 return QRect(width()/2, 0, 1, height());
8795 case Qt::ImAnchorPosition:
8797 return inputMethodQuery(Qt::ImCursorPosition);
8799 return (int)inputMethodHints();
8806 \property QWidget::inputMethodHints
8807 \brief What input method specific hints the widget has.
8809 This is only relevant for input widgets. It is used by
8810 the input method to retrieve hints as to how the input method
8811 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8812 is set, the input method may change its visual components to reflect
8813 that only numbers can be entered.
8815 \note The flags are only hints, so the particular input method
8816 implementation is free to ignore them. If you want to be
8817 sure that a certain type of characters are entered,
8818 you should also set a QValidator on the widget.
8820 The default value is Qt::ImhNone.
8824 \sa inputMethodQuery(), QInputContext
8826 Qt::InputMethodHints QWidget::inputMethodHints() const
8829 const QWidgetPrivate *priv = d_func();
8830 while (priv->inheritsInputMethodHints) {
8831 priv = priv->q_func()->parentWidget()->d_func();
8834 return priv->imHints;
8840 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8845 qApp->inputPanel()->update(Qt::ImHints);
8850 #ifndef QT_NO_DRAGANDDROP
8853 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8855 This event handler is called when a drag is in progress and the
8856 mouse enters this widget. The event is passed in the \a event parameter.
8858 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8861 See the \link dnd.html Drag-and-drop documentation\endlink for an
8862 overview of how to provide drag-and-drop in your application.
8864 \sa QDrag, QDragEnterEvent
8866 void QWidget::dragEnterEvent(QDragEnterEvent *)
8871 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8873 This event handler is called if a drag is in progress, and when
8874 any of the following conditions occur: the cursor enters this widget,
8875 the cursor moves within this widget, or a modifier key is pressed on
8876 the keyboard while this widget has the focus. The event is passed
8877 in the \a event parameter.
8879 See the \link dnd.html Drag-and-drop documentation\endlink for an
8880 overview of how to provide drag-and-drop in your application.
8882 \sa QDrag, QDragMoveEvent
8884 void QWidget::dragMoveEvent(QDragMoveEvent *)
8889 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8891 This event handler is called when a drag is in progress and the
8892 mouse leaves this widget. The event is passed in the \a event
8895 See the \link dnd.html Drag-and-drop documentation\endlink for an
8896 overview of how to provide drag-and-drop in your application.
8898 \sa QDrag, QDragLeaveEvent
8900 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8905 \fn void QWidget::dropEvent(QDropEvent *event)
8907 This event handler is called when the drag is dropped on this
8908 widget. The event is passed in the \a event parameter.
8910 See the \link dnd.html Drag-and-drop documentation\endlink for an
8911 overview of how to provide drag-and-drop in your application.
8913 \sa QDrag, QDropEvent
8915 void QWidget::dropEvent(QDropEvent *)
8919 #endif // QT_NO_DRAGANDDROP
8922 \fn void QWidget::showEvent(QShowEvent *event)
8924 This event handler can be reimplemented in a subclass to receive
8925 widget show events which are passed in the \a event parameter.
8927 Non-spontaneous show events are sent to widgets immediately
8928 before they are shown. The spontaneous show events of windows are
8929 delivered afterwards.
8931 Note: A widget receives spontaneous show and hide events when its
8932 mapping status is changed by the window system, e.g. a spontaneous
8933 hide event when the user minimizes the window, and a spontaneous
8934 show event when the window is restored again. After receiving a
8935 spontaneous hide event, a widget is still considered visible in
8936 the sense of isVisible().
8938 \sa visible, event(), QShowEvent
8940 void QWidget::showEvent(QShowEvent *)
8945 \fn void QWidget::hideEvent(QHideEvent *event)
8947 This event handler can be reimplemented in a subclass to receive
8948 widget hide events. The event is passed in the \a event parameter.
8950 Hide events are sent to widgets immediately after they have been
8953 Note: A widget receives spontaneous show and hide events when its
8954 mapping status is changed by the window system, e.g. a spontaneous
8955 hide event when the user minimizes the window, and a spontaneous
8956 show event when the window is restored again. After receiving a
8957 spontaneous hide event, a widget is still considered visible in
8958 the sense of isVisible().
8960 \sa visible, event(), QHideEvent
8962 void QWidget::hideEvent(QHideEvent *)
8967 This special event handler can be reimplemented in a subclass to
8968 receive native platform events identified by \a eventType
8969 which are passed in the \a message parameter.
8971 In your reimplementation of this function, if you want to stop the
8972 event being handled by Qt, return true and set \a result.
8973 If you return false, this native event is passed back to Qt,
8974 which translates the event into a Qt event and sends it to the widget.
8976 \note Events are only delivered to this event handler if the widget is
8977 has a native Window handle.
8979 \note This function superseedes the event filter functions
8980 x11Event(), winEvent() and macEvent() of Qt 4.
8983 \header \i Platform \i Event Type Identifier \i Message Type \i Result Type
8984 \row \i Windows \i "windows_generic_MSG" \i MSG * \i LRESULT
8988 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
8990 Q_UNUSED(eventType);
8997 Ensures that the widget has been polished by QStyle (i.e., has a
8998 proper font and palette).
9000 QWidget calls this function after it has been fully constructed
9001 but before it is shown the very first time. You can call this
9002 function if you want to ensure that the widget is polished before
9003 doing an operation, e.g., the correct font size might be needed in
9004 the widget's sizeHint() reimplementation. Note that this function
9005 \e is called from the default implementation of sizeHint().
9007 Polishing is useful for final initialization that must happen after
9008 all constructors (from base classes as well as from subclasses)
9011 If you need to change some settings when a widget is polished,
9012 reimplement event() and handle the QEvent::Polish event type.
9014 \bold{Note:} The function is declared const so that it can be called from
9015 other const functions (e.g., sizeHint()).
9019 void QWidget::ensurePolished() const
9023 const QMetaObject *m = metaObject();
9024 if (m == d->polished)
9028 QEvent e(QEvent::Polish);
9029 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9031 // polish children after 'this'
9032 QList<QObject*> children = d->children;
9033 for (int i = 0; i < children.size(); ++i) {
9034 QObject *o = children.at(i);
9035 if(!o->isWidgetType())
9037 if (QWidget *w = qobject_cast<QWidget *>(o))
9038 w->ensurePolished();
9041 if (d->parent && d->sendChildEvents) {
9042 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9043 QCoreApplication::sendEvent(d->parent, &e);
9045 if (d->extra && d->extra->topextra && d->extra->topextra->window
9046 && d->extra->topextra->window->objectName().isEmpty()) {
9047 QString on = objectName();
9049 on = QString::fromUtf8(metaObject()->className());
9050 on += QStringLiteral("Class");
9052 on += QStringLiteral("Window");
9053 d->extra->topextra->window->setObjectName(on);
9058 Returns the mask currently set on a widget. If no mask is set the
9059 return value will be an empty region.
9061 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9063 QRegion QWidget::mask() const
9066 return d->extra ? d->extra->mask : QRegion();
9070 Returns the layout manager that is installed on this widget, or 0
9071 if no layout manager is installed.
9073 The layout manager sets the geometry of the widget's children
9074 that have been added to the layout.
9076 \sa setLayout(), sizePolicy(), {Layout Management}
9078 QLayout *QWidget::layout() const
9080 return d_func()->layout;
9085 \fn void QWidget::setLayout(QLayout *layout)
9087 Sets the layout manager for this widget to \a layout.
9089 If there already is a layout manager installed on this widget,
9090 QWidget won't let you install another. You must first delete the
9091 existing layout manager (returned by layout()) before you can
9092 call setLayout() with the new layout.
9094 If \a layout is the layout manger on a different widget, setLayout()
9095 will reparent the layout and make it the layout manager for this widget.
9099 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9101 An alternative to calling this function is to pass this widget to
9102 the layout's constructor.
9104 The QWidget will take ownership of \a layout.
9106 \sa layout(), {Layout Management}
9109 void QWidget::setLayout(QLayout *l)
9112 qWarning("QWidget::setLayout: Cannot set layout to 0");
9117 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9118 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9119 objectName().toLocal8Bit().data());
9123 QObject *oldParent = l->parent();
9124 if (oldParent && oldParent != this) {
9125 if (oldParent->isWidgetType()) {
9126 // Steal the layout off a widget parent. Takes effect when
9127 // morphing laid-out container widgets in Designer.
9128 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9129 oldParentWidget->takeLayout();
9131 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9132 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9133 objectName().toLocal8Bit().data());
9139 l->d_func()->topLevel = true;
9141 if (oldParent != this) {
9143 l->d_func()->reparentChildWidgets(this);
9147 if (isWindow() && d->maybeTopData())
9148 d->topData()->sizeAdjusted = false;
9152 \fn QLayout *QWidget::takeLayout()
9154 Remove the layout from the widget.
9158 QLayout *QWidget::takeLayout()
9161 QLayout *l = layout();
9170 \property QWidget::sizePolicy
9171 \brief the default layout behavior of the widget
9173 If there is a QLayout that manages this widget's children, the
9174 size policy specified by that layout is used. If there is no such
9175 QLayout, the result of this function is used.
9177 The default policy is Preferred/Preferred, which means that the
9178 widget can be freely resized, but prefers to be the size
9179 sizeHint() returns. Button-like widgets set the size policy to
9180 specify that they may stretch horizontally, but are fixed
9181 vertically. The same applies to lineedit controls (such as
9182 QLineEdit, QSpinBox or an editable QComboBox) and other
9183 horizontally orientated widgets (such as QProgressBar).
9184 QToolButton's are normally square, so they allow growth in both
9185 directions. Widgets that support different directions (such as
9186 QSlider, QScrollBar or QHeader) specify stretching in the
9187 respective direction only. Widgets that can provide scroll bars
9188 (usually subclasses of QScrollArea) tend to specify that they can
9189 use additional space, and that they can make do with less than
9192 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9194 QSizePolicy QWidget::sizePolicy() const
9197 return d->size_policy;
9200 void QWidget::setSizePolicy(QSizePolicy policy)
9203 setAttribute(Qt::WA_WState_OwnSizePolicy);
9204 if (policy == d->size_policy)
9206 d->size_policy = policy;
9208 #ifndef QT_NO_GRAPHICSVIEW
9209 if (QWExtra *extra = d->extra) {
9210 if (extra->proxyWidget)
9211 extra->proxyWidget->setSizePolicy(policy);
9217 if (isWindow() && d->maybeTopData())
9218 d->topData()->sizeAdjusted = false;
9222 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9225 Sets the size policy of the widget to \a horizontal and \a
9226 vertical, with standard stretch and no height-for-width.
9228 \sa QSizePolicy::QSizePolicy()
9232 Returns the preferred height for this widget, given the width \a w.
9234 If this widget has a layout, the default implementation returns
9235 the layout's preferred height. if there is no layout, the default
9236 implementation returns -1 indicating that the preferred height
9237 does not depend on the width.
9240 int QWidget::heightForWidth(int w) const
9242 if (layout() && layout()->hasHeightForWidth())
9243 return layout()->totalHeightForWidth(w);
9253 This is a bit hackish, but ideally we would have created a virtual function
9254 in the public API (however, too late...) so that subclasses could reimplement
9256 Instead we add a virtual function to QWidgetPrivate.
9257 ### Qt5: move to public class and make virtual
9259 bool QWidgetPrivate::hasHeightForWidth() const
9261 return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth();
9265 \fn QWidget *QWidget::childAt(int x, int y) const
9267 Returns the visible child widget at the position (\a{x}, \a{y})
9268 in the widget's coordinate system. If there is no visible child
9269 widget at the specified position, the function returns 0.
9275 Returns the visible child widget at point \a p in the widget's own
9279 QWidget *QWidget::childAt(const QPoint &p) const
9281 return d_func()->childAt_helper(p, false);
9284 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9286 if (children.isEmpty())
9291 // Unified tool bars on the Mac require special handling since they live outside
9292 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9293 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9294 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9296 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9299 if (!pointInsideRectAndMask(p))
9301 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9304 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9307 Q_UNUSED(includeFrame);
9309 for (int i = children.size() - 1; i >= 0; --i) {
9310 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9311 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9312 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9316 // Map the point 'p' from parent coordinates to child coordinates.
9317 QPoint childPoint = p;
9319 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9320 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9321 // QWidget::mapFromParent won't do the trick.
9322 if (includeFrame && qobject_cast<QToolBar *>(child))
9323 childPoint = qt_mac_nativeMapFromParent(child, p);
9326 childPoint -= child->data->crect.topLeft();
9328 // Check if the point hits the child.
9329 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9332 // Do the same for the child's descendants.
9333 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9336 // We have found our target; namely the child at position 'p'.
9342 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9346 widgetItem->invalidateSizeCache();
9348 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9349 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9350 if (parent->d_func()->layout)
9351 parent->d_func()->layout->invalidate();
9352 else if (parent->isVisible())
9353 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9359 Notifies the layout system that this widget has changed and may
9360 need to change geometry.
9362 Call this function if the sizeHint() or sizePolicy() have changed.
9364 For explicitly hidden widgets, updateGeometry() is a no-op. The
9365 layout system will be notified as soon as the widget is shown.
9368 void QWidget::updateGeometry()
9371 d->updateGeometry_helper(false);
9374 /*! \property QWidget::windowFlags
9376 Window flags are a combination of a type (e.g. Qt::Dialog) and
9377 zero or more hints to the window system (e.g.
9378 Qt::FramelessWindowHint).
9380 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9381 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9382 0) on the desktop. If the widget is a window and becomes a
9383 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9384 relative to its parent widget.
9386 \note This function calls setParent() when changing the flags for
9387 a window, causing the widget to be hidden. You must call show() to make
9388 the widget visible again..
9390 \sa windowType(), {Window Flags Example}
9392 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9394 if (data->window_flags == flags)
9399 if ((data->window_flags | flags) & Qt::Window) {
9400 // the old type was a window and/or the new type is a window
9401 QPoint oldPos = pos();
9402 bool visible = isVisible();
9403 setParent(parentWidget(), flags);
9405 // if both types are windows or neither of them are, we restore
9407 if (!((data->window_flags ^ flags) & Qt::Window)
9408 && (visible || testAttribute(Qt::WA_Moved))) {
9411 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9412 d->adjustQuitOnCloseAttribute();
9414 data->window_flags = flags;
9419 Sets the window flags for the widget to \a flags,
9420 \e without telling the window system.
9422 \warning Do not call this function unless you really know what
9425 \sa setWindowFlags()
9427 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9429 data->window_flags = flags;
9433 \fn Qt::WindowType QWidget::windowType() const
9435 Returns the window type of this widget. This is identical to
9436 windowFlags() & Qt::WindowType_Mask.
9442 Sets the parent of the widget to \a parent, and resets the window
9443 flags. The widget is moved to position (0, 0) in its new parent.
9445 If the new parent widget is in a different window, the
9446 reparented widget and its children are appended to the end of the
9447 \l{setFocusPolicy()}{tab chain} of the new parent
9448 widget, in the same internal order as before. If one of the moved
9449 widgets had keyboard focus, setParent() calls clearFocus() for that
9452 If the new parent widget is in the same window as the
9453 old parent, setting the parent doesn't change the tab order or
9456 If the "new" parent widget is the old parent widget, this function
9459 \note The widget becomes invisible as part of changing its parent,
9460 even if it was previously visible. You must call show() to make the
9461 widget visible again.
9463 \warning It is very unlikely that you will ever need this
9464 function. If you have a widget that changes its content
9465 dynamically, it is far easier to use \l QStackedWidget.
9467 \sa setWindowFlags()
9469 void QWidget::setParent(QWidget *parent)
9471 if (parent == parentWidget())
9473 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9479 This function also takes widget flags, \a f as an argument.
9482 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9485 d->inSetParent = true;
9486 bool resized = testAttribute(Qt::WA_Resized);
9487 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9488 QWidget *oldtlw = window();
9490 QWidget *desktopWidget = 0;
9491 if (parent && parent->windowType() == Qt::Desktop)
9492 desktopWidget = parent;
9493 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9495 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC)
9496 if (newParent && parent && !desktopWidget) {
9497 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9499 // On Mac, toolbars inside the unified title bar will never overlap with
9500 // siblings in the content view. So we skip enforce native siblings in that case
9501 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9504 parent->d_func()->enforceNativeChildren();
9505 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9506 setAttribute(Qt::WA_NativeWindow);
9511 if (!testAttribute(Qt::WA_WState_Hidden)) {
9513 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9516 QEvent e(QEvent::ParentAboutToChange);
9517 QApplication::sendEvent(this, &e);
9520 if (newParent && isAncestorOf(focusWidget()))
9521 focusWidget()->clearFocus();
9523 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9524 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9526 d->setParent_sys(parent, f);
9528 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9529 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9530 if (oldBsTracker && oldBsTracker != bsTracker)
9531 oldBsTracker->unregisterWidgetSubtree(this);
9536 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9538 oldBs->removeDirtyWidget(this);
9539 // Move the widget and all its static children from
9540 // the old backing store to the new one.
9541 oldBs->moveStaticWidgets(this);
9544 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9547 d->reparentFocusWidgets(oldtlw);
9548 setAttribute(Qt::WA_Resized, resized);
9549 if (!testAttribute(Qt::WA_StyleSheet)
9550 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9552 d->resolvePalette();
9554 d->resolveLayoutDirection();
9557 // Note: GL widgets under WGL or EGL will always need a ParentChange
9558 // event to handle recreation/rebinding of the GL context, hence the
9559 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9562 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9563 || (f & Qt::MSWindowsOwnDC)
9566 // propagate enabled updates enabled state to non-windows
9568 if (!testAttribute(Qt::WA_ForceDisabled))
9569 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9570 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9571 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9575 // send and post remaining QObject events
9576 if (parent && d->sendChildEvents) {
9577 QChildEvent e(QEvent::ChildAdded, this);
9578 QApplication::sendEvent(parent, &e);
9581 //### already hidden above ---> must probably do something smart on the mac
9583 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9584 // if(!qt_mac_is_macdrawer(q)) //special case
9585 // q->setAttribute(Qt::WA_WState_Hidden);
9587 // q->setAttribute(Qt::WA_WState_Hidden);
9590 if (parent && d->sendChildEvents && d->polished) {
9591 QChildEvent e(QEvent::ChildPolished, this);
9592 QCoreApplication::sendEvent(parent, &e);
9595 QEvent e(QEvent::ParentChange);
9596 QApplication::sendEvent(this, &e);
9600 if (isWindow() || parentWidget()->isVisible())
9601 setAttribute(Qt::WA_WState_Hidden, true);
9602 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9603 setAttribute(Qt::WA_WState_Hidden, false);
9606 d->updateIsOpaque();
9608 #ifndef QT_NO_GRAPHICSVIEW
9609 // Embed the widget into a proxy if the parent is embedded.
9610 // ### Doesn't handle reparenting out of an embedded widget.
9611 if (oldtlw->graphicsProxyWidget()) {
9612 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9613 ancestorProxy->d_func()->unembedSubWindow(this);
9615 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9616 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9617 ancestorProxy->d_func()->embedSubWindow(this);
9621 d->inSetParent = false;
9625 Scrolls the widget including its children \a dx pixels to the
9626 right and \a dy downward. Both \a dx and \a dy may be negative.
9628 After scrolling, the widgets will receive paint events for
9629 the areas that need to be repainted. For widgets that Qt knows to
9630 be opaque, this is only the newly exposed parts.
9631 For example, if an opaque widget is scrolled 8 pixels to the left,
9632 only an 8-pixel wide stripe at the right edge needs updating.
9634 Since widgets propagate the contents of their parents by default,
9635 you need to set the \l autoFillBackground property, or use
9636 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9639 For widgets that use contents propagation, a scroll will cause an
9640 update of the entire scroll area.
9642 \sa {Transparency and Double Buffering}
9645 void QWidget::scroll(int dx, int dy)
9647 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9649 if (dx == 0 && dy == 0)
9652 #ifndef QT_NO_GRAPHICSVIEW
9653 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9654 // Graphics View maintains its own dirty region as a list of rects;
9655 // until we can connect item updates directly to the view, we must
9656 // separately add a translated dirty region.
9657 if (!d->dirty.isEmpty()) {
9658 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9659 proxy->update(rect);
9661 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9665 d->setDirtyOpaqueRegion();
9666 d->scroll_sys(dx, dy);
9672 This version only scrolls \a r and does not move the children of
9675 If \a r is empty or invalid, the result is undefined.
9679 void QWidget::scroll(int dx, int dy, const QRect &r)
9682 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9684 if (dx == 0 && dy == 0)
9687 #ifndef QT_NO_GRAPHICSVIEW
9688 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9689 // Graphics View maintains its own dirty region as a list of rects;
9690 // until we can connect item updates directly to the view, we must
9691 // separately add a translated dirty region.
9692 if (!d->dirty.isEmpty()) {
9693 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9694 proxy->update(rect);
9696 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9700 d->scroll_sys(dx, dy, r);
9704 Repaints the widget directly by calling paintEvent() immediately,
9705 unless updates are disabled or the widget is hidden.
9707 We suggest only using repaint() if you need an immediate repaint,
9708 for example during animation. In almost all circumstances update()
9709 is better, as it permits Qt to optimize for speed and minimize
9712 \warning If you call repaint() in a function which may itself be
9713 called from paintEvent(), you may get infinite recursion. The
9714 update() function never causes recursion.
9716 \sa update(), paintEvent(), setUpdatesEnabled()
9719 void QWidget::repaint()
9726 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9729 If \a w is negative, it is replaced with \c{width() - x}, and if
9730 \a h is negative, it is replaced width \c{height() - y}.
9732 void QWidget::repaint(int x, int y, int w, int h)
9734 if (x > data->crect.width() || y > data->crect.height())
9738 w = data->crect.width() - x;
9740 h = data->crect.height() - y;
9742 repaint(QRect(x, y, w, h));
9747 This version repaints a rectangle \a rect inside the widget.
9749 void QWidget::repaint(const QRect &rect)
9753 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9758 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9761 if (hasBackingStoreSupport()) {
9763 if (qt_widget_private(this)->isInUnifiedToolbar) {
9764 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9768 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9769 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9770 tlwExtra->inRepaint = true;
9771 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9772 tlwExtra->inRepaint = false;
9775 d->repaint_sys(rect);
9782 This version repaints a region \a rgn inside the widget.
9784 void QWidget::repaint(const QRegion &rgn)
9788 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9793 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9796 if (hasBackingStoreSupport()) {
9798 if (qt_widget_private(this)->isInUnifiedToolbar) {
9799 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9803 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9804 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9805 tlwExtra->inRepaint = true;
9806 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9807 tlwExtra->inRepaint = false;
9810 d->repaint_sys(rgn);
9815 Updates the widget unless updates are disabled or the widget is
9818 This function does not cause an immediate repaint; instead it
9819 schedules a paint event for processing when Qt returns to the main
9820 event loop. This permits Qt to optimize for more speed and less
9821 flicker than a call to repaint() does.
9823 Calling update() several times normally results in just one
9826 Qt normally erases the widget's area before the paintEvent() call.
9827 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9828 responsible for painting all its pixels with an opaque color.
9830 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9832 void QWidget::update()
9837 /*! \fn void QWidget::update(int x, int y, int w, int h)
9840 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9847 This version updates a rectangle \a rect inside the widget.
9849 void QWidget::update(const QRect &rect)
9851 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9854 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9855 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9859 if (hasBackingStoreSupport()) {
9861 if (qt_widget_private(this)->isInUnifiedToolbar) {
9862 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9866 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9867 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9868 tlwExtra->backingStoreTracker->markDirty(rect, this);
9870 d_func()->repaint_sys(rect);
9877 This version repaints a region \a rgn inside the widget.
9879 void QWidget::update(const QRegion &rgn)
9881 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9884 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9885 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9889 if (hasBackingStoreSupport()) {
9891 if (qt_widget_private(this)->isInUnifiedToolbar) {
9892 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9896 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9897 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9898 tlwExtra->backingStoreTracker->markDirty(rgn, this);
9900 d_func()->repaint_sys(rgn);
9908 This just sets the corresponding attribute bit to 1 or 0
9910 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9913 if (attribute < int(8*sizeof(uint))) {
9915 data->widget_attributes |= (1<<attribute);
9917 data->widget_attributes &= ~(1<<attribute);
9919 const int x = attribute - 8*sizeof(uint);
9920 const int int_off = x / (8*sizeof(uint));
9922 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9924 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9929 Sets the attribute \a attribute on this widget if \a on is true;
9930 otherwise clears the attribute.
9934 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9936 if (testAttribute(attribute) == on)
9940 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9941 "QWidget::setAttribute(WidgetAttribute, bool)",
9942 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9944 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
9945 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
9946 // see qwidget_win.cpp, ::paintEngine for details
9948 if (d->noPaintOnScreen)
9953 setAttribute_internal(attribute, on, data, d);
9955 switch (attribute) {
9957 #ifndef QT_NO_DRAGANDDROP
9958 case Qt::WA_AcceptDrops: {
9959 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9960 setAttribute(Qt::WA_DropSiteRegistered, true);
9961 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9962 setAttribute(Qt::WA_DropSiteRegistered, false);
9963 QEvent e(QEvent::AcceptDropsChange);
9964 QApplication::sendEvent(this, &e);
9967 case Qt::WA_DropSiteRegistered: {
9968 d->registerDropSite(on);
9969 for (int i = 0; i < d->children.size(); ++i) {
9970 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9971 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9972 w->setAttribute(Qt::WA_DropSiteRegistered, on);
9978 case Qt::WA_NoChildEventsForParent:
9979 d->sendChildEvents = !on;
9981 case Qt::WA_NoChildEventsFromChildren:
9982 d->receiveChildEvents = !on;
9984 case Qt::WA_MacBrushedMetal:
9986 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
9987 // fall through since changing the metal attribute affects the opaque size grip.
9988 case Qt::WA_MacOpaqueSizeGrip:
9989 d->macUpdateOpaqueSizeGrip();
9991 case Qt::WA_MacShowFocusRect:
9998 qt_mac_update_mouseTracking(this);
10001 case Qt::WA_MacAlwaysShowToolWindow:
10003 d->macUpdateHideOnSuspend();
10006 case Qt::WA_MacNormalSize:
10007 case Qt::WA_MacSmallSize:
10008 case Qt::WA_MacMiniSize:
10011 // We can only have one of these set at a time
10012 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10013 Qt::WA_MacMiniSize };
10014 for (int i = 0; i < 3; ++i) {
10015 if (MacSizes[i] != attribute)
10016 setAttribute_internal(MacSizes[i], false, data, d);
10018 d->macUpdateSizeAttribute();
10022 case Qt::WA_ShowModal:
10025 QApplicationPrivate::leaveModal(this);
10026 // reset modality type to Modeless when clearing WA_ShowModal
10027 data->window_modality = Qt::NonModal;
10028 } else if (data->window_modality == Qt::NonModal) {
10029 // determine the modality type if it hasn't been set prior
10030 // to setting WA_ShowModal. set the default to WindowModal
10031 // if we are the child of a group leader; otherwise use
10032 // ApplicationModal.
10033 QWidget *w = parentWidget();
10036 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10037 w = w->parentWidget();
10041 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10043 : Qt::ApplicationModal;
10044 // Some window managers does not allow us to enter modal after the
10045 // window is showing. Therefore, to be consistent, we cannot call
10046 // QApplicationPrivate::enterModal(this) here. The window must be
10047 // hidden before changing modality.
10049 if (testAttribute(Qt::WA_WState_Created)) {
10050 // don't call setModal_sys() before create_sys()
10054 case Qt::WA_MouseTracking: {
10055 QEvent e(QEvent::MouseTrackingChange);
10056 QApplication::sendEvent(this, &e);
10058 case Qt::WA_NativeWindow: {
10059 d->createTLExtra();
10061 QWidget *focusWidget = d->effectiveFocusWidget();
10062 if (on && !internalWinId() && hasFocus()
10063 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10064 qApp->inputPanel()->reset();
10065 qApp->inputPanel()->update(Qt::ImEnabled);
10067 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10069 // On Mac, toolbars inside the unified title bar will never overlap with
10070 // siblings in the content view. So we skip enforce native siblings in that case
10071 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10074 parentWidget()->d_func()->enforceNativeChildren();
10075 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10077 if (isEnabled() && focusWidget->isEnabled()
10078 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10079 qApp->inputPanel()->update(Qt::ImEnabled);
10084 case Qt::WA_PaintOnScreen:
10085 d->updateIsOpaque();
10086 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10087 // Recreate the widget if it's already created as an alien widget and
10088 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10089 // So must their children.
10091 setAttribute(Qt::WA_NativeWindow);
10092 d->enforceNativeChildren();
10096 case Qt::WA_OpaquePaintEvent:
10097 d->updateIsOpaque();
10099 case Qt::WA_NoSystemBackground:
10100 d->updateIsOpaque();
10102 case Qt::WA_UpdatesDisabled:
10103 d->updateSystemBackground();
10105 case Qt::WA_TransparentForMouseEvents:
10107 d->macUpdateIgnoreMouseEvents();
10110 case Qt::WA_InputMethodEnabled: {
10112 if (qApp->focusObject() == this) {
10114 qApp->inputPanel()->reset();
10115 qApp->inputPanel()->update(Qt::ImEnabled);
10120 case Qt::WA_WindowPropagation:
10121 d->resolvePalette();
10123 d->resolveLocale();
10126 case Qt::WA_NoX11EventCompression:
10129 d->extra->compress_events = on;
10131 case Qt::WA_X11OpenGLOverlay:
10132 d->updateIsOpaque();
10134 case Qt::WA_X11DoNotAcceptFocus:
10135 if (testAttribute(Qt::WA_WState_Created))
10136 d->updateX11AcceptFocus();
10139 case Qt::WA_DontShowOnScreen: {
10140 if (on && isVisible()) {
10141 // Make sure we keep the current state and only hide the widget
10142 // from the desktop. show_sys will only update platform specific
10143 // attributes at this point.
10151 case Qt::WA_X11NetWmWindowTypeDesktop:
10152 case Qt::WA_X11NetWmWindowTypeDock:
10153 case Qt::WA_X11NetWmWindowTypeToolBar:
10154 case Qt::WA_X11NetWmWindowTypeMenu:
10155 case Qt::WA_X11NetWmWindowTypeUtility:
10156 case Qt::WA_X11NetWmWindowTypeSplash:
10157 case Qt::WA_X11NetWmWindowTypeDialog:
10158 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10159 case Qt::WA_X11NetWmWindowTypePopupMenu:
10160 case Qt::WA_X11NetWmWindowTypeToolTip:
10161 case Qt::WA_X11NetWmWindowTypeNotification:
10162 case Qt::WA_X11NetWmWindowTypeCombo:
10163 case Qt::WA_X11NetWmWindowTypeDND:
10164 if (testAttribute(Qt::WA_WState_Created))
10165 d->setNetWmWindowTypes();
10169 case Qt::WA_StaticContents:
10170 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10172 bs->addStaticWidget(this);
10174 bs->removeStaticWidget(this);
10177 case Qt::WA_TranslucentBackground:
10179 setAttribute(Qt::WA_NoSystemBackground);
10180 d->updateIsTranslucent();
10184 case Qt::WA_AcceptTouchEvents:
10185 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10187 d->registerTouchWindow();
10195 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10197 Returns true if attribute \a attribute is set on this widget;
10198 otherwise returns false.
10202 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10204 Q_D(const QWidget);
10205 const int x = attribute - 8*sizeof(uint);
10206 const int int_off = x / (8*sizeof(uint));
10207 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10211 \property QWidget::windowOpacity
10213 \brief The level of opacity for the window.
10215 The valid range of opacity is from 1.0 (completely opaque) to
10216 0.0 (completely transparent).
10218 By default the value of this property is 1.0.
10220 This feature is available on Embedded Linux, Mac OS X, Windows,
10221 and X11 platforms that support the Composite extension.
10223 This feature is not available on Windows CE.
10225 Note that under X11 you need to have a composite manager running,
10226 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10227 supported by the window manager you are using.
10229 \warning Changing this property from opaque to transparent might issue a
10230 paint event that needs to be processed before the window is displayed
10231 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10232 that semi-transparent windows update and resize significantly slower than
10237 qreal QWidget::windowOpacity() const
10239 Q_D(const QWidget);
10240 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10243 void QWidget::setWindowOpacity(qreal opacity)
10249 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10250 QTLWExtra *extra = d->topData();
10251 extra->opacity = uint(opacity * 255);
10252 setAttribute(Qt::WA_WState_WindowOpacitySet);
10254 if (!testAttribute(Qt::WA_WState_Created))
10257 #ifndef QT_NO_GRAPHICSVIEW
10258 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10259 // Avoid invalidating the cache if set.
10260 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10262 else if (QGraphicsScene *scene = proxy->scene())
10263 scene->update(proxy->sceneBoundingRect());
10268 d->setWindowOpacity_sys(opacity);
10272 \property QWidget::windowModified
10273 \brief whether the document shown in the window has unsaved changes
10275 A modified window is a window whose content has changed but has
10276 not been saved to disk. This flag will have different effects
10277 varied by the platform. On Mac OS X the close button will have a
10278 modified look; on other platforms, the window title will have an
10281 The window title must contain a "[*]" placeholder, which
10282 indicates where the '*' should appear. Normally, it should appear
10283 right after the file name (e.g., "document1.txt[*] - Text
10284 Editor"). If the window isn't modified, the placeholder is simply
10287 Note that if a widget is set as modified, all its ancestors will
10288 also be set as modified. However, if you call \c
10289 {setWindowModified(false)} on a widget, this will not propagate to
10290 its parent because other children of the parent might have been
10293 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10295 bool QWidget::isWindowModified() const
10297 return testAttribute(Qt::WA_WindowModified);
10300 void QWidget::setWindowModified(bool mod)
10303 setAttribute(Qt::WA_WindowModified, mod);
10306 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10307 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10309 d->setWindowTitle_helper(windowTitle());
10310 d->setWindowIconText_helper(windowIconText());
10312 d->setWindowModified_sys(mod);
10315 QEvent e(QEvent::ModifiedChange);
10316 QApplication::sendEvent(this, &e);
10319 #ifndef QT_NO_TOOLTIP
10321 \property QWidget::toolTip
10323 \brief the widget's tooltip
10325 Note that by default tooltips are only shown for widgets that are
10326 children of the active window. You can change this behavior by
10327 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10328 not on the widget with the tooltip.
10330 If you want to control a tooltip's behavior, you can intercept the
10331 event() function and catch the QEvent::ToolTip event (e.g., if you
10332 want to customize the area for which the tooltip should be shown).
10334 By default, this property contains an empty string.
10336 \sa QToolTip statusTip whatsThis
10338 void QWidget::setToolTip(const QString &s)
10343 QEvent event(QEvent::ToolTipChange);
10344 QApplication::sendEvent(this, &event);
10347 QString QWidget::toolTip() const
10349 Q_D(const QWidget);
10352 #endif // QT_NO_TOOLTIP
10355 #ifndef QT_NO_STATUSTIP
10357 \property QWidget::statusTip
10358 \brief the widget's status tip
10360 By default, this property contains an empty string.
10362 \sa toolTip whatsThis
10364 void QWidget::setStatusTip(const QString &s)
10370 QString QWidget::statusTip() const
10372 Q_D(const QWidget);
10373 return d->statusTip;
10375 #endif // QT_NO_STATUSTIP
10377 #ifndef QT_NO_WHATSTHIS
10379 \property QWidget::whatsThis
10381 \brief the widget's What's This help text.
10383 By default, this property contains an empty string.
10385 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10387 void QWidget::setWhatsThis(const QString &s)
10393 QString QWidget::whatsThis() const
10395 Q_D(const QWidget);
10396 return d->whatsThis;
10398 #endif // QT_NO_WHATSTHIS
10400 #ifndef QT_NO_ACCESSIBILITY
10402 \property QWidget::accessibleName
10404 \brief the widget's name as seen by assistive technologies
10406 This property is used by accessible clients to identify, find, or announce
10407 the widget for accessible clients.
10409 By default, this property contains an empty string.
10411 \sa QAccessibleInterface::text()
10413 void QWidget::setAccessibleName(const QString &name)
10416 d->accessibleName = name;
10417 QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
10420 QString QWidget::accessibleName() const
10422 Q_D(const QWidget);
10423 return d->accessibleName;
10427 \property QWidget::accessibleDescription
10429 \brief the widget's description as seen by assistive technologies
10431 By default, this property contains an empty string.
10433 \sa QAccessibleInterface::text()
10435 void QWidget::setAccessibleDescription(const QString &description)
10438 d->accessibleDescription = description;
10439 QAccessible::updateAccessibility(this, 0, QAccessible::DescriptionChanged);
10442 QString QWidget::accessibleDescription() const
10444 Q_D(const QWidget);
10445 return d->accessibleDescription;
10447 #endif // QT_NO_ACCESSIBILITY
10449 #ifndef QT_NO_SHORTCUT
10451 Adds a shortcut to Qt's shortcut system that watches for the given
10452 \a key sequence in the given \a context. If the \a context is
10453 Qt::ApplicationShortcut, the shortcut applies to the application as a
10454 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10455 or to the window itself, Qt::WindowShortcut.
10457 If the same \a key sequence has been grabbed by several widgets,
10458 when the \a key sequence occurs a QEvent::Shortcut event is sent
10459 to all the widgets to which it applies in a non-deterministic
10460 order, but with the ``ambiguous'' flag set to true.
10462 \warning You should not normally need to use this function;
10463 instead create \l{QAction}s with the shortcut key sequences you
10464 require (if you also want equivalent menu options and toolbar
10465 buttons), or create \l{QShortcut}s if you just need key sequences.
10466 Both QAction and QShortcut handle all the event filtering for you,
10467 and provide signals which are triggered when the user triggers the
10468 key sequence, so are much easier to use than this low-level
10471 \sa releaseShortcut() setShortcutEnabled()
10473 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10478 setAttribute(Qt::WA_GrabbedShortcut);
10479 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10483 Removes the shortcut with the given \a id from Qt's shortcut
10484 system. The widget will no longer receive QEvent::Shortcut events
10485 for the shortcut's key sequence (unless it has other shortcuts
10486 with the same key sequence).
10488 \warning You should not normally need to use this function since
10489 Qt's shortcut system removes shortcuts automatically when their
10490 parent widget is destroyed. It is best to use QAction or
10491 QShortcut to handle shortcuts, since they are easier to use than
10492 this low-level function. Note also that this is an expensive
10495 \sa grabShortcut() setShortcutEnabled()
10497 void QWidget::releaseShortcut(int id)
10501 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10505 If \a enable is true, the shortcut with the given \a id is
10506 enabled; otherwise the shortcut is disabled.
10508 \warning You should not normally need to use this function since
10509 Qt's shortcut system enables/disables shortcuts automatically as
10510 widgets become hidden/visible and gain or lose focus. It is best
10511 to use QAction or QShortcut to handle shortcuts, since they are
10512 easier to use than this low-level function.
10514 \sa grabShortcut() releaseShortcut()
10516 void QWidget::setShortcutEnabled(int id, bool enable)
10520 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10526 If \a enable is true, auto repeat of the shortcut with the
10527 given \a id is enabled; otherwise it is disabled.
10529 \sa grabShortcut() releaseShortcut()
10531 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10535 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10537 #endif // QT_NO_SHORTCUT
10540 Updates the widget's micro focus.
10544 void QWidget::updateMicroFocus()
10546 // updating everything since this is currently called for any kind of state change
10547 qApp->inputPanel()->update(Qt::ImQueryAll);
10549 #ifndef QT_NO_ACCESSIBILITY
10551 // ##### is this correct
10552 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
10558 Raises this widget to the top of the parent widget's stack.
10560 After this call the widget will be visually in front of any
10561 overlapping sibling widgets.
10563 \note When using activateWindow(), you can call this function to
10564 ensure that the window is stacked on top.
10566 \sa lower(), stackUnder()
10569 void QWidget::raise()
10573 QWidget *p = parentWidget();
10574 const int parentChildCount = p->d_func()->children.size();
10575 if (parentChildCount < 2)
10577 const int from = p->d_func()->children.indexOf(this);
10578 Q_ASSERT(from >= 0);
10579 // Do nothing if the widget is already in correct stacking order _and_ created.
10580 if (from != parentChildCount -1)
10581 p->d_func()->children.move(from, parentChildCount - 1);
10582 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10584 else if (from == parentChildCount - 1)
10587 QRegion region(rect());
10588 d->subtractOpaqueSiblings(region);
10589 d->invalidateBuffer(region);
10591 if (testAttribute(Qt::WA_WState_Created))
10594 QEvent e(QEvent::ZOrderChange);
10595 QApplication::sendEvent(this, &e);
10599 Lowers the widget to the bottom of the parent widget's stack.
10601 After this call the widget will be visually behind (and therefore
10602 obscured by) any overlapping sibling widgets.
10604 \sa raise(), stackUnder()
10607 void QWidget::lower()
10611 QWidget *p = parentWidget();
10612 const int parentChildCount = p->d_func()->children.size();
10613 if (parentChildCount < 2)
10615 const int from = p->d_func()->children.indexOf(this);
10616 Q_ASSERT(from >= 0);
10617 // Do nothing if the widget is already in correct stacking order _and_ created.
10619 p->d_func()->children.move(from, 0);
10620 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10622 else if (from == 0)
10625 if (testAttribute(Qt::WA_WState_Created))
10628 QEvent e(QEvent::ZOrderChange);
10629 QApplication::sendEvent(this, &e);
10634 Places the widget under \a w in the parent widget's stack.
10636 To make this work, the widget itself and \a w must be siblings.
10638 \sa raise(), lower()
10640 void QWidget::stackUnder(QWidget* w)
10643 QWidget *p = parentWidget();
10644 if (!w || isWindow() || p != w->parentWidget() || this == w)
10647 int from = p->d_func()->children.indexOf(this);
10648 int to = p->d_func()->children.indexOf(w);
10649 Q_ASSERT(from >= 0);
10653 // Do nothing if the widget is already in correct stacking order _and_ created.
10655 p->d_func()->children.move(from, to);
10656 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10658 else if (from == to)
10661 if (testAttribute(Qt::WA_WState_Created))
10662 d->stackUnder_sys(w);
10664 QEvent e(QEvent::ZOrderChange);
10665 QApplication::sendEvent(this, &e);
10670 \fn bool QWidget::isTopLevel() const
10673 Use isWindow() instead.
10677 \fn bool QWidget::isRightToLeft() const
10682 \fn bool QWidget::isLeftToRight() const
10687 \macro QWIDGETSIZE_MAX
10690 Defines the maximum size for a QWidget object.
10692 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10693 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10695 \sa QWidget::setMaximumSize()
10699 \fn QWidget::setupUi(QWidget *widget)
10701 Sets up the user interface for the specified \a widget.
10703 \note This function is available with widgets that derive from user
10704 interface descriptions created using \l{uic}.
10706 \sa {Using a Designer UI File in Your Application}
10709 QRect QWidgetPrivate::frameStrut() const
10711 Q_Q(const QWidget);
10712 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10713 // x2 = x1 + w - 1, so w/h = 1
10714 return QRect(0, 0, 1, 1);
10717 if (data.fstrut_dirty
10719 // ### Fix properly for 4.3
10722 && q->testAttribute(Qt::WA_WState_Created))
10723 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10725 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10728 #ifdef QT_KEYPAD_NAVIGATION
10732 Changes the focus from the current focusWidget to a widget in
10735 Returns true, if there was a widget in that direction
10737 bool QWidgetPrivate::navigateToDirection(Direction direction)
10739 QWidget *targetWidget = widgetInNavigationDirection(direction);
10741 targetWidget->setFocus();
10742 return (targetWidget != 0);
10748 Searches for a widget that is positioned in the \a direction, starting
10749 from the current focusWidget.
10751 Returns the pointer to a found widget or 0, if there was no widget in
10754 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10756 const QWidget *sourceWidget = QApplication::focusWidget();
10759 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10760 const int sourceX =
10761 (direction == DirectionNorth || direction == DirectionSouth) ?
10762 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10763 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10764 const int sourceY =
10765 (direction == DirectionEast || direction == DirectionWest) ?
10766 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10767 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10768 const QPoint sourcePoint(sourceX, sourceY);
10769 const QPoint sourceCenter = sourceRect.center();
10770 const QWidget *sourceWindow = sourceWidget->window();
10772 QWidget *targetWidget = 0;
10773 int shortestDistance = INT_MAX;
10774 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10776 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10778 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10779 // but the owner of the proxy cannot.
10780 // Additionally, empty widgets should be ignored.
10781 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10784 // Only navigate to a target widget that...
10785 if ( targetCandidate != sourceWidget
10786 // ...takes the focus,
10787 && targetCandidate->focusPolicy() & Qt::TabFocus
10788 // ...is above if DirectionNorth,
10789 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10790 // ...is on the right if DirectionEast,
10791 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
10792 // ...is below if DirectionSouth,
10793 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
10794 // ...is on the left if DirectionWest,
10795 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
10797 && targetCandidate->isEnabled()
10799 && targetCandidate->isVisible()
10800 // ...is in the same window,
10801 && targetCandidate->window() == sourceWindow) {
10802 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10803 if (targetCandidateDistance < shortestDistance) {
10804 shortestDistance = targetCandidateDistance;
10805 targetWidget = targetCandidate;
10809 return targetWidget;
10815 Tells us if it there is currently a reachable widget by keypad navigation in
10816 a certain \a orientation.
10817 If no navigation is possible, occurring key events in that \a orientation may
10818 be used to interact with the value in the focused widget, even though it
10819 currently has not the editFocus.
10821 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10823 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10825 return orientation == Qt::Horizontal?
10826 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10827 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10828 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10829 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10834 Checks, if the \a widget is inside a QTabWidget. If is is inside
10835 one, left/right key events will be used to switch between tabs in keypad
10836 navigation. If there is no QTabWidget, the horizontal key events can be used
10838 interact with the value in the focused widget, even though it currently has
10841 \sa QWidget::hasEditFocus()
10843 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10845 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10846 if (qobject_cast<const QTabWidget*>(tabWidget))
10856 Sets the backing store to be the \a store specified.
10857 The QWidget will take ownership of the \a store.
10859 void QWidget::setBackingStore(QBackingStore *store)
10861 // ### createWinId() ??
10868 QTLWExtra *topData = d->topData();
10869 if (topData->backingStore == store)
10872 QBackingStore *oldStore = topData->backingStore;
10873 delete topData->backingStore;
10874 topData->backingStore = store;
10876 QWidgetBackingStore *bs = d->maybeBackingStore();
10880 if (isTopLevel()) {
10881 if (bs->store != oldStore && bs->store != store)
10890 Returns the QBackingStore this widget will be drawn into.
10892 QBackingStore *QWidget::backingStore() const
10894 Q_D(const QWidget);
10895 QTLWExtra *extra = d->maybeTopData();
10896 if (extra && extra->backingStore)
10897 return extra->backingStore;
10899 QWidgetBackingStore *bs = d->maybeBackingStore();
10901 return bs ? bs->store : 0;
10904 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10907 *left = (int)leftLayoutItemMargin;
10909 *top = (int)topLayoutItemMargin;
10911 *right = (int)rightLayoutItemMargin;
10913 *bottom = (int)bottomLayoutItemMargin;
10916 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10918 if (leftLayoutItemMargin == left
10919 && topLayoutItemMargin == top
10920 && rightLayoutItemMargin == right
10921 && bottomLayoutItemMargin == bottom)
10925 leftLayoutItemMargin = (signed char)left;
10926 topLayoutItemMargin = (signed char)top;
10927 rightLayoutItemMargin = (signed char)right;
10928 bottomLayoutItemMargin = (signed char)bottom;
10929 q->updateGeometry();
10932 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10935 QStyleOption myOpt;
10938 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
10942 QRect liRect = q->style()->subElementRect(element, opt, q);
10943 if (liRect.isValid()) {
10944 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10945 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10946 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10947 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10949 leftLayoutItemMargin = 0;
10950 topLayoutItemMargin = 0;
10951 rightLayoutItemMargin = 0;
10952 bottomLayoutItemMargin = 0;
10955 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10956 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10960 if (!q->parentWidget()) {
10961 Qt::WindowType type = q->windowType();
10962 if (type == Qt::Widget || type == Qt::SubWindow)
10964 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10965 q->setAttribute(Qt::WA_QuitOnClose, false);
10971 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10973 return widget->data;
10976 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10978 return widget->d_func();
10982 #ifndef QT_NO_GRAPHICSVIEW
10986 Returns the proxy widget for the corresponding embedded widget in a graphics
10987 view; otherwise returns 0.
10989 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
10990 QGraphicsScene::addWidget()
10992 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
10994 Q_D(const QWidget);
10996 return d->extra->proxyWidget;
11004 \typedef QWidgetList
11007 Synonym for QList<QWidget *>.
11010 #ifndef QT_NO_GESTURES
11012 Subscribes the widget to a given \a gesture with specific \a flags.
11014 \sa ungrabGesture(), QGestureEvent
11017 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11020 d->gestureContext.insert(gesture, flags);
11021 (void)QGestureManager::instance(); // create a gesture manager
11025 Unsubscribes the widget from a given \a gesture type
11027 \sa grabGesture(), QGestureEvent
11030 void QWidget::ungrabGesture(Qt::GestureType gesture)
11033 if (d->gestureContext.remove(gesture)) {
11034 if (QGestureManager *manager = QGestureManager::instance())
11035 manager->cleanupCachedGestures(this, gesture);
11038 #endif // QT_NO_GESTURES
11044 Platform dependent window identifier.
11048 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11050 Frees up window system resources. Destroys the widget window if \a
11051 destroyWindow is true.
11053 destroy() calls itself recursively for all the child widgets,
11054 passing \a destroySubWindows for the \a destroyWindow parameter.
11055 To have more control over destruction of subwidgets, destroy
11056 subwidgets selectively first.
11058 This function is usually called from the QWidget destructor.
11062 \fn QPaintEngine *QWidget::paintEngine() const
11064 Returns the widget's paint engine.
11066 Note that this function should not be called explicitly by the
11067 user, since it's meant for reimplementation purposes only. The
11068 function is called by Qt internally, and the default
11069 implementation may not always return a valid pointer.
11073 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11075 Translates the widget coordinate \a pos to global screen
11076 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11077 the global coordinates of the top-left pixel of the widget.
11079 \sa mapFromGlobal() mapTo() mapToParent()
11083 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11085 Translates the global screen coordinate \a pos to widget
11088 \sa mapToGlobal() mapFrom() mapFromParent()
11092 \fn void QWidget::grabMouse()
11094 Grabs the mouse input.
11096 This widget receives all mouse events until releaseMouse() is
11097 called; other widgets get no mouse events at all. Keyboard
11098 events are not affected. Use grabKeyboard() if you want to grab
11101 \warning Bugs in mouse-grabbing applications very often lock the
11102 terminal. Use this function with extreme caution, and consider
11103 using the \c -nograb command line option while debugging.
11105 It is almost never necessary to grab the mouse when using Qt, as
11106 Qt grabs and releases it sensibly. In particular, Qt grabs the
11107 mouse when a mouse button is pressed and keeps it until the last
11108 button is released.
11110 \note Only visible widgets can grab mouse input. If isVisible()
11111 returns false for a widget, that widget cannot call grabMouse().
11113 \note \bold{(Mac OS X developers)} For \e Cocoa, calling
11114 grabMouse() on a widget only works when the mouse is inside the
11115 frame of that widget. For \e Carbon, it works outside the widget's
11116 frame as well, like for Windows and X11.
11118 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11122 \fn void QWidget::grabMouse(const QCursor &cursor)
11123 \overload grabMouse()
11125 Grabs the mouse input and changes the cursor shape.
11127 The cursor will assume shape \a cursor (for as long as the mouse
11128 focus is grabbed) and this widget will be the only one to receive
11129 mouse events until releaseMouse() is called().
11131 \warning Grabbing the mouse might lock the terminal.
11133 \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse().
11135 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11139 \fn void QWidget::releaseMouse()
11141 Releases the mouse grab.
11143 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11147 \fn void QWidget::grabKeyboard()
11149 Grabs the keyboard input.
11151 This widget receives all keyboard events until releaseKeyboard()
11152 is called; other widgets get no keyboard events at all. Mouse
11153 events are not affected. Use grabMouse() if you want to grab that.
11155 The focus widget is not affected, except that it doesn't receive
11156 any keyboard events. setFocus() moves the focus as usual, but the
11157 new focus widget receives keyboard events only after
11158 releaseKeyboard() is called.
11160 If a different widget is currently grabbing keyboard input, that
11161 widget's grab is released first.
11163 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11167 \fn void QWidget::releaseKeyboard()
11169 Releases the keyboard grab.
11171 \sa grabKeyboard(), grabMouse(), releaseMouse()
11175 \fn QWidget *QWidget::mouseGrabber()
11177 Returns the widget that is currently grabbing the mouse input.
11179 If no widget in this application is currently grabbing the mouse,
11182 \sa grabMouse(), keyboardGrabber()
11186 \fn QWidget *QWidget::keyboardGrabber()
11188 Returns the widget that is currently grabbing the keyboard input.
11190 If no widget in this application is currently grabbing the
11191 keyboard, 0 is returned.
11193 \sa grabMouse(), mouseGrabber()
11197 \fn void QWidget::activateWindow()
11199 Sets the top-level widget containing this widget to be the active
11202 An active window is a visible top-level window that has the
11203 keyboard input focus.
11205 This function performs the same operation as clicking the mouse on
11206 the title bar of a top-level window. On X11, the result depends on
11207 the Window Manager. If you want to ensure that the window is
11208 stacked on top as well you should also call raise(). Note that the
11209 window must be visible, otherwise activateWindow() has no effect.
11211 On Windows, if you are calling this when the application is not
11212 currently the active one then it will not make it the active
11213 window. It will change the color of the taskbar entry to indicate
11214 that the window has changed in some way. This is because Microsoft
11215 does not allow an application to interrupt what the user is currently
11216 doing in another application.
11218 \sa isActiveWindow(), window(), show()
11222 \fn int QWidget::metric(PaintDeviceMetric m) const
11224 Internal implementation of the virtual QPaintDevice::metric()
11227 \a m is the metric to get.
11230 void QWidget::init(QPainter *painter) const
11232 const QPalette &pal = palette();
11233 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11234 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11235 QFont f(font(), const_cast<QWidget *>(this));
11236 painter->d_func()->state->deviceFont = f;
11237 painter->d_func()->state->font = f;
11240 QPaintDevice *QWidget::redirected(QPoint *offset) const
11242 return d_func()->redirected(offset);
11245 QPainter *QWidget::sharedPainter() const
11247 // Someone sent a paint event directly to the widget
11248 if (!d_func()->redirectDev)
11251 QPainter *sp = d_func()->sharedPainter();
11252 if (!sp || !sp->isActive())
11255 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11262 \fn void QWidget::setMask(const QRegion ®ion)
11265 Causes only the parts of the widget which overlap \a region to be
11266 visible. If the region includes pixels outside the rect() of the
11267 widget, window system controls in that area may or may not be
11268 visible, depending on the platform.
11270 Note that this effect can be slow if the region is particularly
11275 void QWidget::setMask(const QRegion &newMask)
11280 if (newMask == d->extra->mask)
11283 #ifndef QT_NO_BACKINGSTORE
11284 const QRegion oldMask(d->extra->mask);
11287 d->extra->mask = newMask;
11288 d->extra->hasMask = !newMask.isEmpty();
11291 if (!testAttribute(Qt::WA_WState_Created))
11295 d->setMask_sys(newMask);
11297 #ifndef QT_NO_BACKINGSTORE
11301 if (!d->extra->hasMask) {
11302 // Mask was cleared; update newly exposed area.
11303 QRegion expose(rect());
11305 if (!expose.isEmpty()) {
11306 d->setDirtyOpaqueRegion();
11313 // Update newly exposed area on the parent widget.
11314 QRegion parentExpose(rect());
11315 parentExpose -= newMask;
11316 if (!parentExpose.isEmpty()) {
11317 d->setDirtyOpaqueRegion();
11318 parentExpose.translate(data->crect.topLeft());
11319 parentWidget()->update(parentExpose);
11322 // Update newly exposed area on this widget
11323 if (!oldMask.isEmpty())
11324 update(newMask - oldMask);
11330 \fn void QWidget::setMask(const QBitmap &bitmap)
11332 Causes only the pixels of the widget for which \a bitmap has a
11333 corresponding 1 bit to be visible. If the region includes pixels
11334 outside the rect() of the widget, window system controls in that
11335 area may or may not be visible, depending on the platform.
11337 Note that this effect can be slow if the region is particularly
11340 The following code shows how an image with an alpha channel can be
11341 used to generate a mask for a widget:
11343 \snippet doc/src/snippets/widget-mask/main.cpp 0
11345 The label shown by this code is masked using the image it contains,
11346 giving the appearance that an irregularly-shaped image is being drawn
11347 directly onto the screen.
11349 Masked widgets receive mouse events only on their visible
11352 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11354 void QWidget::setMask(const QBitmap &bitmap)
11356 setMask(QRegion(bitmap));
11360 \fn void QWidget::clearMask()
11362 Removes any mask set by setMask().
11366 void QWidget::clearMask()
11368 setMask(QRegion());
11371 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11372 Returns the X11 Picture handle of the widget for XRender
11373 support. Use of this function is not portable. This function will
11374 return 0 if XRender support is not compiled into Qt, if the
11375 XRender extension is not supported on the X11 display, or if the
11376 handle could not be created.
11380 void QWidgetPrivate::syncUnifiedMode() {
11381 // The whole purpose of this method is to keep the unifiedToolbar in sync.
11382 // That means making sure we either exchange the drawing methods or we let
11383 // the toolbar know that it does not require to draw the baseline.
11385 // This function makes sense only if this is a top level
11388 OSWindowRef window = qt_mac_window_for(q);
11389 if(changeMethods) {
11390 // Ok, we are in documentMode.
11391 if(originalDrawMethod)
11392 qt_mac_replaceDrawRect(window, this);
11394 if(!originalDrawMethod)
11395 qt_mac_replaceDrawRectOriginal(window, this);
11403 #include "moc_qwidget.cpp"