Cocoa: bugfix for autocads plugin project
[qt-netbsd.git] / src / gui / kernel / qwidget.cpp
blob6ffac2c91481d1032d3da03626d6710fdb34c86c
1 /****************************************************************************
2 **
3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: Nokia Corporation (qt-info@nokia.com)
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** No Commercial Usage
10 ** This file contains pre-release code and may not be distributed.
11 ** You may use this file in accordance with the terms and conditions
12 ** contained in the either Technology Preview License Agreement or the
13 ** Beta Release License Agreement.
15 ** GNU Lesser General Public License Usage
16 ** Alternatively, this file may be used under the terms of the GNU Lesser
17 ** General Public License version 2.1 as published by the Free Software
18 ** Foundation and appearing in the file LICENSE.LGPL included in the
19 ** packaging of this file. Please review the following information to
20 ** ensure the GNU Lesser General Public License version 2.1 requirements
21 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 ** In addition, as a special exception, Nokia gives you certain
24 ** additional rights. These rights are described in the Nokia Qt LGPL
25 ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26 ** package.
28 ** GNU General Public License Usage
29 ** Alternatively, this file may be used under the terms of the GNU
30 ** General Public License version 3.0 as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL included in the
32 ** packaging of this file. Please review the following information to
33 ** ensure the GNU General Public License version 3.0 requirements will be
34 ** met: http://www.gnu.org/copyleft/gpl.html.
36 ** If you are unsure which license is appropriate for your use, please
37 ** contact the sales department at http://qt.nokia.com/contact.
38 ** $QT_END_LICENSE$
40 ****************************************************************************/
42 #include "qapplication.h"
43 #include "qapplication_p.h"
44 #include "qbrush.h"
45 #include "qcursor.h"
46 #include "qdesktopwidget.h"
47 #include "qevent.h"
48 #include "qhash.h"
49 #include "qlayout.h"
50 #include "qmenu.h"
51 #include "qmetaobject.h"
52 #include "qpixmap.h"
53 #include "qpointer.h"
54 #include "qstack.h"
55 #include "qstyle.h"
56 #include "qstylefactory.h"
57 #include "qvariant.h"
58 #include "qwidget.h"
59 #include "qstyleoption.h"
60 #ifndef QT_NO_ACCESSIBILITY
61 # include "qaccessible.h"
62 #endif
63 #if defined(Q_WS_WIN)
64 # include "qt_windows.h"
65 #endif
66 #ifdef Q_WS_MAC
67 # include "qt_mac_p.h"
68 # include "qt_cocoa_helpers_mac_p.h"
69 # include "qmainwindow.h"
70 #endif
71 #if defined(Q_WS_QWS)
72 # include "qwsdisplay_qws.h"
73 # include "qwsmanager_qws.h"
74 # include "qpaintengine.h" // for PorterDuff
75 # include "private/qwindowsurface_qws_p.h"
76 #endif
77 #include "qpainter.h"
78 #include "qtooltip.h"
79 #include "qwhatsthis.h"
80 #include "qdebug.h"
81 #include "private/qstylesheetstyle_p.h"
82 #include "private/qstyle_p.h"
83 #include "private/qinputcontext_p.h"
84 #include "qfileinfo.h"
85 #include "qstandardgestures.h"
86 #include "qstandardgestures_p.h"
88 #if defined (Q_WS_WIN)
89 # include <private/qwininputcontext_p.h>
90 #endif
92 #if defined(Q_WS_X11)
93 # include <private/qpaintengine_x11_p.h>
94 # include "qx11info_x11.h"
95 #endif
97 #include <private/qwindowsurface_p.h>
98 #include <private/qbackingstore_p.h>
99 #ifdef Q_WS_MAC
100 # include <private/qpaintengine_mac_p.h>
101 #endif
102 #include <private/qpaintengine_raster_p.h>
104 #if defined(Q_OS_SYMBIAN)
105 #include "private/qt_s60_p.h"
106 #endif
108 #include "qwidget_p.h"
109 #include "qaction_p.h"
110 #include "qlayout_p.h"
111 #include "QtGui/qgraphicsproxywidget.h"
112 #include "QtGui/qgraphicsscene.h"
113 #include "private/qgraphicsproxywidget_p.h"
114 #include "QtGui/qabstractscrollarea.h"
115 #include "private/qabstractscrollarea_p.h"
116 #include "private/qevent_p.h"
118 #include "private/qgraphicssystem_p.h"
120 // widget/widget data creation count
121 //#define QWIDGET_EXTRA_DEBUG
122 //#define ALIEN_DEBUG
124 QT_BEGIN_NAMESPACE
126 #if !defined(Q_WS_QWS)
127 static bool qt_enable_backingstore = true;
128 #endif
129 #ifdef Q_WS_X11
130 // for compatibility with Qt 4.0
131 Q_GUI_EXPORT void qt_x11_set_global_double_buffer(bool enable)
133 qt_enable_backingstore = enable;
135 #endif
137 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
139 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
140 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
143 static inline bool hasBackingStoreSupport()
145 #ifdef Q_WS_MAC
146 return QApplicationPrivate::graphicsSystem() != 0;
147 #else
148 return true;
149 #endif
153 \internal
155 Returns true if \a p or any of its parents enable the
156 Qt::BypassGraphicsProxyWidget window flag. Used in QWidget::show() and
157 QWidget::setParent() to determine whether it's necessary to embed the
158 widget into a QGraphicsProxyWidget or not.
160 static inline bool bypassGraphicsProxyWidget(QWidget *p)
162 while (p) {
163 if (p->windowFlags() & Qt::BypassGraphicsProxyWidget)
164 return true;
165 p = p->parentWidget();
167 return false;
170 #ifdef Q_WS_MAC
171 # define QT_NO_PAINT_DEBUG
172 #endif
174 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
175 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
177 QWidgetPrivate::QWidgetPrivate(int version)
178 : QObjectPrivate(version)
179 , extra(0)
180 , focus_next(0)
181 , focus_prev(0)
182 , focus_child(0)
183 , layout(0)
184 , needsFlush(0)
185 , redirectDev(0)
186 , widgetItem(0)
187 , extraPaintEngine(0)
188 , polished(0)
189 , graphicsEffect(0)
190 , inheritedFontResolveMask(0)
191 , inheritedPaletteResolveMask(0)
192 , leftmargin(0)
193 , topmargin(0)
194 , rightmargin(0)
195 , bottommargin(0)
196 , leftLayoutItemMargin(0)
197 , topLayoutItemMargin(0)
198 , rightLayoutItemMargin(0)
199 , bottomLayoutItemMargin(0)
200 , hd(0)
201 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
202 , fg_role(QPalette::NoRole)
203 , bg_role(QPalette::NoRole)
204 , dirtyOpaqueChildren(1)
205 , isOpaque(0)
206 , inDirtyList(0)
207 , isScrolled(0)
208 , isMoved(0)
209 , usesDoubleBufferedGLContext(0)
210 #if defined(Q_WS_X11)
211 , picture(0)
212 #elif defined(Q_WS_WIN)
213 , noPaintOnScreen(0)
214 #elif defined(Q_WS_MAC)
215 , needWindowChange(0)
216 , isGLWidget(0)
217 , window_event(0)
218 , qd_hd(0)
219 #endif
220 ,imHints(Qt::ImhNone)
222 if (!qApp) {
223 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
224 return;
227 if (version != QObjectPrivateVersion)
228 qFatal("Cannot mix incompatible Qt libraries");
230 isWidget = true;
231 memset(high_attributes, 0, sizeof(high_attributes));
232 #ifdef QWIDGET_EXTRA_DEBUG
233 static int count = 0;
234 qDebug() << "widgets" << ++count;
235 #endif
239 QWidgetPrivate::~QWidgetPrivate()
241 if (widgetItem)
242 widgetItem->wid = 0;
244 if (extra)
245 deleteExtra();
247 delete graphicsEffect;
250 QWindowSurface *QWidgetPrivate::createDefaultWindowSurface()
252 Q_Q(QWidget);
253 if (QApplicationPrivate::graphicsSystem())
254 return QApplicationPrivate::graphicsSystem()->createWindowSurface(q);
255 return createDefaultWindowSurface_sys();
259 \internal
261 void QWidgetPrivate::scrollChildren(int dx, int dy)
263 Q_Q(QWidget);
264 if (q->children().size() > 0) { // scroll children
265 QPoint pd(dx, dy);
266 QObjectList childObjects = q->children();
267 for (int i = 0; i < childObjects.size(); ++i) { // move all children
268 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
269 if (w && !w->isWindow()) {
270 QPoint oldp = w->pos();
271 QRect r(w->pos() + pd, w->size());
272 w->data->crect = r;
273 #ifndef Q_WS_QWS
274 if (w->testAttribute(Qt::WA_WState_Created))
275 w->d_func()->setWSGeometry();
276 #endif
277 w->d_func()->setDirtyOpaqueRegion();
278 QMoveEvent e(r.topLeft(), oldp);
279 QApplication::sendEvent(w, &e);
285 QInputContext *QWidgetPrivate::inputContext() const
287 #ifndef QT_NO_IM
288 if (ic)
289 return ic;
290 #endif
291 return qApp->inputContext();
295 This function returns the QInputContext for this widget. By
296 default the input context is inherited from the widgets
297 parent. For toplevels it is inherited from QApplication.
299 You can override this and set a special input context for this
300 widget by using the setInputContext() method.
302 \sa setInputContext()
304 QInputContext *QWidget::inputContext()
306 Q_D(QWidget);
307 if (!testAttribute(Qt::WA_InputMethodEnabled))
308 return 0;
310 return d->inputContext();
314 This function sets the input context \a context
315 on this widget.
317 \sa inputContext()
319 void QWidget::setInputContext(QInputContext *context)
321 Q_D(QWidget);
322 if (!testAttribute(Qt::WA_InputMethodEnabled))
323 return;
324 #ifndef QT_NO_IM
325 if (d->ic)
326 delete d->ic;
327 d->ic = context;
328 #endif
333 \obsolete
335 This function can be called on the widget that currently has focus
336 to reset the input method operating on it.
338 This function is providing for convenience, instead you should use
339 \l{QInputContext::}{reset()} on the input context that was
340 returned by inputContext().
342 \sa QInputContext, inputContext(), QInputContext::reset()
344 void QWidget::resetInputContext()
346 if (!hasFocus())
347 return;
348 #ifndef QT_NO_IM
349 QInputContext *qic = this->inputContext();
350 if(qic)
351 qic->reset();
352 #endif // QT_NO_IM
355 #ifdef QT_KEYPAD_NAVIGATION
356 QPointer<QWidget> QWidgetPrivate::editingWidget;
359 Returns true if this widget currently has edit focus; otherwise false.
361 This feature is only available in Qt for Embedded Linux.
363 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
365 bool QWidget::hasEditFocus() const
367 const QWidget* w = this;
368 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
369 w = w->d_func()->extra->focus_proxy;
370 return QWidgetPrivate::editingWidget == w;
374 \fn void QWidget::setEditFocus(bool enable)
376 If \a enable is true, make this widget have edit focus, in which
377 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
378 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
379 change focus.
381 This feature is only available in Qt for Embedded Linux.
383 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
385 void QWidget::setEditFocus(bool on)
387 QWidget *f = this;
388 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
389 f = f->d_func()->extra->focus_proxy;
391 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
392 QWidgetPrivate::editingWidget->setEditFocus(false);
394 if (on && !f->hasFocus())
395 f->setFocus();
397 if ((!on && !QWidgetPrivate::editingWidget)
398 || (on && QWidgetPrivate::editingWidget == f)) {
399 return;
402 if (!on && QWidgetPrivate::editingWidget == f) {
403 QWidgetPrivate::editingWidget = 0;
404 QEvent event(QEvent::LeaveEditFocus);
405 QApplication::sendEvent(f, &event);
406 QApplication::sendEvent(f->style(), &event);
407 } else if (on) {
408 QWidgetPrivate::editingWidget = f;
409 QEvent event(QEvent::EnterEditFocus);
410 QApplication::sendEvent(f, &event);
411 QApplication::sendEvent(f->style(), &event);
413 f->repaint(); // Widget might want to repaint a focus indicator
415 #endif
418 \property QWidget::autoFillBackground
419 \brief whether the widget background is filled automatically
420 \since 4.1
422 If enabled, this property will cause Qt to fill the background of the
423 widget before invoking the paint event. The color used is defined by the
424 QPalette::Window color role from the widget's \l{QPalette}{palette}.
426 In addition, Windows are always filled with QPalette::Window, unless the
427 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
429 This property cannot be turned off (i.e., set to false) if a widget's
430 parent has a static gradient for its background.
432 \warning Use this property with caution in conjunction with
433 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
434 background or a border-image, this property is automatically disabled.
436 By default, this property is false.
438 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
439 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
441 bool QWidget::autoFillBackground() const
443 Q_D(const QWidget);
444 return d->extra && d->extra->autoFillBackground;
447 void QWidget::setAutoFillBackground(bool enabled)
449 Q_D(QWidget);
450 if (!d->extra)
451 d->createExtra();
452 if (d->extra->autoFillBackground == enabled)
453 return;
455 d->extra->autoFillBackground = enabled;
456 d->updateIsOpaque();
457 update();
458 d->updateIsOpaque();
462 \class QWidget
463 \brief The QWidget class is the base class of all user interface objects.
465 \ingroup basicwidgets
468 The widget is the atom of the user interface: it receives mouse, keyboard
469 and other events from the window system, and paints a representation of
470 itself on the screen. Every widget is rectangular, and they are sorted in a
471 Z-order. A widget is clipped by its parent and by the widgets in front of
474 A widget that is not embedded in a parent widget is called a window.
475 Usually, windows have a frame and a title bar, although it is also possible
476 to create windows without such decoration using suitable
477 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
478 subclasses of QDialog are the most common window types.
480 Every widget's constructor accepts one or two standard arguments:
482 \list 1
483 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
484 (the default), the new widget will be a window. If not, it will be
485 a child of \e parent, and be constrained by \e parent's geometry
486 (unless you specify Qt::Window as window flag).
487 \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
488 the default is suitable for almost all widgets, but to get, for
489 example, a window without a window system frame, you must use
490 special flags.
491 \endlist
493 QWidget has many member functions, but some of them have little direct
494 functionality; for example, QWidget has a font property, but never uses
495 this itself. There are many subclasses which provide real functionality,
496 such as QLabel, QPushButton, QListWidget, and QTabWidget.
499 \section1 Top-Level and Child Widgets
501 A widget without a parent widget is always an independent window (top-level
502 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
503 title bar and icon respectively.
505 Non-window widgets are child widgets, displayed within their parent
506 widgets. Most widgets in Qt are mainly useful as child widgets. For
507 example, it is possible to display a button as a top-level window, but most
508 people prefer to put their buttons inside other widgets, such as QDialog.
510 \image parent-child-widgets.png A parent widget containing various child widgets.
512 The diagram above shows a QGroupBox widget being used to hold various child
513 widgets in a layout provided by QGridLayout. The QLabel child widgets have
514 been outlined to indicate their full sizes.
516 If you want to use a QWidget to hold child widgets you will usually want to
517 add a layout to the parent QWidget. See \l{Layout Management} for more
518 information.
521 \section1 Composite Widgets
523 When a widget is used as a container to group a number of child widgets, it
524 is known as a composite widget. These can be created by constructing a
525 widget with the required visual properties - a QFrame, for example - and
526 adding child widgets to it, usually managed by a layout. The above diagram
527 shows such a composite widget that was created using \l{Qt Designer}.
529 Composite widgets can also be created by subclassing a standard widget,
530 such as QWidget or QFrame, and adding the necessary layout and child
531 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
532 {examples provided with Qt} use this approach, and it is also covered in
533 the Qt \l{Tutorials}.
536 \section1 Custom Widgets and Painting
538 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
539 display custom content that is composed using a series of painting
540 operations with an instance of the QPainter class. This approach contrasts
541 with the canvas-style approach used by the \l{Graphics View}
542 {Graphics View Framework} where items are added to a scene by the
543 application and are rendered by the framework itself.
545 Each widget performs all painting operations from within its paintEvent()
546 function. This is called whenever the widget needs to be redrawn, either
547 as a result of some external change or when requested by the application.
549 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
550 can handle paint events.
553 \section1 Size Hints and Size Policies
555 When implementing a new widget, it is almost always useful to reimplement
556 sizeHint() to provide a reasonable default size for the widget and to set
557 the correct size policy with setSizePolicy().
559 By default, composite widgets which do not provide a size hint will be
560 sized according to the space requirements of their child widgets.
562 The size policy lets you supply good default behavior for the layout
563 management system, so that other widgets can contain and manage yours
564 easily. The default size policy indicates that the size hint represents
565 the preferred size of the widget, and this is often good enough for many
566 widgets.
568 \note The size of top-level widgets are constrained to 2/3 of the desktop's
569 height and width. You can resize() the widget manually if these bounds are
570 inadequate.
573 \section1 Events
575 Widgets respond to events that are typically caused by user actions. Qt
576 delivers events to widgets by calling specific event handler functions with
577 instances of QEvent subclasses containing information about each event.
579 If your widget only contains child widgets, you probably do not need to
580 implement any event handlers. If you want to detect a mouse click in a
581 child widget call the child's underMouse() function inside the widget's
582 mousePressEvent().
584 The \l{widgets/scribble}{Scribble example} implements a wider set of
585 events to handle mouse movement, button presses, and window resizing.
587 You will need to supply the behavior and content for your own widgets, but
588 here is a brief overview of the events that are relevant to QWidget,
589 starting with the most common ones:
591 \list
592 \i paintEvent() is called whenever the widget needs to be repainted.
593 Every widget displaying custom content must implement it. Painting
594 using a QPainter can only take place in a paintEvent() or a
595 function called by a paintEvent().
596 \i resizeEvent() is called when the widget has been resized.
597 \i mousePressEvent() is called when a mouse button is pressed while
598 the mouse cursor is inside the widget, or when the widget has
599 grabbed the mouse using grabMouse(). Pressing the mouse without
600 releasing it is effectively the same as calling grabMouse().
601 \i mouseReleaseEvent() is called when a mouse button is released. A
602 widget receives mouse release events when it has received the
603 corresponding mouse press event. This means that if the user
604 presses the mouse inside \e your widget, then drags the mouse
605 somewhere else before releasing the mouse button, \e your widget
606 receives the release event. There is one exception: if a popup menu
607 appears while the mouse button is held down, this popup immediately
608 steals the mouse events.
609 \i mouseDoubleClickEvent() is called when the user double-clicks in
610 the widget. If the user double-clicks, the widget receives a mouse
611 press event, a mouse release event and finally this event instead
612 of a second mouse press event. (Some mouse move events may also be
613 received if the mouse is not held steady during this operation.) It
614 is \e{not possible} to distinguish a click from a double-click
615 until the second click arrives. (This is one reason why most GUI
616 books recommend that double-clicks be an extension of
617 single-clicks, rather than trigger a different action.)
618 \endlist
620 Widgets that accept keyboard input need to reimplement a few more event
621 handlers:
623 \list
624 \i keyPressEvent() is called whenever a key is pressed, and again when
625 a key has been held down long enough for it to auto-repeat. The
626 \key Tab and \key Shift+Tab keys are only passed to the widget if
627 they are not used by the focus-change mechanisms. To force those
628 keys to be processed by your widget, you must reimplement
629 QWidget::event().
630 \i focusInEvent() is called when the widget gains keyboard focus
631 (assuming you have called setFocusPolicy()). Well-behaved widgets
632 indicate that they own the keyboard focus in a clear but discreet
633 way.
634 \i focusOutEvent() is called when the widget loses keyboard focus.
635 \endlist
637 You may be required to also reimplement some of the less common event
638 handlers:
640 \list
641 \i mouseMoveEvent() is called whenever the mouse moves while a mouse
642 button is held down. This can be useful during drag and drop
643 operations. If you call setMouseTracking(true), you get mouse move
644 events even when no buttons are held down. (See also the \l{Drag
645 and Drop} guide.)
646 \i keyReleaseEvent() is called whenever a key is released and while it
647 is held down (if the key is auto-repeating). In that case, the
648 widget will receive a pair of key release and key press event for
649 every repeat. The \key Tab and \key Shift+Tab keys are only passed
650 to the widget if they are not used by the focus-change mechanisms.
651 To force those keys to be processed by your widget, you must
652 reimplement QWidget::event().
653 \i wheelEvent() is called whenever the user turns the mouse wheel
654 while the widget has the focus.
655 \i enterEvent() is called when the mouse enters the widget's screen
656 space. (This excludes screen space owned by any of the widget's
657 children.)
658 \i leaveEvent() is called when the mouse leaves the widget's screen
659 space. If the mouse enters a child widget it will not cause a
660 leaveEvent().
661 \i moveEvent() is called when the widget has been moved relative to
662 its parent.
663 \i closeEvent() is called when the user closes the widget (or when
664 close() is called).
665 \endlist
667 There are also some rather obscure events described in the documentation
668 for QEvent::Type. To handle these events, you need to reimplement event()
669 directly.
671 The default implementation of event() handles \key Tab and \key Shift+Tab
672 (to move the keyboard focus), and passes on most of the other events to
673 one of the more specialized handlers above.
675 Events and the mechanism used to deliver them are covered in the
676 \l{Events and Event Filters} document.
678 \section1 Groups of Functions and Properties
680 \table
681 \header \i Context \i Functions and Properties
683 \row \i Window functions \i
684 show(),
685 hide(),
686 raise(),
687 lower(),
688 close().
690 \row \i Top-level windows \i
691 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
692 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
693 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
694 showNormal().
696 \row \i Window contents \i
697 update(),
698 repaint(),
699 scroll().
701 \row \i Geometry \i
702 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
703 \l sizePolicy, sizeHint(), minimumSizeHint(),
704 updateGeometry(), layout(),
705 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
706 adjustSize(),
707 mapFromGlobal(), mapToGlobal(),
708 mapFromParent(), mapToParent(),
709 \l maximumSize, \l minimumSize, \l sizeIncrement,
710 \l baseSize, setFixedSize()
712 \row \i Mode \i
713 \l visible, isVisibleTo(),
714 \l enabled, isEnabledTo(),
715 \l modal,
716 isWindow(),
717 \l mouseTracking,
718 \l updatesEnabled,
719 visibleRegion().
721 \row \i Look and feel \i
722 style(),
723 setStyle(),
724 \l styleSheet,
725 \l cursor,
726 \l font,
727 \l palette,
728 backgroundRole(), setBackgroundRole(),
729 fontInfo(), fontMetrics().
731 \row \i Keyboard focus functions \i
732 \l focus, \l focusPolicy,
733 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
734 focusNextChild(), focusPreviousChild().
736 \row \i Mouse and keyboard grabbing \i
737 grabMouse(), releaseMouse(),
738 grabKeyboard(), releaseKeyboard(),
739 mouseGrabber(), keyboardGrabber().
741 \row \i Event handlers \i
742 event(),
743 mousePressEvent(),
744 mouseReleaseEvent(),
745 mouseDoubleClickEvent(),
746 mouseMoveEvent(),
747 keyPressEvent(),
748 keyReleaseEvent(),
749 focusInEvent(),
750 focusOutEvent(),
751 wheelEvent(),
752 enterEvent(),
753 leaveEvent(),
754 paintEvent(),
755 moveEvent(),
756 resizeEvent(),
757 closeEvent(),
758 dragEnterEvent(),
759 dragMoveEvent(),
760 dragLeaveEvent(),
761 dropEvent(),
762 childEvent(),
763 showEvent(),
764 hideEvent(),
765 customEvent().
766 changeEvent(),
768 \row \i System functions \i
769 parentWidget(), window(), setParent(), winId(),
770 find(), metric().
772 \row \i Interactive help \i
773 setToolTip(), setWhatsThis()
775 \endtable
778 \section1 Widget Style Sheets
780 In addition to the standard widget styles for each platform, widgets can
781 also be styled according to rules specified in a \l{styleSheet}
782 {style sheet}. This feature enables you to customize the appearance of
783 specific widgets to provide visual cues to users about their purpose. For
784 example, a button could be styled in a particular way to indicate that it
785 performs a destructive action.
787 The use of widget style sheets is described in more detail in the
788 \l{Qt Style Sheets} document.
791 \section1 Transparency and Double Buffering
793 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
794 is no need to write double-buffering code in paintEvent() to avoid
795 flicker.
797 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
798 deprecated. Instead, the contents of parent widgets are propagated by
799 default to each of their children as long as Qt::WA_PaintOnScreen is not
800 set. Custom widgets can be written to take advantage of this feature by
801 updating irregular regions (to create non-rectangular child widgets), or
802 painting with colors that have less than full alpha component. The
803 following diagram shows how attributes and properties of a custom widget
804 can be fine-tuned to achieve different effects.
806 \image propagation-custom.png
808 In the above diagram, a semi-transparent rectangular child widget with an
809 area removed is constructed and added to a parent widget (a QLabel showing
810 a pixmap). Then, different properties and widget attributes are set to
811 achieve different effects:
813 \list
814 \i The left widget has no additional properties or widget attributes
815 set. This default state suits most custom widgets using
816 transparency, are irregularly-shaped, or do not paint over their
817 entire area with an opaque brush.
818 \i The center widget has the \l autoFillBackground property set. This
819 property is used with custom widgets that rely on the widget to
820 supply a default background, and do not paint over their entire
821 area with an opaque brush.
822 \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
823 set. This indicates that the widget will paint over its entire area
824 with opaque colors. The widget's area will initially be
825 \e{uninitialized}, represented in the diagram with a red diagonal
826 grid pattern that shines through the overpainted area. The
827 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
828 paint their own specialized contents quickly and do not need a
829 default filled background.
830 \endlist
832 To rapidly update custom widgets with simple background colors, such as
833 real-time plotting or graphing widgets, it is better to define a suitable
834 background color (using setBackgroundRole() with the
835 QPalette::Window role), set the \l autoFillBackground property, and only
836 implement the necessary drawing functionality in the widget's paintEvent().
838 To rapidly update custom widgets that constantly paint over their entire
839 areas with opaque content, e.g., video streaming widgets, it is better to
840 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
841 associated with repainting the widget's background.
843 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
844 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
845 attribute takes precedence. Depending on your requirements, you should
846 choose either one of them.
848 Since Qt 4.1, the contents of parent widgets are also propagated to
849 standard Qt widgets. This can lead to some unexpected results if the
850 parent widget is decorated in a non-standard way, as shown in the diagram
851 below.
853 \image propagation-standard.png
855 The scope for customizing the painting behavior of standard Qt widgets,
856 without resorting to subclassing, is slightly less than that possible for
857 custom widgets. Usually, the desired appearance of a standard widget can be
858 achieved by setting its \l autoFillBackground property.
861 \section1 Creating Translucent Windows
863 Since Qt 4.5, it has been possible to create windows with translucent regions
864 on window systems that support compositing.
866 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
867 attribute with setAttribute() and ensure that its background is painted with
868 non-opaque colors in the regions you want to be partially transparent.
870 Platform notes:
872 \list
873 \o X11: This feature relies on the use of an X server that supports ARGB visuals
874 and a compositing window manager.
875 \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
876 for the translucency to work.
877 \endlist
880 \section1 Native Widgets vs Alien Widgets
882 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
883 system. They do not have a native window handle associated with them. This
884 feature significantly speeds up widget painting, resizing, and removes flicker.
886 Should you require the old behavior with native windows, you can choose
887 one of the following options:
889 \list 1
890 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
891 \i Set the Qt::AA_NativeWindows attribute on your application. All
892 widgets will be native widgets.
893 \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
894 and all of its ancestors will become native (unless
895 Qt::WA_DontCreateNativeAncestors is set).
896 \i Call QWidget::winId to enforce a native window (this implies 3).
897 \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
898 (this implies 3).
899 \endlist
901 \sa QEvent, QPainter, QGridLayout, QBoxLayout
903 \section1 SoftKeys
904 \since 4.6
905 \preliminary
907 Softkeys API is a platform independent way of mapping actions to (hardware)keys
908 and toolbars provided by the underlying platform.
910 There are three major use cases supported. First one is a mobile device
911 with keypad navigation and no touch ui. Second use case is a mobile
912 device with touch ui. Third use case is desktop. For now the softkey API is
913 only implemented for Series60.
915 QActions are set to widget(s) via softkey API. Actions in focused widget are
916 mapped to native toolbar or hardware keys. Even though the API allows to set
917 any amount of widgets there might be physical restrictions to amount of
918 softkeys that can be used by the device.
920 \o Series60: For series60 menu button is automatically mapped to left
921 soft key if there is QMainWindow with QMenuBar in widgets parent hierarchy.
923 \sa softKeys()
924 \sa setSoftKey()
928 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
929 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
932 /*****************************************************************************
933 QWidget utility functions
934 *****************************************************************************/
936 QRegion qt_dirtyRegion(QWidget *widget)
938 if (!widget)
939 return QRegion();
941 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
942 if (!bs)
943 return QRegion();
945 return bs->dirtyRegion(widget);
948 /*****************************************************************************
949 QWidget member functions
950 *****************************************************************************/
953 Widget state flags:
954 \list
955 \i Qt::WA_WState_Created The widget has a valid winId().
956 \i Qt::WA_WState_Visible The widget is currently visible.
957 \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
958 become visible unless you call show() on it. Qt::WA_WState_Hidden
959 implies !Qt::WA_WState_Visible.
960 \i Qt::WA_WState_CompressKeys Compress keyboard events.
961 \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
962 \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
963 \i Qt::WA_WState_Reparented The widget has been reparented.
964 \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
965 \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
966 \endlist
969 struct QWidgetExceptionCleaner
971 /* this cleans up when the constructor throws an exception */
972 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
974 #ifndef QT_NO_EXCEPTIONS
975 QWidgetPrivate::allWidgets->remove(that);
976 if (d->focus_next != that) {
977 if (d->focus_next)
978 d->focus_next->d_func()->focus_prev = d->focus_prev;
979 if (d->focus_prev)
980 d->focus_prev->d_func()->focus_next = d->focus_next;
982 #endif
987 Constructs a widget which is a child of \a parent, with widget
988 flags set to \a f.
990 If \a parent is 0, the new widget becomes a window. If
991 \a parent is another widget, this widget becomes a child window
992 inside \a parent. The new widget is deleted when its \a parent is
993 deleted.
995 The widget flags argument, \a f, is normally 0, but it can be set
996 to customize the frame of a window (i.e. \a
997 parent must be 0). To customize the frame, use a value composed
998 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1000 If you add a child widget to an already visible widget you must
1001 explicitly show the child to make it visible.
1003 Note that the X11 version of Qt may not be able to deliver all
1004 combinations of style flags on all systems. This is because on
1005 X11, Qt can only ask the window manager, and the window manager
1006 can override the application's settings. On Windows, Qt can set
1007 whatever flags you want.
1009 \sa windowFlags
1012 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1013 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1015 QT_TRY {
1016 d_func()->init(parent, f);
1017 } QT_CATCH(...) {
1018 QWidgetExceptionCleaner::cleanup(this, d_func());
1019 QT_RETHROW;
1023 #ifdef QT3_SUPPORT
1025 \overload
1026 \obsolete
1028 QWidget::QWidget(QWidget *parent, const char *name, Qt::WindowFlags f)
1029 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1031 QT_TRY {
1032 d_func()->init(parent , f);
1033 setObjectName(QString::fromAscii(name));
1034 } QT_CATCH(...) {
1035 QWidgetExceptionCleaner::cleanup(this, d_func());
1036 QT_RETHROW;
1039 #endif
1041 /*! \internal
1043 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1044 : QObject(dd, 0), QPaintDevice()
1046 Q_D(QWidget);
1047 QT_TRY {
1048 d->init(parent, f);
1049 } QT_CATCH(...) {
1050 QWidgetExceptionCleaner::cleanup(this, d_func());
1051 QT_RETHROW;
1056 \internal
1058 int QWidget::devType() const
1060 return QInternal::Widget;
1064 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1065 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1067 bool customize = (flags & (Qt::CustomizeWindowHint
1068 | Qt::FramelessWindowHint
1069 | Qt::WindowTitleHint
1070 | Qt::WindowSystemMenuHint
1071 | Qt::WindowMinimizeButtonHint
1072 | Qt::WindowMaximizeButtonHint
1073 | Qt::WindowCloseButtonHint
1074 | Qt::WindowContextHelpButtonHint));
1076 uint type = (flags & Qt::WindowType_Mask);
1078 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1079 type = Qt::Window;
1080 flags |= Qt::Window;
1083 if (flags & Qt::CustomizeWindowHint) {
1084 // modify window flags to make them consistent.
1085 // Only enable this on non-Mac platforms. Since the old way of doing this would
1086 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1087 // we can't just add this in.
1088 #ifndef Q_WS_MAC
1089 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1090 flags |= Qt::WindowSystemMenuHint;
1091 #else
1092 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1093 | Qt::WindowSystemMenuHint)) {
1094 #endif
1095 flags |= Qt::WindowTitleHint;
1096 flags &= ~Qt::FramelessWindowHint;
1098 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1099 // if any of the window hints that affect the titlebar are set
1100 // and the window is supposed to have frame, we add a titlebar
1101 // and system menu by default.
1102 flags |= Qt::WindowSystemMenuHint;
1103 flags |= Qt::WindowTitleHint;
1105 if (customize)
1106 ; // don't modify window flags if the user explicitely set them.
1107 else if (type == Qt::Dialog || type == Qt::Sheet)
1108 #ifndef Q_WS_WINCE
1109 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1110 #else
1111 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1112 #endif
1113 else if (type == Qt::Tool)
1114 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1115 else
1116 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1121 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1123 Q_Q(QWidget);
1124 if (QApplication::type() == QApplication::Tty)
1125 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1127 Q_ASSERT(allWidgets);
1128 allWidgets->insert(q);
1130 QWidget *desktopWidget = 0;
1131 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1132 desktopWidget = parentWidget;
1133 parentWidget = 0;
1136 q->data = &data;
1138 #ifndef QT_NO_THREAD
1139 if (!parent) {
1140 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1141 "Widgets must be created in the GUI thread.");
1143 #endif
1145 #if defined(Q_WS_X11)
1146 if (desktopWidget) {
1147 // make sure the widget is created on the same screen as the
1148 // programmer specified desktop widget
1149 xinfo = desktopWidget->d_func()->xinfo;
1151 #else
1152 Q_UNUSED(desktopWidget);
1153 #endif
1155 data.fstrut_dirty = true;
1157 data.winid = 0;
1158 data.widget_attributes = 0;
1159 data.window_flags = f;
1160 data.window_state = 0;
1161 data.focus_policy = 0;
1162 data.context_menu_policy = Qt::DefaultContextMenu;
1163 data.window_modality = Qt::NonModal;
1165 data.sizehint_forced = 0;
1166 data.is_closing = 0;
1167 data.in_show = 0;
1168 data.in_set_window_state = 0;
1169 data.in_destructor = false;
1171 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1172 if (f & Qt::MSWindowsOwnDC)
1173 q->setAttribute(Qt::WA_NativeWindow);
1175 #ifdef Q_WS_WINCE
1176 data.window_state_internal = 0;
1177 #endif
1179 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1180 adjustQuitOnCloseAttribute();
1182 q->setAttribute(Qt::WA_WState_Hidden);
1184 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1185 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1187 focus_next = focus_prev = q;
1189 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1190 q->create();
1191 else if (parentWidget)
1192 q->setParent(parentWidget, data.window_flags);
1193 else {
1194 adjustFlags(data.window_flags, q);
1195 resolveLayoutDirection();
1196 // opaque system background?
1197 const QBrush &background = q->palette().brush(QPalette::Window);
1198 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1200 data.fnt = QFont(data.fnt, q);
1201 #if defined(Q_WS_X11)
1202 data.fnt.x11SetScreen(xinfo.screen());
1203 #endif // Q_WS_X11
1205 q->setAttribute(Qt::WA_PendingMoveEvent);
1206 q->setAttribute(Qt::WA_PendingResizeEvent);
1208 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1209 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1211 if (QApplicationPrivate::app_compile_version < 0x040200
1212 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1213 q->create();
1216 QEvent e(QEvent::Create);
1217 QApplication::sendEvent(q, &e);
1218 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1220 extraPaintEngine = 0;
1225 void QWidgetPrivate::createRecursively()
1227 Q_Q(QWidget);
1228 q->create(0, true, true);
1229 for (int i = 0; i < children.size(); ++i) {
1230 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1231 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1232 child->d_func()->createRecursively();
1240 Creates a new widget window if \a window is 0, otherwise sets the
1241 widget's window to \a window.
1243 Initializes the window (sets the geometry etc.) if \a
1244 initializeWindow is true. If \a initializeWindow is false, no
1245 initialization is performed. This parameter only makes sense if \a
1246 window is a valid window.
1248 Destroys the old window if \a destroyOldWindow is true. If \a
1249 destroyOldWindow is false, you are responsible for destroying the
1250 window yourself (using platform native code).
1252 The QWidget constructor calls create(0,true,true) to create a
1253 window for this widget.
1256 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1258 Q_D(QWidget);
1259 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1260 return;
1262 if (d->data.in_destructor)
1263 return;
1265 Qt::WindowType type = windowType();
1266 Qt::WindowFlags &flags = data->window_flags;
1268 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1269 type = Qt::Window;
1270 flags |= Qt::Window;
1273 if (QWidget *parent = parentWidget()) {
1274 if (type & Qt::Window) {
1275 if (!parent->testAttribute(Qt::WA_WState_Created))
1276 parent->createWinId();
1277 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1278 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1279 // We're about to create a native child widget that doesn't have a native parent;
1280 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1281 // attribute is set.
1282 d->createWinId(window);
1283 // Nothing more to do.
1284 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1285 Q_ASSERT(internalWinId());
1286 return;
1290 #ifdef QT3_SUPPORT
1291 if (flags & Qt::WStaticContents)
1292 setAttribute(Qt::WA_StaticContents);
1293 if (flags & Qt::WDestructiveClose)
1294 setAttribute(Qt::WA_DeleteOnClose);
1295 if (flags & Qt::WShowModal)
1296 setWindowModality(Qt::ApplicationModal);
1297 if (flags & Qt::WMouseNoMask)
1298 setAttribute(Qt::WA_MouseNoMask);
1299 if (flags & Qt::WGroupLeader)
1300 setAttribute(Qt::WA_GroupLeader);
1301 if (flags & Qt::WNoMousePropagation)
1302 setAttribute(Qt::WA_NoMousePropagation);
1303 #endif
1305 static int paintOnScreenEnv = -1;
1306 if (paintOnScreenEnv == -1)
1307 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1308 if (paintOnScreenEnv == 1)
1309 setAttribute(Qt::WA_PaintOnScreen);
1311 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1312 setAttribute(Qt::WA_NativeWindow);
1314 #ifdef ALIEN_DEBUG
1315 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1316 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1317 #endif
1319 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1320 // Unregister the dropsite (if already registered) before we
1321 // re-create the widget with a native window.
1322 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1323 && d->extra && d->extra->dropTarget) {
1324 d->registerDropSite(false);
1326 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1328 d->updateIsOpaque();
1330 setAttribute(Qt::WA_WState_Created); // set created flag
1331 d->create_sys(window, initializeWindow, destroyOldWindow);
1333 // a real toplevel window needs a backing store
1334 if (isWindow() && windowType() != Qt::Desktop) {
1335 delete d->topData()->backingStore;
1336 // QWidgetBackingStore will check this variable, hence it must be 0
1337 d->topData()->backingStore = 0;
1338 if (hasBackingStoreSupport())
1339 d->topData()->backingStore = new QWidgetBackingStore(this);
1342 d->setModal_sys();
1344 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1345 setAttribute(Qt::WA_DropSiteRegistered, true);
1347 #ifdef QT_EVAL
1348 extern void qt_eval_init_widget(QWidget *w);
1349 qt_eval_init_widget(this);
1350 #endif
1352 // need to force the resting of the icon after changing parents
1353 if (testAttribute(Qt::WA_SetWindowIcon))
1354 d->setWindowIcon_sys(true);
1355 if (isWindow() && !d->topData()->iconText.isEmpty())
1356 d->setWindowIconText_helper(d->topData()->iconText);
1357 if (windowType() != Qt::Desktop) {
1358 d->updateSystemBackground();
1360 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1361 d->setWindowIcon_sys();
1366 Destroys the widget.
1368 All this widget's children are deleted first. The application
1369 exits if this widget is the main widget.
1372 QWidget::~QWidget()
1374 Q_D(QWidget);
1375 d->data.in_destructor = true;
1377 #if defined (QT_CHECK_STATE)
1378 if (paintingActive())
1379 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1380 #endif
1382 // force acceptDrops false before winId is destroyed.
1383 d->registerDropSite(false);
1385 #ifndef QT_NO_ACTION
1386 // remove all actions from this widget
1387 for (int i = 0; i < d->actions.size(); ++i) {
1388 QActionPrivate *apriv = d->actions.at(i)->d_func();
1389 apriv->widgets.removeAll(this);
1391 d->actions.clear();
1392 #endif
1394 #ifndef QT_NO_SHORTCUT
1395 // Remove all shortcuts grabbed by this
1396 // widget, unless application is closing
1397 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1398 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1399 #endif
1401 // delete layout while we still are a valid widget
1402 delete d->layout;
1403 // Remove myself from focus list
1405 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1406 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1408 if (d->focus_next != this) {
1409 d->focus_next->d_func()->focus_prev = d->focus_prev;
1410 d->focus_prev->d_func()->focus_next = d->focus_next;
1411 d->focus_next = d->focus_prev = 0;
1414 #ifdef QT3_SUPPORT
1415 if (QApplicationPrivate::main_widget == this) { // reset main widget
1416 QApplicationPrivate::main_widget = 0;
1417 QApplication::quit();
1419 #endif
1421 QT_TRY {
1422 clearFocus();
1423 } QT_CATCH(...) {
1424 // swallow this problem because we are in a destructor
1427 d->setDirtyOpaqueRegion();
1429 if (isWindow() && isVisible() && internalWinId()) {
1430 QT_TRY {
1431 d->close_helper(QWidgetPrivate::CloseNoEvent);
1432 } QT_CATCH(...) {
1433 // if we're out of memory, at least hide the window.
1434 QT_TRY {
1435 hide();
1436 } QT_CATCH(...) {
1437 // and if that also doesn't work, then give up
1442 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
1443 else if (!internalWinId() && isVisible()) {
1444 qApp->d_func()->sendSyntheticEnterLeave(this);
1446 #endif
1448 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1449 bs->removeDirtyWidget(this);
1450 if (testAttribute(Qt::WA_StaticContents))
1451 bs->removeStaticWidget(this);
1454 delete d->needsFlush;
1455 d->needsFlush = 0;
1457 // set all QPointers for this object to zero
1458 QObjectPrivate::clearGuards(this);
1460 if (d->declarativeData) {
1461 d->declarativeData->destroyed(this);
1462 d->declarativeData = 0; // don't activate again in ~QObject
1465 if (!d->children.isEmpty())
1466 d->deleteChildren();
1468 QApplication::removePostedEvents(this);
1470 QT_TRY {
1471 destroy(); // platform-dependent cleanup
1472 } QT_CATCH(...) {
1473 // if this fails we can't do anything about it but at least we are not allowed to throw.
1475 --QWidgetPrivate::instanceCounter;
1477 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1478 QWidgetPrivate::allWidgets->remove(this);
1480 QEvent e(QEvent::Destroy);
1481 QCoreApplication::sendEvent(this, &e);
1484 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1485 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1487 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1489 Q_Q(QWidget);
1490 // the user might create a widget with Qt::Desktop window
1491 // attribute (or create another QDesktopWidget instance), which
1492 // will have the same windowid (the root window id) as the
1493 // qt_desktopWidget. We should not add the second desktop widget
1494 // to the mapper.
1495 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1496 if (mapper && data.winid && !userDesktopWidget) {
1497 mapper->remove(data.winid);
1500 data.winid = id;
1501 #if defined(Q_WS_X11)
1502 hd = id; // X11: hd == ident
1503 #endif
1504 if (mapper && id && !userDesktopWidget) {
1505 mapper->insert(data.winid, q);
1509 void QWidgetPrivate::createTLExtra()
1511 if (!extra)
1512 createExtra();
1513 if (!extra->topextra) {
1514 QTLWExtra* x = extra->topextra = new QTLWExtra;
1515 x->icon = 0;
1516 x->iconPixmap = 0;
1517 x->backingStore = 0;
1518 x->windowSurface = 0;
1519 x->sharedPainter = 0;
1520 x->incw = x->inch = 0;
1521 x->basew = x->baseh = 0;
1522 x->frameStrut.setCoords(0, 0, 0, 0);
1523 x->normalGeometry = QRect(0,0,-1,-1);
1524 x->savedFlags = 0;
1525 x->opacity = 255;
1526 x->posFromMove = false;
1527 x->sizeAdjusted = false;
1528 x->inTopLevelResize = false;
1529 x->inRepaint = false;
1530 x->embedded = 0;
1531 createTLSysExtra();
1532 #ifdef QWIDGET_EXTRA_DEBUG
1533 static int count = 0;
1534 qDebug() << "tlextra" << ++count;
1535 #endif
1540 \internal
1541 Creates the widget extra data.
1544 void QWidgetPrivate::createExtra()
1546 if (!extra) { // if not exists
1547 extra = new QWExtra;
1548 extra->glContext = 0;
1549 extra->topextra = 0;
1550 extra->proxyWidget = 0;
1551 #ifndef QT_NO_CURSOR
1552 extra->curs = 0;
1553 #endif
1554 extra->minw = 0;
1555 extra->minh = 0;
1556 extra->maxw = QWIDGETSIZE_MAX;
1557 extra->maxh = QWIDGETSIZE_MAX;
1558 extra->customDpiX = 0;
1559 extra->customDpiY = 0;
1560 extra->explicitMinSize = 0;
1561 extra->explicitMaxSize = 0;
1562 extra->autoFillBackground = 0;
1563 extra->nativeChildrenForced = 0;
1564 extra->inRenderWithPainter = 0;
1565 extra->hasMask = 0;
1566 createSysExtra();
1567 #ifdef QWIDGET_EXTRA_DEBUG
1568 static int count = 0;
1569 qDebug() << "extra" << ++count;
1570 #endif
1576 \internal
1577 Deletes the widget extra data.
1580 void QWidgetPrivate::deleteExtra()
1582 if (extra) { // if exists
1583 #ifndef QT_NO_CURSOR
1584 delete extra->curs;
1585 #endif
1586 deleteSysExtra();
1587 #ifndef QT_NO_STYLE_STYLESHEET
1588 // dereference the stylesheet style
1589 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1590 proxy->deref();
1591 #endif
1592 if (extra->topextra) {
1593 deleteTLSysExtra();
1594 delete extra->topextra->backingStore;
1595 delete extra->topextra->icon;
1596 delete extra->topextra->iconPixmap;
1597 #if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER)
1598 delete extra->topextra->qwsManager;
1599 #endif
1600 delete extra->topextra->windowSurface;
1601 delete extra->topextra;
1603 delete extra;
1604 // extra->xic destroyed in QWidget::destroy()
1605 extra = 0;
1610 Returns true if there are widgets above this which overlap with
1611 \a rect, which is in parent's coordinate system (same as crect).
1614 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1616 Q_Q(const QWidget);
1618 const QWidget *w = q;
1619 QRect r = rect;
1620 while (w) {
1621 if (w->isWindow())
1622 return false;
1623 QWidgetPrivate *pd = w->parentWidget()->d_func();
1624 bool above = false;
1625 for (int i = 0; i < pd->children.size(); ++i) {
1626 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1627 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1628 continue;
1629 if (!above) {
1630 above = (sibling == w);
1631 continue;
1634 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1635 const QWExtra *siblingExtra = sibling->d_func()->extra;
1636 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1637 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1638 continue;
1640 return true;
1643 w = w->parentWidget();
1644 r.translate(pd->data.crect.topLeft());
1646 return false;
1649 void QWidgetPrivate::syncBackingStore()
1651 if (paintOnScreen()) {
1652 repaint_sys(dirty);
1653 dirty = QRegion();
1654 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1655 bs->sync();
1659 void QWidgetPrivate::syncBackingStore(const QRegion &region)
1661 if (paintOnScreen())
1662 repaint_sys(region);
1663 else if (QWidgetBackingStore *bs = maybeBackingStore())
1664 bs->sync(q_func(), region);
1667 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1669 Q_Q(QWidget);
1671 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1672 return; // nothing we can do
1674 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1675 return; // nothing to do
1677 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1678 if (enable)
1679 q->update();
1681 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1682 for (int i = 0; i < children.size(); ++i) {
1683 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1684 if (w && !w->isWindow() && !w->testAttribute(attribute))
1685 w->d_func()->setUpdatesEnabled_helper(enable);
1690 \internal
1692 Propagate this widget's palette to all children, except style sheet
1693 widgets, and windows that don't enable window propagation (palettes don't
1694 normally propagate to windows).
1696 void QWidgetPrivate::propagatePaletteChange()
1698 Q_Q(QWidget);
1699 // Propagate a new inherited mask to all children.
1700 if (!q->parentWidget() && extra && extra->proxyWidget) {
1701 #ifndef QT_NO_GRAPHICSVIEW
1702 QGraphicsProxyWidget *p = extra->proxyWidget;
1703 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1704 #endif //QT_NO_GRAPHICSVIEW
1705 } else if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1706 inheritedPaletteResolveMask = 0;
1708 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1710 QEvent pc(QEvent::PaletteChange);
1711 QApplication::sendEvent(q, &pc);
1712 for (int i = 0; i < children.size(); ++i) {
1713 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1714 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1715 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1716 QWidgetPrivate *wd = w->d_func();
1717 wd->inheritedPaletteResolveMask = mask;
1718 wd->resolvePalette();
1721 #if defined(QT3_SUPPORT)
1722 q->paletteChange(q->palette()); // compatibility
1723 #endif
1727 Returns the widget's clipping rectangle.
1729 QRect QWidgetPrivate::clipRect() const
1731 Q_Q(const QWidget);
1732 const QWidget * w = q;
1733 if (!w->isVisible())
1734 return QRect();
1735 QRect r = effectiveRectFor(q->rect());
1736 int ox = 0;
1737 int oy = 0;
1738 while (w
1739 && w->isVisible()
1740 && !w->isWindow()
1741 && w->parentWidget()) {
1742 ox -= w->x();
1743 oy -= w->y();
1744 w = w->parentWidget();
1745 r &= QRect(ox, oy, w->width(), w->height());
1747 return r;
1751 Returns the widget's clipping region (without siblings).
1753 QRegion QWidgetPrivate::clipRegion() const
1755 Q_Q(const QWidget);
1756 if (!q->isVisible())
1757 return QRegion();
1758 QRegion r(q->rect());
1759 const QWidget * w = q;
1760 const QWidget *ignoreUpTo;
1761 int ox = 0;
1762 int oy = 0;
1763 while (w
1764 && w->isVisible()
1765 && !w->isWindow()
1766 && w->parentWidget()) {
1767 ox -= w->x();
1768 oy -= w->y();
1769 ignoreUpTo = w;
1770 w = w->parentWidget();
1771 r &= QRegion(ox, oy, w->width(), w->height());
1773 int i = 0;
1774 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1776 for ( ; i < w->d_func()->children.size(); ++i) {
1777 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1778 if(sibling->isVisible() && !sibling->isWindow()) {
1779 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1780 sibling->width(), sibling->height());
1781 if (qRectIntersects(siblingRect, q->rect()))
1782 r -= QRegion(siblingRect);
1787 return r;
1790 void QWidgetPrivate::setDirtyOpaqueRegion()
1792 Q_Q(QWidget);
1794 dirtyOpaqueChildren = true;
1796 if (q->isWindow())
1797 return;
1799 QWidget *parent = q->parentWidget();
1800 if (!parent)
1801 return;
1803 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1804 QWidgetPrivate *pd = parent->d_func();
1805 if (!pd->dirtyOpaqueChildren)
1806 pd->setDirtyOpaqueRegion();
1809 QRegion QWidgetPrivate::getOpaqueRegion() const
1811 Q_Q(const QWidget);
1813 QRegion r = isOpaque ? q->rect() : getOpaqueChildren();
1814 if (extra && extra->hasMask)
1815 r &= extra->mask;
1816 if (r.isEmpty())
1817 return r;
1818 return r & clipRect();
1821 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1823 if (!dirtyOpaqueChildren)
1824 return opaqueChildren;
1826 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1827 that->opaqueChildren = QRegion();
1829 for (int i = 0; i < children.size(); ++i) {
1830 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1831 if (!child || !child->isVisible() || child->isWindow())
1832 continue;
1834 const QPoint offset = child->geometry().topLeft();
1835 that->opaqueChildren += child->d_func()->getOpaqueRegion().translated(offset);
1838 that->dirtyOpaqueChildren = false;
1840 return that->opaqueChildren;
1843 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1845 if (children.isEmpty() || clipRect.isEmpty())
1846 return;
1848 const QRegion &r = getOpaqueChildren();
1849 if (!r.isEmpty())
1850 source -= (r & clipRect);
1853 //subtract any relatives that are higher up than me --- this is too expensive !!!
1854 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1855 bool alsoNonOpaque) const
1857 Q_Q(const QWidget);
1858 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1859 if (disableSubtractOpaqueSiblings || q->isWindow())
1860 return;
1862 QRect clipBoundingRect;
1863 bool dirtyClipBoundingRect = true;
1865 QRegion parentClip;
1866 bool dirtyParentClip = true;
1868 QPoint parentOffset = data.crect.topLeft();
1870 const QWidget *w = q;
1872 while (w) {
1873 if (w->isWindow())
1874 break;
1875 QWidgetPrivate *pd = w->parentWidget()->d_func();
1876 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1877 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1878 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1879 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1880 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1881 continue;
1883 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1884 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1885 continue;
1887 if (dirtyClipBoundingRect) {
1888 clipBoundingRect = sourceRegion.boundingRect();
1889 dirtyClipBoundingRect = false;
1892 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1893 continue;
1895 if (dirtyParentClip) {
1896 parentClip = sourceRegion.translated(parentOffset);
1897 dirtyParentClip = false;
1900 const QPoint siblingPos(sibling->data->crect.topLeft());
1901 const QRect siblingClipRect(sibling->d_func()->clipRect());
1902 QRegion siblingDirty(parentClip);
1903 siblingDirty &= (siblingClipRect.translated(siblingPos));
1904 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1905 && !sibling->d_func()->graphicsEffect;
1906 if (hasMask)
1907 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1908 if (siblingDirty.isEmpty())
1909 continue;
1911 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1912 if (hasMask) {
1913 siblingDirty.translate(-parentOffset);
1914 sourceRegion -= siblingDirty;
1915 } else {
1916 sourceRegion -= siblingGeometry.translated(-parentOffset);
1918 } else {
1919 if (hasDirtySiblingsAbove)
1920 *hasDirtySiblingsAbove = true;
1921 if (sibling->d_func()->children.isEmpty())
1922 continue;
1923 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1924 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1925 sourceRegion -= opaqueSiblingChildren;
1927 if (sourceRegion.isEmpty())
1928 return;
1930 dirtyClipBoundingRect = true;
1931 dirtyParentClip = true;
1934 w = w->parentWidget();
1935 parentOffset += pd->data.crect.topLeft();
1936 dirtyParentClip = true;
1940 void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const
1942 Q_Q(const QWidget);
1944 const QWidget *w = q;
1945 QPoint offset;
1947 if (graphicsEffect) {
1948 w = q->parentWidget();
1949 offset -= data.crect.topLeft();
1952 while (w) {
1953 const QWidgetPrivate *wd = w->d_func();
1954 if (wd->extra && wd->extra->hasMask)
1955 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
1956 if (w->isWindow())
1957 return;
1958 offset -= wd->data.crect.topLeft();
1959 w = w->parentWidget();
1963 bool QWidgetPrivate::paintOnScreen() const
1965 #if defined(Q_WS_QWS)
1966 return false;
1967 #elif defined(QT_NO_BACKINGSTORE)
1968 return true;
1969 #else
1970 Q_Q(const QWidget);
1971 if (q->testAttribute(Qt::WA_PaintOnScreen)
1972 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
1973 return true;
1976 return !qt_enable_backingstore;
1977 #endif
1980 void QWidgetPrivate::updateIsOpaque()
1982 // hw: todo: only needed if opacity actually changed
1983 setDirtyOpaqueRegion();
1985 if (graphicsEffect) {
1986 // ### We should probably add QGraphicsEffect::isOpaque at some point.
1987 setOpaque(false);
1988 return;
1991 Q_Q(QWidget);
1992 #ifdef Q_WS_X11
1993 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
1994 setOpaque(false);
1995 return;
1997 #endif
1999 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2000 setOpaque(true);
2001 return;
2004 const QPalette &pal = q->palette();
2006 if (q->autoFillBackground()) {
2007 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2008 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2009 setOpaque(true);
2010 return;
2014 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2015 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2016 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2017 setOpaque(true);
2018 return;
2021 setOpaque(false);
2024 void QWidgetPrivate::setOpaque(bool opaque)
2026 if (isOpaque == opaque)
2027 return;
2028 isOpaque = opaque;
2029 #ifdef Q_WS_MAC
2030 macUpdateIsOpaque();
2031 #endif
2032 #ifdef Q_WS_X11
2033 x11UpdateIsOpaque();
2034 #endif
2035 #ifdef Q_WS_WIN
2036 winUpdateIsOpaque();
2037 #endif
2038 #ifdef Q_OS_SYMBIAN
2039 s60UpdateIsOpaque();
2040 #endif
2043 void QWidgetPrivate::updateIsTranslucent()
2045 #ifdef Q_WS_MAC
2046 macUpdateIsOpaque();
2047 #endif
2048 #ifdef Q_WS_X11
2049 x11UpdateIsOpaque();
2050 #endif
2051 #ifdef Q_WS_WIN
2052 winUpdateIsOpaque();
2053 #endif
2054 #ifdef Q_OS_SYMBIAN
2055 s60UpdateIsOpaque();
2056 #endif
2060 \fn void QPixmap::fill(const QWidget *widget, const QPoint &offset)
2062 Fills the pixmap with the \a widget's background color or pixmap
2063 according to the given offset.
2065 The QPoint \a offset defines a point in widget coordinates to
2066 which the pixmap's top-left pixel will be mapped to. This is only
2067 significant if the widget has a background pixmap; otherwise the
2068 pixmap will simply be filled with the background color of the
2069 widget.
2072 void QPixmap::fill( const QWidget *widget, const QPoint &off )
2074 QPainter p(this);
2075 p.translate(-off);
2076 widget->d_func()->paintBackground(&p, QRect(off, size()));
2079 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2081 Q_ASSERT(painter);
2083 if (brush.style() == Qt::TexturePattern) {
2084 #ifdef Q_WS_MAC
2085 // Optimize pattern filling on mac by using HITheme directly
2086 // when filling with the standard widget background.
2087 // Defined in qmacstyle_mac.cpp
2088 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2089 qt_mac_fill_background(painter, rgn, brush);
2090 #else
2091 #if !defined(QT_NO_STYLE_S60)
2092 // Defined in qs60style.cpp
2093 extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2094 if (!qt_s60_fill_background(painter, rgn, brush))
2095 #endif // !defined(QT_NO_STYLE_S60)
2097 const QRect rect(rgn.boundingRect());
2098 painter->setClipRegion(rgn);
2099 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2101 #endif // Q_WS_MAC
2102 } else {
2103 const QVector<QRect> &rects = rgn.rects();
2104 for (int i = 0; i < rects.size(); ++i)
2105 painter->fillRect(rects.at(i), brush);
2109 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2111 Q_Q(const QWidget);
2113 #ifndef QT_NO_SCROLLAREA
2114 bool resetBrushOrigin = false;
2115 QPointF oldBrushOrigin;
2116 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2117 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2118 if (scrollArea && scrollArea->viewport() == q) {
2119 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2120 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2121 oldBrushOrigin = painter->brushOrigin();
2122 resetBrushOrigin = true;
2123 painter->setBrushOrigin(-priv->contentsOffset());
2126 #endif // QT_NO_SCROLLAREA
2128 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2130 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2131 const QBrush bg = q->palette().brush(QPalette::Window);
2132 #ifdef Q_WS_QWS
2133 if (!(flags & DontSetCompositionMode) && painter->paintEngine()->hasFeature(QPaintEngine::PorterDuff))
2134 painter->setCompositionMode(QPainter::CompositionMode_Source); //copy alpha straight in
2135 #endif
2136 fillRegion(painter, rgn, bg);
2139 if (q->autoFillBackground())
2140 fillRegion(painter, rgn, autoFillBrush);
2143 if (q->testAttribute(Qt::WA_StyledBackground)) {
2144 painter->setClipRegion(rgn);
2145 QStyleOption opt;
2146 opt.initFrom(q);
2147 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2150 #ifndef QT_NO_SCROLLAREA
2151 if (resetBrushOrigin)
2152 painter->setBrushOrigin(oldBrushOrigin);
2153 #endif // QT_NO_SCROLLAREA
2157 \internal
2158 This function is called when a widget is hidden or destroyed.
2159 It resets some application global pointers that should only refer active,
2160 visible widgets.
2163 #ifdef Q_WS_MAC
2164 extern QPointer<QWidget> qt_button_down;
2165 #else
2166 extern QWidget *qt_button_down;
2167 #endif
2169 void QWidgetPrivate::deactivateWidgetCleanup()
2171 Q_Q(QWidget);
2172 // If this was the active application window, reset it
2173 if (QApplication::activeWindow() == q)
2174 QApplication::setActiveWindow(0);
2175 // If the is the active mouse press widget, reset it
2176 if (q == qt_button_down)
2177 qt_button_down = 0;
2182 Returns a pointer to the widget with window identifer/handle \a
2185 The window identifier type depends on the underlying window
2186 system, see \c qwindowdefs.h for the actual definition. If there
2187 is no widget with this identifier, 0 is returned.
2190 QWidget *QWidget::find(WId id)
2192 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2198 \fn WId QWidget::internalWinId() const
2199 \internal
2200 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2205 \fn WId QWidget::winId() const
2207 Returns the window system identifier of the widget.
2209 Portable in principle, but if you use it you are probably about to
2210 do something non-portable. Be careful.
2212 If a widget is non-native (alien) and winId() is invoked on it, that widget
2213 will be provided a native handle.
2215 On Mac OS X, the type returned depends on which framework Qt was linked
2216 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2217 is using Cocoa, {WId} is a pointer to an NSView.
2219 \note We recommend that you do not store this value as it is likely to
2220 change at run-time.
2222 \sa find()
2224 WId QWidget::winId() const
2226 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2227 QWidget *that = const_cast<QWidget*>(this);
2228 that->setAttribute(Qt::WA_NativeWindow);
2229 that->d_func()->createWinId();
2230 return that->data->winid;
2232 return data->winid;
2236 void QWidgetPrivate::createWinId(WId winid)
2238 Q_Q(QWidget);
2239 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2240 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2241 if (!q->isWindow()) {
2242 QWidget *parent = q->parentWidget();
2243 QWidgetPrivate *pd = parent->d_func();
2244 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2245 parent->setAttribute(Qt::WA_NativeWindow);
2246 if (!parent->internalWinId()) {
2247 pd->createWinId();
2250 for (int i = 0; i < pd->children.size(); ++i) {
2251 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2252 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2253 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2254 if (w!=q) {
2255 w->create();
2256 } else {
2257 w->create(winid);
2258 // if the window has already been created, we
2259 // need to raise it to its proper stacking position
2260 if (winid)
2261 w->raise();
2265 } else {
2266 q->create();
2273 \internal
2274 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2278 void QWidget::createWinId()
2280 Q_D(QWidget);
2281 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2282 d->createWinId();
2286 \since 4.4
2288 Returns the effective window system identifier of the widget, i.e. the
2289 native parent's window system identifier.
2291 If the widget is native, this function returns the native widget ID.
2292 Otherwise, the window ID of the first native parent widget, i.e., the
2293 top-level widget that contains this widget, is returned.
2295 \note We recommend that you do not store this value as it is likely to
2296 change at run-time.
2298 \sa nativeParentWidget()
2300 WId QWidget::effectiveWinId() const
2302 WId id = internalWinId();
2303 if (id || !testAttribute(Qt::WA_WState_Created))
2304 return id;
2305 QWidget *realParent = nativeParentWidget();
2306 Q_ASSERT(realParent);
2307 Q_ASSERT(realParent->internalWinId());
2308 return realParent->internalWinId();
2311 #ifndef QT_NO_STYLE_STYLESHEET
2314 \property QWidget::styleSheet
2315 \brief the widget's style sheet
2316 \since 4.2
2318 The style sheet contains a textual description of customizations to the
2319 widget's style, as described in the \l{Qt Style Sheets} document.
2321 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2323 \warning Qt style sheets are currently not supported for custom QStyle
2324 subclasses. We plan to address this in some future release.
2326 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2328 QString QWidget::styleSheet() const
2330 Q_D(const QWidget);
2331 if (!d->extra)
2332 return QString();
2333 return d->extra->styleSheet;
2336 void QWidget::setStyleSheet(const QString& styleSheet)
2338 Q_D(QWidget);
2339 d->createExtra();
2341 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2342 d->extra->styleSheet = styleSheet;
2343 if (styleSheet.isEmpty()) { // stylesheet removed
2344 if (!proxy)
2345 return;
2347 d->inheritStyle();
2348 return;
2351 if (proxy) { // style sheet update
2352 proxy->repolish(this);
2353 return;
2356 if (testAttribute(Qt::WA_SetStyle)) {
2357 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2358 } else {
2359 d->setStyle_helper(new QStyleSheetStyle(0), true);
2363 #endif // QT_NO_STYLE_STYLESHEET
2366 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2369 QStyle *QWidget::style() const
2371 Q_D(const QWidget);
2373 if (d->extra && d->extra->style)
2374 return d->extra->style;
2375 return QApplication::style();
2379 Sets the widget's GUI style to \a style. The ownership of the style
2380 object is not transferred.
2382 If no style is set, the widget uses the application's style,
2383 QApplication::style() instead.
2385 Setting a widget's style has no effect on existing or future child
2386 widgets.
2388 \warning This function is particularly useful for demonstration
2389 purposes, where you want to show Qt's styling capabilities. Real
2390 applications should avoid it and use one consistent GUI style
2391 instead.
2393 \warning Qt style sheets are currently not supported for custom QStyle
2394 subclasses. We plan to address this in some future release.
2396 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2399 void QWidget::setStyle(QStyle *style)
2401 Q_D(QWidget);
2402 setAttribute(Qt::WA_SetStyle, style != 0);
2403 d->createExtra();
2404 #ifndef QT_NO_STYLE_STYLESHEET
2405 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2406 //if for some reason someone try to set a QStyleSheetStyle, ref it
2407 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2408 proxy->ref();
2409 d->setStyle_helper(style, false);
2410 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2411 // if we have an application stylesheet or have a proxy already, propagate
2412 d->setStyle_helper(new QStyleSheetStyle(style), true);
2413 } else
2414 #endif
2415 d->setStyle_helper(style, false);
2418 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2419 #ifdef Q_WS_MAC
2420 metalHack
2421 #endif
2424 Q_Q(QWidget);
2425 QStyle *oldStyle = q->style();
2426 #ifndef QT_NO_STYLE_STYLESHEET
2427 QStyle *origStyle = 0;
2428 #endif
2430 #ifdef Q_WS_MAC
2431 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2432 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2433 // set when changing that attribute and passes the widget's CURRENT style.
2434 // therefore no need to do a reassignment.
2435 if (!metalHack)
2436 #endif
2438 createExtra();
2440 #ifndef QT_NO_STYLE_STYLESHEET
2441 origStyle = extra->style;
2442 #endif
2443 extra->style = newStyle;
2446 // repolish
2447 if (q->windowType() != Qt::Desktop) {
2448 if (polished) {
2449 oldStyle->unpolish(q);
2450 #ifdef Q_WS_MAC
2451 if (metalHack)
2452 macUpdateMetalAttribute();
2453 #endif
2454 q->style()->polish(q);
2455 #ifdef Q_WS_MAC
2456 } else if (metalHack) {
2457 macUpdateMetalAttribute();
2458 #endif
2462 if (propagate) {
2463 for (int i = 0; i < children.size(); ++i) {
2464 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2465 if (c)
2466 c->d_func()->inheritStyle();
2470 QEvent e(QEvent::StyleChange);
2471 QApplication::sendEvent(q, &e);
2472 #ifdef QT3_SUPPORT
2473 q->styleChange(*oldStyle);
2474 #endif
2476 #ifndef QT_NO_STYLE_STYLESHEET
2477 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2478 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle)) {
2479 cssStyle->clearWidgetFont(q);
2482 #endif
2484 #ifndef QT_NO_STYLE_STYLESHEET
2485 // dereference the old stylesheet style
2486 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle))
2487 proxy->deref();
2488 #endif
2491 // Inherits style from the current parent and propagates it as necessary
2492 void QWidgetPrivate::inheritStyle()
2494 #ifndef QT_NO_STYLE_STYLESHEET
2495 Q_Q(QWidget);
2497 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2499 if (!q->styleSheet().isEmpty()) {
2500 Q_ASSERT(proxy);
2501 proxy->repolish(q);
2502 return;
2505 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2506 QWidget *parent = q->parentWidget();
2507 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2508 // If we have stylesheet on app or parent has stylesheet style, we need
2509 // to be running a proxy
2510 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2511 QStyle *newStyle = parentStyle;
2512 if (q->testAttribute(Qt::WA_SetStyle))
2513 newStyle = new QStyleSheetStyle(origStyle);
2514 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2515 newProxy->ref();
2517 setStyle_helper(newStyle, true);
2518 return;
2521 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2522 // we just need our original style back
2523 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2524 return;
2526 // We could have inherited the proxy from our parent (which has a custom style)
2527 // In such a case we need to start following the application style (i.e revert
2528 // the propagation behavior of QStyleSheetStyle)
2529 if (!q->testAttribute(Qt::WA_SetStyle))
2530 origStyle = 0;
2532 setStyle_helper(origStyle, true);
2533 #endif // QT_NO_STYLE_STYLESHEET
2536 #ifdef QT3_SUPPORT
2538 \overload
2540 Sets the widget's GUI style to \a style using the QStyleFactory.
2542 QStyle* QWidget::setStyle(const QString &style)
2544 QStyle *s = QStyleFactory::create(style);
2545 setStyle(s);
2546 return s;
2548 #endif
2551 \fn bool QWidget::isWindow() const
2553 Returns true if the widget is an independent window, otherwise
2554 returns false.
2556 A window is a widget that isn't visually the child of any other
2557 widget and that usually has a frame and a
2558 \l{QWidget::setWindowTitle()}{window title}.
2560 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2561 It will then be grouped with its parent and deleted when the
2562 parent is deleted, minimized when the parent is minimized etc. If
2563 supported by the window manager, it will also have a common
2564 taskbar entry with its parent.
2566 QDialog and QMainWindow widgets are by default windows, even if a
2567 parent widget is specified in the constructor. This behavior is
2568 specified by the Qt::Window flag.
2570 \sa window(), isModal(), parentWidget()
2574 \property QWidget::modal
2575 \brief whether the widget is a modal widget
2577 This property only makes sense for windows. A modal widget
2578 prevents widgets in all other windows from getting any input.
2580 By default, this property is false.
2582 \sa isWindow(), windowModality, QDialog
2586 \property QWidget::windowModality
2587 \brief which windows are blocked by the modal widget
2588 \since 4.1
2590 This property only makes sense for windows. A modal widget
2591 prevents widgets in other windows from getting input. The value of
2592 this property controls which windows are blocked when the widget
2593 is visible. Changing this property while the window is visible has
2594 no effect; you must hide() the widget first, then show() it again.
2596 By default, this property is Qt::NonModal.
2598 \sa isWindow(), QWidget::modal, QDialog
2601 Qt::WindowModality QWidget::windowModality() const
2603 return static_cast<Qt::WindowModality>(data->window_modality);
2606 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2608 data->window_modality = windowModality;
2609 // setModal_sys() will be called by setAttribute()
2610 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2611 setAttribute(Qt::WA_SetWindowModality, true);
2615 \fn bool QWidget::underMouse() const
2617 Returns true if the widget is under the mouse cursor; otherwise
2618 returns false.
2620 This value is not updated properly during drag and drop
2621 operations.
2623 \sa enterEvent(), leaveEvent()
2627 \property QWidget::minimized
2628 \brief whether this widget is minimized (iconified)
2630 This property is only relevant for windows.
2632 By default, this property is false.
2634 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2636 bool QWidget::isMinimized() const
2637 { return data->window_state & Qt::WindowMinimized; }
2640 Shows the widget minimized, as an icon.
2642 Calling this function only affects \l{isWindow()}{windows}.
2644 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2645 isMinimized()
2647 void QWidget::showMinimized()
2649 bool isMin = isMinimized();
2650 if (isMin && isVisible())
2651 return;
2653 ensurePolished();
2654 #ifdef QT3_SUPPORT
2655 if (parent())
2656 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
2657 #endif
2659 if (!isMin)
2660 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2661 show();
2665 \property QWidget::maximized
2666 \brief whether this widget is maximized
2668 This property is only relevant for windows.
2670 \note Due to limitations on some window systems, this does not always
2671 report the expected results (e.g., if the user on X11 maximizes the
2672 window via the window manager, Qt has no way of distinguishing this
2673 from any other resize). This is expected to improve as window manager
2674 protocols evolve.
2676 By default, this property is false.
2678 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2680 bool QWidget::isMaximized() const
2681 { return data->window_state & Qt::WindowMaximized; }
2686 Returns the current window state. The window state is a OR'ed
2687 combination of Qt::WindowState: Qt::WindowMinimized,
2688 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2690 \sa Qt::WindowState setWindowState()
2692 Qt::WindowStates QWidget::windowState() const
2694 return Qt::WindowStates(data->window_state);
2697 /*!\internal
2699 The function sets the window state on child widgets similar to
2700 setWindowState(). The difference is that the window state changed
2701 event has the isOverride() flag set. It exists mainly to keep
2702 Q3Workspace working.
2704 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2706 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2707 data->window_state = newstate;
2708 QApplication::sendEvent(this, &e);
2712 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2714 Sets the window state to \a windowState. The window state is a OR'ed
2715 combination of Qt::WindowState: Qt::WindowMinimized,
2716 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2718 If the window is not visible (i.e. isVisible() returns false), the
2719 window state will take effect when show() is called. For visible
2720 windows, the change is immediate. For example, to toggle between
2721 full-screen and normal mode, use the following code:
2723 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2725 In order to restore and activate a minimized window (while
2726 preserving its maximized and/or full-screen state), use the following:
2728 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2730 Calling this function will hide the widget. You must call show() to make
2731 the widget visible again.
2733 \note On some window systems Qt::WindowActive is not immediate, and may be
2734 ignored in certain cases.
2736 When the window state changes, the widget receives a changeEvent()
2737 of type QEvent::WindowStateChange.
2739 \sa Qt::WindowState windowState()
2743 \property QWidget::fullScreen
2744 \brief whether the widget is shown in full screen mode
2746 A widget in full screen mode occupies the whole screen area and does not
2747 display window decorations, such as a title bar.
2749 By default, this property is false.
2751 \sa windowState(), minimized, maximized
2753 bool QWidget::isFullScreen() const
2754 { return data->window_state & Qt::WindowFullScreen; }
2757 Shows the widget in full-screen mode.
2759 Calling this function only affects \l{isWindow()}{windows}.
2761 To return from full-screen mode, call showNormal().
2763 Full-screen mode works fine under Windows, but has certain
2764 problems under X. These problems are due to limitations of the
2765 ICCCM protocol that specifies the communication between X11
2766 clients and the window manager. ICCCM simply does not understand
2767 the concept of non-decorated full-screen windows. Therefore, the
2768 best we can do is to request a borderless window and place and
2769 resize it to fill the entire screen. Depending on the window
2770 manager, this may or may not work. The borderless window is
2771 requested using MOTIF hints, which are at least partially
2772 supported by virtually all modern window managers.
2774 An alternative would be to bypass the window manager entirely and
2775 create a window with the Qt::X11BypassWindowManagerHint flag. This
2776 has other severe problems though, like totally broken keyboard focus
2777 and very strange effects on desktop changes or when the user raises
2778 other windows.
2780 X11 window managers that follow modern post-ICCCM specifications
2781 support full-screen mode properly.
2783 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2785 void QWidget::showFullScreen()
2787 ensurePolished();
2788 #ifdef QT3_SUPPORT
2789 if (parent())
2790 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
2791 #endif
2793 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2794 | Qt::WindowFullScreen);
2795 show();
2796 activateWindow();
2800 Shows the widget maximized.
2802 Calling this function only affects \l{isWindow()}{windows}.
2804 On X11, this function may not work properly with certain window
2805 managers. See the \l{Window Geometry} documentation for an explanation.
2807 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2809 void QWidget::showMaximized()
2811 ensurePolished();
2812 #ifdef QT3_SUPPORT
2813 if (parent())
2814 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
2815 #endif
2817 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2818 | Qt::WindowMaximized);
2819 show();
2823 Restores the widget after it has been maximized or minimized.
2825 Calling this function only affects \l{isWindow()}{windows}.
2827 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2829 void QWidget::showNormal()
2831 ensurePolished();
2832 #ifdef QT3_SUPPORT
2833 if (parent())
2834 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
2835 #endif
2837 setWindowState(windowState() & ~(Qt::WindowMinimized
2838 | Qt::WindowMaximized
2839 | Qt::WindowFullScreen));
2840 show();
2844 Returns true if this widget would become enabled if \a ancestor is
2845 enabled; otherwise returns false.
2849 This is the case if neither the widget itself nor every parent up
2850 to but excluding \a ancestor has been explicitly disabled.
2852 isEnabledTo(0) is equivalent to isEnabled().
2854 \sa setEnabled() enabled
2857 bool QWidget::isEnabledTo(QWidget* ancestor) const
2859 const QWidget * w = this;
2860 while (!w->testAttribute(Qt::WA_ForceDisabled)
2861 && !w->isWindow()
2862 && w->parentWidget()
2863 && w->parentWidget() != ancestor)
2864 w = w->parentWidget();
2865 return !w->testAttribute(Qt::WA_ForceDisabled);
2868 #ifndef QT_NO_ACTION
2870 Appends the action \a action to this widget's list of actions.
2872 All QWidgets have a list of \l{QAction}s, however they can be
2873 represented graphically in many different ways. The default use of
2874 the QAction list (as returned by actions()) is to create a context
2875 QMenu.
2877 A QWidget should only have one of each action and adding an action
2878 it already has will not cause the same action to be in the widget twice.
2880 The ownership of \a action is not transferred to this QWidget.
2882 \sa removeAction(), insertAction(), actions(), QMenu
2884 void QWidget::addAction(QAction *action)
2886 insertAction(0, action);
2890 Appends the actions \a actions to this widget's list of actions.
2892 \sa removeAction(), QMenu, addAction()
2894 void QWidget::addActions(QList<QAction*> actions)
2896 for(int i = 0; i < actions.count(); i++)
2897 insertAction(0, actions.at(i));
2901 Inserts the action \a action to this widget's list of actions,
2902 before the action \a before. It appends the action if \a before is 0 or
2903 \a before is not a valid action for this widget.
2905 A QWidget should only have one of each action.
2907 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2909 void QWidget::insertAction(QAction *before, QAction *action)
2911 if(!action) {
2912 qWarning("QWidget::insertAction: Attempt to insert null action");
2913 return;
2916 Q_D(QWidget);
2917 if(d->actions.contains(action))
2918 removeAction(action);
2920 int pos = d->actions.indexOf(before);
2921 if (pos < 0) {
2922 before = 0;
2923 pos = d->actions.size();
2925 d->actions.insert(pos, action);
2927 QActionPrivate *apriv = action->d_func();
2928 apriv->widgets.append(this);
2930 QActionEvent e(QEvent::ActionAdded, action, before);
2931 QApplication::sendEvent(this, &e);
2935 Inserts the actions \a actions to this widget's list of actions,
2936 before the action \a before. It appends the action if \a before is 0 or
2937 \a before is not a valid action for this widget.
2939 A QWidget can have at most one of each action.
2941 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2943 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2945 for(int i = 0; i < actions.count(); ++i)
2946 insertAction(before, actions.at(i));
2950 Removes the action \a action from this widget's list of actions.
2951 \sa insertAction(), actions(), insertAction()
2953 void QWidget::removeAction(QAction *action)
2955 if (!action)
2956 return;
2958 Q_D(QWidget);
2960 QActionPrivate *apriv = action->d_func();
2961 apriv->widgets.removeAll(this);
2963 if (d->actions.removeAll(action)) {
2964 QActionEvent e(QEvent::ActionRemoved, action);
2965 QApplication::sendEvent(this, &e);
2970 Returns the (possibly empty) list of this widget's actions.
2972 \sa contextMenuPolicy, insertAction(), removeAction()
2974 QList<QAction*> QWidget::actions() const
2976 Q_D(const QWidget);
2977 return d->actions;
2979 #endif // QT_NO_ACTION
2982 \fn bool QWidget::isEnabledToTLW() const
2983 \obsolete
2985 This function is deprecated. It is equivalent to isEnabled()
2989 \property QWidget::enabled
2990 \brief whether the widget is enabled
2992 An enabled widget handles keyboard and mouse events; a disabled
2993 widget does not.
2995 Some widgets display themselves differently when they are
2996 disabled. For example a button might draw its label grayed out. If
2997 your widget needs to know when it becomes enabled or disabled, you
2998 can use the changeEvent() with type QEvent::EnabledChange.
3000 Disabling a widget implicitly disables all its children. Enabling
3001 respectively enables all child widgets unless they have been
3002 explicitly disabled.
3004 By default, this property is true.
3006 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3008 void QWidget::setEnabled(bool enable)
3010 Q_D(QWidget);
3011 setAttribute(Qt::WA_ForceDisabled, !enable);
3012 d->setEnabled_helper(enable);
3015 void QWidgetPrivate::setEnabled_helper(bool enable)
3017 Q_Q(QWidget);
3019 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3020 return; // nothing we can do
3022 if (enable != q->testAttribute(Qt::WA_Disabled))
3023 return; // nothing to do
3025 q->setAttribute(Qt::WA_Disabled, !enable);
3026 updateSystemBackground();
3028 if (!enable && q->window()->focusWidget() == q) {
3029 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3030 if (!parentIsEnabled || !q->focusNextChild())
3031 q->clearFocus();
3034 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3035 for (int i = 0; i < children.size(); ++i) {
3036 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3037 if (w && !w->testAttribute(attribute))
3038 w->d_func()->setEnabled_helper(enable);
3040 #if defined(Q_WS_X11)
3041 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3042 // enforce the windows behavior of clearing the cursor on
3043 // disabled widgets
3044 extern void qt_x11_enforce_cursor(QWidget * w); // defined in qwidget_x11.cpp
3045 qt_x11_enforce_cursor(q);
3047 #endif
3048 #if defined(Q_WS_MAC)
3049 setEnabled_helper_sys(enable);
3050 #endif
3051 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3052 QInputContext *qic = inputContext();
3053 if (enable) {
3054 qic->setFocusWidget(q);
3055 } else {
3056 qic->reset();
3057 qic->setFocusWidget(0);
3060 QEvent e(QEvent::EnabledChange);
3061 QApplication::sendEvent(q, &e);
3062 #ifdef QT3_SUPPORT
3063 q->enabledChange(!enable); // compatibility
3064 #endif
3068 \property QWidget::acceptDrops
3069 \brief whether drop events are enabled for this widget
3071 Setting this property to true announces to the system that this
3072 widget \e may be able to accept drop events.
3074 If the widget is the desktop (windowType() == Qt::Desktop), this may
3075 fail if another application is using the desktop; you can call
3076 acceptDrops() to test if this occurs.
3078 \warning Do not modify this property in a drag and drop event handler.
3080 By default, this property is false.
3082 \sa {Drag and Drop}
3084 bool QWidget::acceptDrops() const
3086 return testAttribute(Qt::WA_AcceptDrops);
3089 void QWidget::setAcceptDrops(bool on)
3091 setAttribute(Qt::WA_AcceptDrops, on);
3096 \fn void QWidget::enabledChange(bool)
3098 \internal
3099 \obsolete
3103 \fn void QWidget::paletteChange(const QPalette &)
3105 \internal
3106 \obsolete
3110 \fn void QWidget::fontChange(const QFont &)
3112 \internal
3113 \obsolete
3117 \fn void QWidget::windowActivationChange(bool)
3119 \internal
3120 \obsolete
3124 \fn void QWidget::languageChange()
3126 \obsolete
3130 \fn void QWidget::styleChange(QStyle& style)
3132 \internal
3133 \obsolete
3137 Disables widget input events if \a disable is true; otherwise
3138 enables input events.
3140 See the \l enabled documentation for more information.
3142 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3144 void QWidget::setDisabled(bool disable)
3146 setEnabled(!disable);
3150 \property QWidget::frameGeometry
3151 \brief geometry of the widget relative to its parent including any
3152 window frame
3154 See the \l{Window Geometry} documentation for an overview of geometry
3155 issues with windows.
3157 By default, this property contains a value that depends on the user's
3158 platform and screen geometry.
3160 \sa geometry() x() y() pos()
3162 QRect QWidget::frameGeometry() const
3164 Q_D(const QWidget);
3165 if (isWindow() && ! (windowType() == Qt::Popup)) {
3166 QRect fs = d->frameStrut();
3167 return QRect(data->crect.x() - fs.left(),
3168 data->crect.y() - fs.top(),
3169 data->crect.width() + fs.left() + fs.right(),
3170 data->crect.height() + fs.top() + fs.bottom());
3172 return data->crect;
3176 \property QWidget::x
3178 \brief the x coordinate of the widget relative to its parent including
3179 any window frame
3181 See the \l{Window Geometry} documentation for an overview of geometry
3182 issues with windows.
3184 By default, this property has a value of 0.
3186 \sa frameGeometry, y, pos
3188 int QWidget::x() const
3190 Q_D(const QWidget);
3191 if (isWindow() && ! (windowType() == Qt::Popup))
3192 return data->crect.x() - d->frameStrut().left();
3193 return data->crect.x();
3197 \property QWidget::y
3198 \brief the y coordinate of the widget relative to its parent and
3199 including any window frame
3201 See the \l{Window Geometry} documentation for an overview of geometry
3202 issues with windows.
3204 By default, this property has a value of 0.
3206 \sa frameGeometry, x, pos
3208 int QWidget::y() const
3210 Q_D(const QWidget);
3211 if (isWindow() && ! (windowType() == Qt::Popup))
3212 return data->crect.y() - d->frameStrut().top();
3213 return data->crect.y();
3217 \property QWidget::pos
3218 \brief the position of the widget within its parent widget
3220 If the widget is a window, the position is that of the widget on
3221 the desktop, including its frame.
3223 When changing the position, the widget, if visible, receives a
3224 move event (moveEvent()) immediately. If the widget is not
3225 currently visible, it is guaranteed to receive an event before it
3226 is shown.
3228 By default, this property contains a position that refers to the
3229 origin.
3231 \warning Calling move() or setGeometry() inside moveEvent() can
3232 lead to infinite recursion.
3234 See the \l{Window Geometry} documentation for an overview of geometry
3235 issues with windows.
3237 \sa frameGeometry, size x(), y()
3239 QPoint QWidget::pos() const
3241 Q_D(const QWidget);
3242 if (isWindow() && ! (windowType() == Qt::Popup)) {
3243 QRect fs = d->frameStrut();
3244 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3246 return data->crect.topLeft();
3250 \property QWidget::geometry
3251 \brief the geometry of the widget relative to its parent and
3252 excluding the window frame
3254 When changing the geometry, the widget, if visible, receives a
3255 move event (moveEvent()) and/or a resize event (resizeEvent())
3256 immediately. If the widget is not currently visible, it is
3257 guaranteed to receive appropriate events before it is shown.
3259 The size component is adjusted if it lies outside the range
3260 defined by minimumSize() and maximumSize().
3262 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3263 can lead to infinite recursion.
3265 See the \l{Window Geometry} documentation for an overview of geometry
3266 issues with windows.
3268 By default, this property contains a value that depends on the user's
3269 platform and screen geometry.
3271 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3272 resizeEvent(), minimumSize(), maximumSize()
3276 \property QWidget::normalGeometry
3278 \brief the geometry of the widget as it will appear when shown as
3279 a normal (not maximized or full screen) top-level widget
3281 For child widgets this property always holds an empty rectangle.
3283 By default, this property contains an empty rectangle.
3285 \sa QWidget::windowState(), QWidget::geometry
3289 \property QWidget::size
3290 \brief the size of the widget excluding any window frame
3292 If the widget is visible when it is being resized, it receives a resize event
3293 (resizeEvent()) immediately. If the widget is not currently
3294 visible, it is guaranteed to receive an event before it is shown.
3296 The size is adjusted if it lies outside the range defined by
3297 minimumSize() and maximumSize().
3299 By default, this property contains a value that depends on the user's
3300 platform and screen geometry.
3302 \warning Calling resize() or setGeometry() inside resizeEvent() can
3303 lead to infinite recursion.
3305 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3306 appear on screen. This also applies to windows.
3308 \sa pos, geometry, minimumSize, maximumSize, resizeEvent()
3312 \property QWidget::width
3313 \brief the width of the widget excluding any window frame
3315 See the \l{Window Geometry} documentation for an overview of geometry
3316 issues with windows.
3318 \note Do not use this function to find the width of a screen on
3319 a \l{QDesktopWidget}{multiple screen desktop}. Read
3320 \l{multiple screens note}{this note} for details.
3322 By default, this property contains a value that depends on the user's
3323 platform and screen geometry.
3325 \sa geometry, height, size
3329 \property QWidget::height
3330 \brief the height of the widget excluding any window frame
3332 See the \l{Window Geometry} documentation for an overview of geometry
3333 issues with windows.
3335 \note Do not use this function to find the height of a screen
3336 on a \l {QDesktopWidget} {multiple screen desktop}. Read
3337 \l {multiple screens note} {this note} for details.
3339 By default, this property contains a value that depends on the user's
3340 platform and screen geometry.
3342 \sa geometry, width, size
3346 \property QWidget::rect
3347 \brief the internal geometry of the widget excluding any window
3348 frame
3350 The rect property equals QRect(0, 0, width(), height()).
3352 See the \l{Window Geometry} documentation for an overview of geometry
3353 issues with windows.
3355 By default, this property contains a value that depends on the user's
3356 platform and screen geometry.
3358 \sa size
3362 QRect QWidget::normalGeometry() const
3364 Q_D(const QWidget);
3365 if (!d->extra || !d->extra->topextra)
3366 return QRect();
3368 if (!isMaximized() && !isFullScreen())
3369 return geometry();
3371 return d->topData()->normalGeometry;
3376 \property QWidget::childrenRect
3377 \brief the bounding rectangle of the widget's children
3379 Hidden children are excluded.
3381 By default, for a widget with no children, this property contains a
3382 rectangle with zero width and height located at the origin.
3384 \sa childrenRegion() geometry()
3387 QRect QWidget::childrenRect() const
3389 Q_D(const QWidget);
3390 QRect r(0, 0, 0, 0);
3391 for (int i = 0; i < d->children.size(); ++i) {
3392 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3393 if (w && !w->isWindow() && !w->isHidden())
3394 r |= w->geometry();
3396 return r;
3400 \property QWidget::childrenRegion
3401 \brief the combined region occupied by the widget's children
3403 Hidden children are excluded.
3405 By default, for a widget with no children, this property contains an
3406 empty region.
3408 \sa childrenRect() geometry() mask()
3411 QRegion QWidget::childrenRegion() const
3413 Q_D(const QWidget);
3414 QRegion r;
3415 for (int i = 0; i < d->children.size(); ++i) {
3416 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3417 if (w && !w->isWindow() && !w->isHidden()) {
3418 QRegion mask = w->mask();
3419 if (mask.isEmpty())
3420 r |= w->geometry();
3421 else
3422 r |= mask.translated(w->pos());
3425 return r;
3430 \property QWidget::minimumSize
3431 \brief the widget's minimum size
3433 The widget cannot be resized to a smaller size than the minimum
3434 widget size. The widget's size is forced to the minimum size if
3435 the current size is smaller.
3437 The minimum size set by this function will override the minimum size
3438 defined by QLayout. In order to unset the minimum size, use a
3439 value of \c{QSize(0, 0)}.
3441 By default, this property contains a size with zero width and height.
3443 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3446 QSize QWidget::minimumSize() const
3448 Q_D(const QWidget);
3449 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3453 \property QWidget::maximumSize
3454 \brief the widget's maximum size in pixels
3456 The widget cannot be resized to a larger size than the maximum
3457 widget size.
3459 By default, this property contains a size in which both width and height
3460 have values of 16777215.
3462 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3463 of widgets.
3465 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3468 QSize QWidget::maximumSize() const
3470 Q_D(const QWidget);
3471 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3472 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3477 \property QWidget::minimumWidth
3478 \brief the widget's minimum width in pixels
3480 This property corresponds to the width held by the \l minimumSize property.
3482 By default, this property has a value of 0.
3484 \sa minimumSize, minimumHeight
3488 \property QWidget::minimumHeight
3489 \brief the widget's minimum height in pixels
3491 This property corresponds to the height held by the \l minimumSize property.
3493 By default, this property has a value of 0.
3495 \sa minimumSize, minimumWidth
3499 \property QWidget::maximumWidth
3500 \brief the widget's maximum width in pixels
3502 This property corresponds to the width held by the \l maximumSize property.
3504 By default, this property contains a value of 16777215.
3506 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3507 of widgets.
3509 \sa maximumSize, maximumHeight
3513 \property QWidget::maximumHeight
3514 \brief the widget's maximum height in pixels
3516 This property corresponds to the height held by the \l maximumSize property.
3518 By default, this property contains a value of 16777215.
3520 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3521 of widgets.
3523 \sa maximumSize, maximumWidth
3527 \property QWidget::sizeIncrement
3528 \brief the size increment of the widget
3530 When the user resizes the window, the size will move in steps of
3531 sizeIncrement().width() pixels horizontally and
3532 sizeIncrement.height() pixels vertically, with baseSize() as the
3533 basis. Preferred widget sizes are for non-negative integers \e i
3534 and \e j:
3535 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3537 Note that while you can set the size increment for all widgets, it
3538 only affects windows.
3540 By default, this property contains a size with zero width and height.
3542 \warning The size increment has no effect under Windows, and may
3543 be disregarded by the window manager on X11.
3545 \sa size, minimumSize, maximumSize
3547 QSize QWidget::sizeIncrement() const
3549 Q_D(const QWidget);
3550 return (d->extra && d->extra->topextra)
3551 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3552 : QSize(0, 0);
3556 \property QWidget::baseSize
3557 \brief the base size of the widget
3559 The base size is used to calculate a proper widget size if the
3560 widget defines sizeIncrement().
3562 By default, for a newly-created widget, this property contains a size with
3563 zero width and height.
3565 \sa setSizeIncrement()
3568 QSize QWidget::baseSize() const
3570 Q_D(const QWidget);
3571 return (d->extra != 0 && d->extra->topextra != 0)
3572 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3573 : QSize(0, 0);
3576 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3578 Q_Q(QWidget);
3580 #ifdef Q_WS_QWS
3581 if (q->isWindow()) {
3582 const QRect maxWindowRect = QApplication::desktop()->availableGeometry(QApplication::desktop()->screenNumber(q));
3583 if (!maxWindowRect.isEmpty()) {
3584 // ### This is really just a work-around. Layout shouldn't be
3585 // asking for minimum sizes bigger than the screen.
3586 if (minw > maxWindowRect.width())
3587 minw = maxWindowRect.width();
3588 if (minh > maxWindowRect.height())
3589 minh = maxWindowRect.height();
3592 #endif
3593 int mw = minw, mh = minh;
3594 if (mw == QWIDGETSIZE_MAX)
3595 mw = 0;
3596 if (mh == QWIDGETSIZE_MAX)
3597 mh = 0;
3598 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3599 qWarning("QWidget::setMinimumSize: (%s/%s) "
3600 "The largest allowed size is (%d,%d)",
3601 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3602 QWIDGETSIZE_MAX);
3603 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3604 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3606 if (minw < 0 || minh < 0) {
3607 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3608 "are not possible",
3609 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3610 minw = mw = qMax(minw, 0);
3611 minh = mh = qMax(minh, 0);
3613 createExtra();
3614 if (extra->minw == mw && extra->minh == mh)
3615 return false;
3616 extra->minw = mw;
3617 extra->minh = mh;
3618 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3619 return true;
3623 \overload
3625 This function corresponds to setMinimumSize(QSize(minw, minh)).
3626 Sets the minimum width to \a minw and the minimum height to \a
3627 minh.
3630 void QWidget::setMinimumSize(int minw, int minh)
3632 Q_D(QWidget);
3633 if (!d->setMinimumSize_helper(minw, minh))
3634 return;
3636 if (isWindow())
3637 d->setConstraints_sys();
3638 if (minw > width() || minh > height()) {
3639 bool resized = testAttribute(Qt::WA_Resized);
3640 bool maximized = isMaximized();
3641 resize(qMax(minw,width()), qMax(minh,height()));
3642 setAttribute(Qt::WA_Resized, resized); //not a user resize
3643 if (maximized)
3644 data->window_state = data->window_state | Qt::WindowMaximized;
3646 #ifndef QT_NO_GRAPHICSVIEW
3647 if (d->extra) {
3648 if (d->extra->proxyWidget)
3649 d->extra->proxyWidget->setMinimumSize(minw, minh);
3651 #endif
3652 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3655 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3657 Q_Q(QWidget);
3658 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3659 qWarning("QWidget::setMaximumSize: (%s/%s) "
3660 "The largest allowed size is (%d,%d)",
3661 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3662 QWIDGETSIZE_MAX);
3663 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3664 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3666 if (maxw < 0 || maxh < 0) {
3667 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3668 "are not possible",
3669 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3670 maxw = qMax(maxw, 0);
3671 maxh = qMax(maxh, 0);
3673 createExtra();
3674 if (extra->maxw == maxw && extra->maxh == maxh)
3675 return false;
3676 extra->maxw = maxw;
3677 extra->maxh = maxh;
3678 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3679 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3680 return true;
3684 \overload
3686 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3687 maxh)). Sets the maximum width to \a maxw and the maximum height
3688 to \a maxh.
3690 void QWidget::setMaximumSize(int maxw, int maxh)
3692 Q_D(QWidget);
3693 if (!d->setMaximumSize_helper(maxw, maxh))
3694 return;
3696 if (isWindow())
3697 d->setConstraints_sys();
3698 if (maxw < width() || maxh < height()) {
3699 bool resized = testAttribute(Qt::WA_Resized);
3700 resize(qMin(maxw,width()), qMin(maxh,height()));
3701 setAttribute(Qt::WA_Resized, resized); //not a user resize
3704 #ifndef QT_NO_GRAPHICSVIEW
3705 if (d->extra) {
3706 if (d->extra->proxyWidget)
3707 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3709 #endif
3711 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3715 \overload
3717 Sets the x (width) size increment to \a w and the y (height) size
3718 increment to \a h.
3720 void QWidget::setSizeIncrement(int w, int h)
3722 Q_D(QWidget);
3723 d->createTLExtra();
3724 QTLWExtra* x = d->topData();
3725 if (x->incw == w && x->inch == h)
3726 return;
3727 x->incw = w;
3728 x->inch = h;
3729 if (isWindow())
3730 d->setConstraints_sys();
3734 \overload
3736 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3737 the widgets base size to width \a basew and height \a baseh.
3739 void QWidget::setBaseSize(int basew, int baseh)
3741 Q_D(QWidget);
3742 d->createTLExtra();
3743 QTLWExtra* x = d->topData();
3744 if (x->basew == basew && x->baseh == baseh)
3745 return;
3746 x->basew = basew;
3747 x->baseh = baseh;
3748 if (isWindow())
3749 d->setConstraints_sys();
3753 Sets both the minimum and maximum sizes of the widget to \a s,
3754 thereby preventing it from ever growing or shrinking.
3756 This will override the default size constraints set by QLayout.
3758 To remove constraints, set the size to QWIDGETSIZE_MAX.
3760 Alternatively, if you want the widget to have a
3761 fixed size based on its contents, you can call
3762 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3764 \sa maximumSize, minimumSize
3767 void QWidget::setFixedSize(const QSize & s)
3769 setFixedSize(s.width(), s.height());
3774 \fn void QWidget::setFixedSize(int w, int h)
3775 \overload
3777 Sets the width of the widget to \a w and the height to \a h.
3780 void QWidget::setFixedSize(int w, int h)
3782 Q_D(QWidget);
3783 #ifdef Q_WS_QWS
3784 // temporary fix for 4.3.x.
3785 // Should move the embedded spesific contraints in setMinimumSize_helper into QLayout
3786 int tmpW = w;
3787 int tmpH = h;
3788 bool minSizeSet = d->setMinimumSize_helper(tmpW, tmpH);
3789 #else
3790 bool minSizeSet = d->setMinimumSize_helper(w, h);
3791 #endif
3792 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3793 if (!minSizeSet && !maxSizeSet)
3794 return;
3796 if (isWindow())
3797 d->setConstraints_sys();
3798 else
3799 d->updateGeometry_helper(true);
3801 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3802 resize(w, h);
3805 void QWidget::setMinimumWidth(int w)
3807 Q_D(QWidget);
3808 d->createExtra();
3809 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3810 setMinimumSize(w, minimumSize().height());
3811 d->extra->explicitMinSize = expl;
3814 void QWidget::setMinimumHeight(int h)
3816 Q_D(QWidget);
3817 d->createExtra();
3818 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3819 setMinimumSize(minimumSize().width(), h);
3820 d->extra->explicitMinSize = expl;
3823 void QWidget::setMaximumWidth(int w)
3825 Q_D(QWidget);
3826 d->createExtra();
3827 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3828 setMaximumSize(w, maximumSize().height());
3829 d->extra->explicitMaxSize = expl;
3832 void QWidget::setMaximumHeight(int h)
3834 Q_D(QWidget);
3835 d->createExtra();
3836 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3837 setMaximumSize(maximumSize().width(), h);
3838 d->extra->explicitMaxSize = expl;
3842 Sets both the minimum and maximum width of the widget to \a w
3843 without changing the heights. Provided for convenience.
3845 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3848 void QWidget::setFixedWidth(int w)
3850 Q_D(QWidget);
3851 d->createExtra();
3852 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3853 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3854 setMinimumSize(w, minimumSize().height());
3855 setMaximumSize(w, maximumSize().height());
3856 d->extra->explicitMinSize = explMin;
3857 d->extra->explicitMaxSize = explMax;
3862 Sets both the minimum and maximum heights of the widget to \a h
3863 without changing the widths. Provided for convenience.
3865 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3868 void QWidget::setFixedHeight(int h)
3870 Q_D(QWidget);
3871 d->createExtra();
3872 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3873 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3874 setMinimumSize(minimumSize().width(), h);
3875 setMaximumSize(maximumSize().width(), h);
3876 d->extra->explicitMinSize = explMin;
3877 d->extra->explicitMaxSize = explMax;
3882 Translates the widget coordinate \a pos to the coordinate system
3883 of \a parent. The \a parent must not be 0 and must be a parent
3884 of the calling widget.
3886 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3889 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3891 QPoint p = pos;
3892 if (parent) {
3893 const QWidget * w = this;
3894 while (w != parent) {
3895 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3896 "parent must be in parent hierarchy");
3897 p = w->mapToParent(p);
3898 w = w->parentWidget();
3901 return p;
3906 Translates the widget coordinate \a pos from the coordinate system
3907 of \a parent to this widget's coordinate system. The \a parent
3908 must not be 0 and must be a parent of the calling widget.
3910 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3913 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3915 QPoint p(pos);
3916 if (parent) {
3917 const QWidget * w = this;
3918 while (w != parent) {
3919 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3920 "parent must be in parent hierarchy");
3922 p = w->mapFromParent(p);
3923 w = w->parentWidget();
3926 return p;
3931 Translates the widget coordinate \a pos to a coordinate in the
3932 parent widget.
3934 Same as mapToGlobal() if the widget has no parent.
3936 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3939 QPoint QWidget::mapToParent(const QPoint &pos) const
3941 return pos + data->crect.topLeft();
3945 Translates the parent widget coordinate \a pos to widget
3946 coordinates.
3948 Same as mapFromGlobal() if the widget has no parent.
3950 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3953 QPoint QWidget::mapFromParent(const QPoint &pos) const
3955 return pos - data->crect.topLeft();
3960 Returns the window for this widget, i.e. the next ancestor widget
3961 that has (or could have) a window-system frame.
3963 If the widget is a window, the widget itself is returned.
3965 Typical usage is changing the window title:
3967 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3969 \sa isWindow()
3972 QWidget *QWidget::window() const
3974 QWidget *w = (QWidget *)this;
3975 QWidget *p = w->parentWidget();
3976 while (!w->isWindow() && p) {
3977 w = p;
3978 p = p->parentWidget();
3980 return w;
3984 \since 4.4
3986 Returns the native parent for this widget, i.e. the next ancestor widget
3987 that has a system identifier, or 0 if it does not have any native parent.
3989 \sa effectiveWinId()
3991 QWidget *QWidget::nativeParentWidget() const
3993 QWidget *parent = parentWidget();
3994 while (parent && !parent->internalWinId())
3995 parent = parent->parentWidget();
3996 return parent;
3999 /*! \fn QWidget *QWidget::topLevelWidget() const
4000 \obsolete
4002 Use window() instead.
4005 #ifdef QT3_SUPPORT
4007 Returns the color role used for painting the widget's background.
4009 Use QPalette(backgroundRole(()) instead.
4011 Qt::BackgroundMode QWidget::backgroundMode() const
4013 if (testAttribute(Qt::WA_NoSystemBackground))
4014 return Qt::NoBackground;
4015 switch(backgroundRole()) {
4016 case QPalette::WindowText:
4017 return Qt::PaletteForeground;
4018 case QPalette::Button:
4019 return Qt::PaletteButton;
4020 case QPalette::Light:
4021 return Qt::PaletteLight;
4022 case QPalette::Midlight:
4023 return Qt::PaletteMidlight;
4024 case QPalette::Dark:
4025 return Qt::PaletteDark;
4026 case QPalette::Mid:
4027 return Qt::PaletteMid;
4028 case QPalette::Text:
4029 return Qt::PaletteText;
4030 case QPalette::BrightText:
4031 return Qt::PaletteBrightText;
4032 case QPalette::Base:
4033 return Qt::PaletteBase;
4034 case QPalette::Window:
4035 return Qt::PaletteBackground;
4036 case QPalette::Shadow:
4037 return Qt::PaletteShadow;
4038 case QPalette::Highlight:
4039 return Qt::PaletteHighlight;
4040 case QPalette::HighlightedText:
4041 return Qt::PaletteHighlightedText;
4042 case QPalette::ButtonText:
4043 return Qt::PaletteButtonText;
4044 case QPalette::Link:
4045 return Qt::PaletteLink;
4046 case QPalette::LinkVisited:
4047 return Qt::PaletteLinkVisited;
4048 default:
4049 break;
4051 return Qt::NoBackground;
4055 \fn void QWidget::setBackgroundMode(Qt::BackgroundMode
4056 widgetBackground, Qt::BackgroundMode paletteBackground)
4058 Sets the color role used for painting the widget's background to
4059 background mode \a widgetBackground. The \a paletteBackground mode
4060 parameter is ignored.
4062 void QWidget::setBackgroundMode(Qt::BackgroundMode m, Qt::BackgroundMode)
4064 Q_D(QWidget);
4065 if(m == Qt::NoBackground) {
4066 setAttribute(Qt::WA_NoSystemBackground, true);
4067 return;
4069 setAttribute(Qt::WA_NoSystemBackground, false);
4070 d->fg_role = QPalette::NoRole;
4071 QPalette::ColorRole role = d->bg_role;
4072 switch(m) {
4073 case Qt::FixedColor:
4074 case Qt::FixedPixmap:
4075 break;
4076 case Qt::PaletteForeground:
4077 role = QPalette::WindowText;
4078 break;
4079 case Qt::PaletteButton:
4080 role = QPalette::Button;
4081 break;
4082 case Qt::PaletteLight:
4083 role = QPalette::Light;
4084 break;
4085 case Qt::PaletteMidlight:
4086 role = QPalette::Midlight;
4087 break;
4088 case Qt::PaletteDark:
4089 role = QPalette::Dark;
4090 break;
4091 case Qt::PaletteMid:
4092 role = QPalette::Mid;
4093 break;
4094 case Qt::PaletteText:
4095 role = QPalette::Text;
4096 break;
4097 case Qt::PaletteBrightText:
4098 role = QPalette::BrightText;
4099 break;
4100 case Qt::PaletteBase:
4101 role = QPalette::Base;
4102 break;
4103 case Qt::PaletteBackground:
4104 role = QPalette::Window;
4105 break;
4106 case Qt::PaletteShadow:
4107 role = QPalette::Shadow;
4108 break;
4109 case Qt::PaletteHighlight:
4110 role = QPalette::Highlight;
4111 break;
4112 case Qt::PaletteHighlightedText:
4113 role = QPalette::HighlightedText;
4114 break;
4115 case Qt::PaletteButtonText:
4116 role = QPalette::ButtonText;
4117 break;
4118 case Qt::PaletteLink:
4119 role = QPalette::Link;
4120 break;
4121 case Qt::PaletteLinkVisited:
4122 role = QPalette::LinkVisited;
4123 break;
4124 case Qt::X11ParentRelative:
4125 d->fg_role = role = QPalette::NoRole;
4126 default:
4127 break;
4129 setBackgroundRole(role);
4133 The widget mapper is no longer part of the public API.
4135 QT3_SUPPORT QWidgetMapper *QWidget::wmapper() { return QWidgetPrivate::mapper; }
4137 #endif
4141 Returns the background role of the widget.
4143 The background role defines the brush from the widget's \l palette that
4144 is used to render the background.
4146 If no explicit background role is set, the widget inherts its parent
4147 widget's background role.
4149 \sa setBackgroundRole(), foregroundRole()
4151 QPalette::ColorRole QWidget::backgroundRole() const
4154 const QWidget *w = this;
4155 do {
4156 QPalette::ColorRole role = w->d_func()->bg_role;
4157 if (role != QPalette::NoRole)
4158 return role;
4159 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4160 break;
4161 w = w->parentWidget();
4162 } while (w);
4163 return QPalette::Window;
4167 Sets the background role of the widget to \a role.
4169 The background role defines the brush from the widget's \l palette that
4170 is used to render the background.
4172 If \a role is QPalette::NoRole, then the widget inherits its
4173 parent's background role.
4175 \sa backgroundRole(), foregroundRole()
4178 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4180 Q_D(QWidget);
4181 d->bg_role = role;
4182 d->updateSystemBackground();
4183 d->propagatePaletteChange();
4184 d->updateIsOpaque();
4188 Returns the foreground role.
4190 The foreground role defines the color from the widget's \l palette that
4191 is used to draw the foreground.
4193 If no explicit foreground role is set, the function returns a role
4194 that contrasts with the background role.
4196 \sa setForegroundRole(), backgroundRole()
4198 QPalette::ColorRole QWidget::foregroundRole() const
4200 Q_D(const QWidget);
4201 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4202 if (rl != QPalette::NoRole)
4203 return rl;
4204 QPalette::ColorRole role = QPalette::WindowText;
4205 switch (backgroundRole()) {
4206 case QPalette::Button:
4207 role = QPalette::ButtonText;
4208 break;
4209 case QPalette::Base:
4210 role = QPalette::Text;
4211 break;
4212 case QPalette::Dark:
4213 case QPalette::Shadow:
4214 role = QPalette::Light;
4215 break;
4216 case QPalette::Highlight:
4217 role = QPalette::HighlightedText;
4218 break;
4219 case QPalette::ToolTipBase:
4220 role = QPalette::ToolTipText;
4221 break;
4222 default:
4225 return role;
4229 Sets the foreground role of the widget to \a role.
4231 The foreground role defines the color from the widget's \l palette that
4232 is used to draw the foreground.
4234 If \a role is QPalette::NoRole, the widget uses a foreground role
4235 that contrasts with the background role.
4237 \sa foregroundRole(), backgroundRole()
4239 void QWidget::setForegroundRole(QPalette::ColorRole role)
4241 Q_D(QWidget);
4242 d->fg_role = role;
4243 d->updateSystemBackground();
4244 d->propagatePaletteChange();
4248 \property QWidget::palette
4249 \brief the widget's palette
4251 This property describes the widget's palette. The palette is used by the
4252 widget's style when rendering standard components, and is available as a
4253 means to ensure that custom widgets can maintain consistency with the
4254 native platform's look and feel. It's common that different platforms, or
4255 different styles, have different palettes.
4257 When you assign a new palette to a widget, the color roles from this
4258 palette are combined with the widget's default palette to form the
4259 widget's final palette. The palette entry for the widget's background role
4260 is used to fill the widget's background (see QWidget::autoFillBackground),
4261 and the foreground role initializes QPainter's pen.
4263 The default depends on the system environment. QApplication maintains a
4264 system/theme palette which serves as a default for all widgets. There may
4265 also be special palette defaults for certain types of widgets (e.g., on
4266 Windows XP and Vista, all classes that derive from QMenuBar have a special
4267 default palette). You can also define default palettes for widgets
4268 yourself by passing a custom palette and the name of a widget to
4269 QApplication::setPalette(). Finally, the style always has the option of
4270 polishing the palette as it's assigned (see QStyle::polish()).
4272 QWidget propagates explicit palette roles from parent to child. If you
4273 assign a brush or color to a specific role on a palette and assign that
4274 palette to a widget, that role will propagate to all the widget's
4275 children, overriding any system defaults for that role. Note that palettes
4276 by default don't propagate to windows (see isWindow()) unless the
4277 Qt::WA_WindowPropagation attribute is enabled.
4279 QWidget's palette propagation is similar to its font propagation.
4281 The current style, which is used to render the content of all standard Qt
4282 widgets, is free to choose colors and brushes from the widget palette, or
4283 in some cases, to ignore the palette (partially, or completely). In
4284 particular, certain styles like GTK style, Mac style, Windows XP, and
4285 Vista style, depend on third party APIs to render the content of widgets,
4286 and these styles typically do not follow the palette. Because of this,
4287 assigning roles to a widget's palette is not guaranteed to change the
4288 appearance of the widget. Instead, you may choose to apply a \l
4289 styleSheet. You can refer to our Knowledge Base article
4290 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4291 information.
4293 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4294 When using style sheets, the palette of a widget can be customized using
4295 the "color", "background-color", "selection-color",
4296 "selection-background-color" and "alternate-background-color".
4298 \sa QApplication::palette(), QWidget::font()
4300 const QPalette &QWidget::palette() const
4302 if (!isEnabled()) {
4303 data->pal.setCurrentColorGroup(QPalette::Disabled);
4304 } else if ((!isVisible() || isActiveWindow())
4305 #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
4306 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4307 #endif
4309 data->pal.setCurrentColorGroup(QPalette::Active);
4310 } else {
4311 #ifdef Q_WS_MAC
4312 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4313 if (qt_mac_can_clickThrough(this))
4314 data->pal.setCurrentColorGroup(QPalette::Active);
4315 else
4316 #endif
4317 data->pal.setCurrentColorGroup(QPalette::Inactive);
4319 return data->pal;
4322 void QWidget::setPalette(const QPalette &palette)
4324 Q_D(QWidget);
4325 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4327 // Determine which palette is inherited from this widget's ancestors and
4328 // QApplication::palette, resolve this against \a palette (attributes from
4329 // the inherited palette are copied over this widget's palette). Then
4330 // propagate this palette to this widget's children.
4331 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4332 QPalette resolvedPalette = palette.resolve(naturalPalette);
4333 d->setPalette_helper(resolvedPalette);
4337 \internal
4339 Returns the palette that the widget \a w inherits from its ancestors and
4340 QApplication::palette. \a inheritedMask is the combination of the widget's
4341 ancestors palette request masks (i.e., which attributes from the parent
4342 widget's palette are implicitly imposed on this widget by the user). Note
4343 that this font does not take into account the palette set on \a w itself.
4345 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4347 Q_Q(const QWidget);
4348 QPalette naturalPalette = QApplication::palette(q);
4349 if (!q->testAttribute(Qt::WA_StyleSheet)
4350 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation) || (extra && extra->proxyWidget))) {
4351 if (QWidget *p = q->parentWidget()) {
4352 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4353 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4354 QPalette inheritedPalette = p->palette();
4355 inheritedPalette.resolve(inheritedMask);
4356 naturalPalette = inheritedPalette.resolve(naturalPalette);
4357 } else {
4358 naturalPalette = p->palette();
4361 } else if (extra && extra->proxyWidget) {
4362 #ifndef QT_NO_GRAPHICSVIEW
4363 QPalette inheritedPalette = extra->proxyWidget->palette();
4364 inheritedPalette.resolve(inheritedMask);
4365 naturalPalette = inheritedPalette.resolve(naturalPalette);
4366 #endif //QT_NO_GRAPHICSVIEW
4369 naturalPalette.resolve(0);
4370 return naturalPalette;
4373 \internal
4375 Determine which palette is inherited from this widget's ancestors and
4376 QApplication::palette, resolve this against this widget's palette
4377 (attributes from the inherited palette are copied over this widget's
4378 palette). Then propagate this palette to this widget's children.
4380 void QWidgetPrivate::resolvePalette()
4382 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4383 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4384 setPalette_helper(resolvedPalette);
4387 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4389 Q_Q(QWidget);
4390 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4391 return;
4392 data.pal = palette;
4393 updateSystemBackground();
4394 propagatePaletteChange();
4395 updateIsOpaque();
4396 q->update();
4397 updateIsOpaque();
4401 \property QWidget::font
4402 \brief the font currently set for the widget
4404 This property describes the widget's requested font. The font is used by
4405 the widget's style when rendering standard components, and is available as
4406 a means to ensure that custom widgets can maintain consistency with the
4407 native platform's look and feel. It's common that different platforms, or
4408 different styles, define different fonts for an application.
4410 When you assign a new font to a widget, the properties from this font are
4411 combined with the widget's default font to form the widget's final
4412 font. You can call fontInfo() to get a copy of the widget's final
4413 font. The final font is also used to initialize QPainter's font.
4415 The default depends on the system environment. QApplication maintains a
4416 system/theme font which serves as a default for all widgets. There may
4417 also be special font defaults for certain types of widgets. You can also
4418 define default fonts for widgets yourself by passing a custom font and the
4419 name of a widget to QApplication::setFont(). Finally, the font is matched
4420 against Qt's font database to find the best match.
4422 QWidget propagates explicit font properties from parent to child. If you
4423 change a specific property on a font and assign that font to a widget,
4424 that property will propagate to all the widget's children, overriding any
4425 system defaults for that property. Note that fonts by default don't
4426 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4427 attribute is enabled.
4429 QWidget's font propagation is similar to its palette propagation.
4431 The current style, which is used to render the content of all standard Qt
4432 widgets, is free to choose to use the widget font, or in some cases, to
4433 ignore it (partially, or completely). In particular, certain styles like
4434 GTK style, Mac style, Windows XP, and Vista style, apply special
4435 modifications to the widget font to match the platform's native look and
4436 feel. Because of this, assigning properties to a widget's font is not
4437 guaranteed to change the appearance of the widget. Instead, you may choose
4438 to apply a \l styleSheet.
4440 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4441 style sheets will take precedence if the settings conflict.
4443 \sa fontInfo(), fontMetrics()
4446 void QWidget::setFont(const QFont &font)
4448 Q_D(QWidget);
4450 #ifndef QT_NO_STYLE_STYLESHEET
4451 const QStyleSheetStyle* style;
4452 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4453 style->saveWidgetFont(this, font);
4455 #endif
4457 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4459 // Determine which font is inherited from this widget's ancestors and
4460 // QApplication::font, resolve this against \a font (attributes from the
4461 // inherited font are copied over). Then propagate this font to this
4462 // widget's children.
4463 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4464 QFont resolvedFont = font.resolve(naturalFont);
4465 d->setFont_helper(resolvedFont);
4469 \internal
4471 Returns the font that the widget \a w inherits from its ancestors and
4472 QApplication::font. \a inheritedMask is the combination of the widget's
4473 ancestors font request masks (i.e., which attributes from the parent
4474 widget's font are implicitly imposed on this widget by the user). Note
4475 that this font does not take into account the font set on \a w itself.
4477 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4478 is applied, fonts are not propagated anymore
4480 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4482 Q_Q(const QWidget);
4483 QFont naturalFont = QApplication::font(q);
4484 if (!q->testAttribute(Qt::WA_StyleSheet)
4485 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation) || (extra && extra->proxyWidget))) {
4486 if (QWidget *p = q->parentWidget()) {
4487 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4488 if (!naturalFont.isCopyOf(QApplication::font())) {
4489 QFont inheritedFont = p->font();
4490 inheritedFont.resolve(inheritedMask);
4491 naturalFont = inheritedFont.resolve(naturalFont);
4492 } else {
4493 naturalFont = p->font();
4496 } else if (extra && extra->proxyWidget) {
4497 #ifndef QT_NO_GRAPHICSVIEW
4498 QFont inheritedFont = extra->proxyWidget->font();
4499 inheritedFont.resolve(inheritedMask);
4500 naturalFont = inheritedFont.resolve(naturalFont);
4501 #endif //QT_NO_GRAPHICSVIEW
4504 naturalFont.resolve(0);
4505 return naturalFont;
4509 \internal
4511 Determine which font is implicitly imposed on this widget by its ancestors
4512 and QApplication::font, resolve this against its own font (attributes from
4513 the implicit font are copied over). Then propagate this font to this
4514 widget's children.
4516 void QWidgetPrivate::resolveFont()
4518 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4519 QFont resolvedFont = data.fnt.resolve(naturalFont);
4520 setFont_helper(resolvedFont);
4524 \internal
4526 Assign \a font to this widget, and propagate it to all children, except
4527 style sheet widgets (handled differently) and windows that don't enable
4528 window propagation. \a implicitMask is the union of all ancestor widgets'
4529 font request masks, and determines which attributes from this widget's
4530 font should propagate.
4532 void QWidgetPrivate::updateFont(const QFont &font)
4534 Q_Q(QWidget);
4535 #ifndef QT_NO_STYLE_STYLESHEET
4536 const QStyleSheetStyle* cssStyle;
4537 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4538 #endif
4540 #ifdef QT3_SUPPORT
4541 QFont old = data.fnt;
4542 #endif
4543 data.fnt = QFont(font, q);
4544 #if defined(Q_WS_X11)
4545 // make sure the font set on this widget is associated with the correct screen
4546 data.fnt.x11SetScreen(xinfo.screen());
4547 #endif
4548 // Combine new mask with natural mask and propagate to children.
4549 if (!q->parentWidget() && extra && extra->proxyWidget) {
4550 #ifndef QT_NO_GRAPHICSVIEW
4551 QGraphicsProxyWidget *p = extra->proxyWidget;
4552 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4553 #endif //QT_NO_GRAPHICSVIEW
4554 } else if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4555 inheritedFontResolveMask = 0;
4557 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4559 for (int i = 0; i < children.size(); ++i) {
4560 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4561 if (w) {
4562 if (0) {
4563 #ifndef QT_NO_STYLE_STYLESHEET
4564 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4565 // Style sheets follow a different font propagation scheme.
4566 if (cssStyle)
4567 cssStyle->updateStyleSheetFont(w);
4568 #endif
4569 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4570 // Propagate font changes.
4571 QWidgetPrivate *wd = w->d_func();
4572 wd->inheritedFontResolveMask = newMask;
4573 wd->resolveFont();
4578 #ifndef QT_NO_STYLE_STYLESHEET
4579 if (cssStyle) {
4580 cssStyle->updateStyleSheetFont(q);
4582 #endif
4584 QEvent e(QEvent::FontChange);
4585 QApplication::sendEvent(q, &e);
4586 #ifdef QT3_SUPPORT
4587 q->fontChange(old);
4588 #endif
4591 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4593 Q_Q(QWidget);
4595 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4596 return;
4597 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4598 if (!children.isEmpty()) {
4599 for (int i = 0; i < children.size(); ++i) {
4600 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4601 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4602 w->d_func()->setLayoutDirection_helper(direction);
4605 QEvent e(QEvent::LayoutDirectionChange);
4606 QApplication::sendEvent(q, &e);
4609 void QWidgetPrivate::resolveLayoutDirection()
4611 Q_Q(const QWidget);
4612 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4613 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4617 \property QWidget::layoutDirection
4619 \brief the layout direction for this widget
4621 By default, this property is set to Qt::LeftToRight.
4623 When the layout direction is set on a widget, it will propagate to
4624 the widget's children. Children added after the call to \c
4625 setLayoutDirection() will not inherit the parent's layout
4626 direction.
4628 \sa QApplication::layoutDirection
4630 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4632 Q_D(QWidget);
4634 setAttribute(Qt::WA_SetLayoutDirection);
4635 d->setLayoutDirection_helper(direction);
4638 Qt::LayoutDirection QWidget::layoutDirection() const
4640 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4643 void QWidget::unsetLayoutDirection()
4645 Q_D(QWidget);
4646 setAttribute(Qt::WA_SetLayoutDirection, false);
4647 d->resolveLayoutDirection();
4651 \fn QFontMetrics QWidget::fontMetrics() const
4653 Returns the font metrics for the widget's current font.
4654 Equivalent to QFontMetrics(widget->font()).
4656 \sa font(), fontInfo(), setFont()
4660 \fn QFontInfo QWidget::fontInfo() const
4662 Returns the font info for the widget's current font.
4663 Equivalent to QFontInto(widget->font()).
4665 \sa font(), fontMetrics(), setFont()
4670 \property QWidget::cursor
4671 \brief the cursor shape for this widget
4673 The mouse cursor will assume this shape when it's over this
4674 widget. See the \link Qt::CursorShape list of predefined cursor
4675 objects\endlink for a range of useful shapes.
4677 An editor widget might use an I-beam cursor:
4678 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4680 If no cursor has been set, or after a call to unsetCursor(), the
4681 parent's cursor is used.
4683 By default, this property contains a cursor with the Qt::ArrowCursor
4684 shape.
4686 Some underlying window implementations will reset the cursor if it
4687 leaves a widget even if the mouse is grabbed. If you want to have
4688 a cursor set for all widgets, even when outside the window, consider
4689 QApplication::setOverrideCursor().
4691 \sa QApplication::setOverrideCursor()
4694 #ifndef QT_NO_CURSOR
4695 QCursor QWidget::cursor() const
4697 Q_D(const QWidget);
4698 if (testAttribute(Qt::WA_SetCursor))
4699 return (d->extra && d->extra->curs)
4700 ? *d->extra->curs
4701 : QCursor(Qt::ArrowCursor);
4702 if (isWindow() || !parentWidget())
4703 return QCursor(Qt::ArrowCursor);
4704 return parentWidget()->cursor();
4707 void QWidget::setCursor(const QCursor &cursor)
4709 Q_D(QWidget);
4710 // On Mac we must set the cursor even if it is the ArrowCursor.
4711 #if !defined(Q_WS_MAC) && !defined(Q_WS_QWS)
4712 if (cursor.shape() != Qt::ArrowCursor
4713 || (d->extra && d->extra->curs))
4714 #endif
4716 d->createExtra();
4717 QCursor *newCursor = new QCursor(cursor);
4718 delete d->extra->curs;
4719 d->extra->curs = newCursor;
4721 setAttribute(Qt::WA_SetCursor);
4722 d->setCursor_sys(cursor);
4724 QEvent event(QEvent::CursorChange);
4725 QApplication::sendEvent(this, &event);
4728 void QWidget::unsetCursor()
4730 Q_D(QWidget);
4731 if (d->extra) {
4732 delete d->extra->curs;
4733 d->extra->curs = 0;
4735 if (!isWindow())
4736 setAttribute(Qt::WA_SetCursor, false);
4737 d->unsetCursor_sys();
4739 QEvent event(QEvent::CursorChange);
4740 QApplication::sendEvent(this, &event);
4743 #endif
4746 \enum QWidget::RenderFlag
4748 This enum describes how to render the widget when calling QWidget::render().
4750 \value DrawWindowBackground If you enable this option, the widget's background
4751 is rendered into the target even if autoFillBackground is not set. By default,
4752 this option is enabled.
4754 \value DrawChildren If you enable this option, the widget's children
4755 are rendered recursively into the target. By default, this option is enabled.
4757 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4758 is ignored when rendering into the target. By default, this option is disabled.
4760 \since 4.3
4764 \since 4.3
4766 Renders the \a sourceRegion of this widget into the \a target
4767 using \a renderFlags to determine how to render. Rendering
4768 starts at \a targetOffset in the \a target. For example:
4770 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4772 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4773 the region, i.e. the entire widget.
4775 Ensure that you call QPainter::end() for the \a target device's
4776 active painter (if any) before rendering. For example:
4778 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4780 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4781 or QGLWidget::renderPixmap() instead.
4783 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4784 const QRegion &sourceRegion, RenderFlags renderFlags)
4786 Q_D(QWidget);
4787 if (!target) {
4788 qWarning("QWidget::render: null pointer to paint device");
4789 return;
4792 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4793 QRegion paintRegion = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4794 : sourceRegion;
4795 if (paintRegion.isEmpty())
4796 return;
4798 #ifndef Q_WS_MAC
4799 QPainter *oldSharedPainter = inRenderWithPainter ? d->sharedPainter() : 0;
4801 // Use the target's shared painter if set (typically set when doing
4802 // "other->render(widget);" in the widget's paintEvent.
4803 if (target->devType() == QInternal::Widget) {
4804 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
4805 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
4806 QPainter *targetPainter = targetPrivate->sharedPainter();
4807 if (targetPainter && targetPainter->isActive())
4808 d->setSharedPainter(targetPainter);
4811 #endif
4813 // Use the target's redirected device if set and adjust offset and paint
4814 // region accordingly. This is typically the case when people call render
4815 // from the paintEvent.
4816 QPoint offset = targetOffset;
4817 offset -= paintRegion.boundingRect().topLeft();
4818 QPoint redirectionOffset;
4819 QPaintDevice *redirected = 0;
4821 if (target->devType() == QInternal::Widget)
4822 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
4823 if (!redirected)
4824 redirected = QPainter::redirected(target, &redirectionOffset);
4826 if (redirected) {
4827 target = redirected;
4828 offset -= redirectionOffset;
4831 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
4832 if (QPaintEngine *targetEngine = target->paintEngine()) {
4833 const QRegion targetSystemClip = targetEngine->systemClip();
4834 if (!targetSystemClip.isEmpty())
4835 paintRegion &= targetSystemClip.translated(-offset);
4839 // Set backingstore flags.
4840 int flags = QWidgetPrivate::DrawPaintOnScreen | QWidgetPrivate::DrawInvisible;
4841 if (renderFlags & DrawWindowBackground)
4842 flags |= QWidgetPrivate::DrawAsRoot;
4844 if (renderFlags & DrawChildren)
4845 flags |= QWidgetPrivate::DrawRecursive;
4846 else
4847 flags |= QWidgetPrivate::DontSubtractOpaqueChildren;
4849 #ifdef Q_WS_QWS
4850 flags |= QWidgetPrivate::DontSetCompositionMode;
4851 #endif
4853 if (target->devType() == QInternal::Printer) {
4854 QPainter p(target);
4855 d->render_helper(&p, targetOffset, paintRegion, renderFlags);
4856 return;
4859 #ifndef Q_WS_MAC
4860 // Render via backingstore.
4861 d->drawWidget(target, paintRegion, offset, flags, d->sharedPainter());
4863 // Restore shared painter.
4864 if (oldSharedPainter)
4865 d->setSharedPainter(oldSharedPainter);
4866 #else
4867 // Render via backingstore (no shared painter).
4868 d->drawWidget(target, paintRegion, offset, flags, 0);
4869 #endif
4873 \overload
4875 Renders the widget into the \a painter's QPainter::device().
4877 Transformations and settings applied to the \a painter will be used
4878 when rendering.
4880 \note The \a painter must be active. On Mac OS X the widget will be
4881 rendered into a QPixmap and then drawn by the \a painter.
4883 \sa QPainter::device()
4885 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4886 const QRegion &sourceRegion, RenderFlags renderFlags)
4888 if (!painter) {
4889 qWarning("QWidget::render: Null pointer to painter");
4890 return;
4893 if (!painter->isActive()) {
4894 qWarning("QWidget::render: Cannot render with an inactive painter");
4895 return;
4898 const qreal opacity = painter->opacity();
4899 if (qFuzzyIsNull(opacity))
4900 return; // Fully transparent.
4902 Q_D(QWidget);
4903 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4904 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4905 : sourceRegion;
4906 if (toBePainted.isEmpty())
4907 return;
4909 if (!d->extra)
4910 d->createExtra();
4911 d->extra->inRenderWithPainter = true;
4913 #ifdef Q_WS_MAC
4914 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4915 #else
4916 QPaintEngine *engine = painter->paintEngine();
4917 Q_ASSERT(engine);
4918 QPaintEnginePrivate *enginePriv = engine->d_func();
4919 Q_ASSERT(enginePriv);
4920 QPaintDevice *target = engine->paintDevice();
4921 Q_ASSERT(target);
4923 // Render via a pixmap when dealing with non-opaque painters or printers.
4924 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4925 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4926 d->extra->inRenderWithPainter = false;
4927 return;
4930 // Set new shared painter.
4931 QPainter *oldPainter = d->sharedPainter();
4932 d->setSharedPainter(painter);
4934 // Save current system clip, viewport and transform,
4935 const QTransform oldTransform = enginePriv->systemTransform;
4936 const QRegion oldSystemClip = enginePriv->systemClip;
4937 const QRegion oldSystemViewport = enginePriv->systemViewport;
4939 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4940 if (painter->hasClipping()) {
4941 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4942 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4943 } else {
4944 enginePriv->setSystemViewport(oldSystemClip);
4947 render(target, targetOffset, toBePainted, renderFlags);
4949 // Restore system clip, viewport and transform.
4950 enginePriv->systemClip = oldSystemClip;
4951 enginePriv->setSystemViewport(oldSystemViewport);
4952 enginePriv->setSystemTransform(oldTransform);
4954 // Restore shared painter.
4955 d->setSharedPainter(oldPainter);
4956 #endif
4958 d->extra->inRenderWithPainter = false;
4961 #if !defined(Q_OS_SYMBIAN)
4962 void QWidgetPrivate::setSoftKeys_sys(const QList<QAction*> &softkeys)
4964 Q_UNUSED(softkeys)
4966 #endif // !defined(Q_OS_SYMBIAN)
4968 QGraphicsEffect *QWidget::graphicsEffect() const
4970 Q_D(const QWidget);
4971 return d->graphicsEffect;
4975 Sets \a effect as the widget's effect. If there already is an effect installed
4976 on this widget, QWidget will delete the existing effect before installing
4977 the new \a effect.
4979 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4980 the effect from the widget and install it on this widget.
4982 \note This function will apply the effect on itself and all its children.
4984 \since 4.6
4986 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4988 Q_D(QWidget);
4989 if (d->graphicsEffect == effect)
4990 return;
4992 if (d->graphicsEffect && effect) {
4993 delete d->graphicsEffect;
4994 d->graphicsEffect = 0;
4997 if (!effect) {
4998 // Unset current effect.
4999 QGraphicsEffectPrivate *oldEffectPrivate = d->graphicsEffect->d_func();
5000 d->graphicsEffect = 0;
5001 if (oldEffectPrivate) {
5002 oldEffectPrivate->setGraphicsEffectSource(0); // deletes the current source.
5004 } else {
5005 // Set new effect.
5006 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
5007 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
5008 d->graphicsEffect = effect;
5009 effect->d_func()->setGraphicsEffectSource(source);
5012 d->updateIsOpaque();
5013 update();
5016 bool QWidgetPrivate::isAboutToShow() const
5018 if (data.in_show)
5019 return true;
5021 Q_Q(const QWidget);
5022 if (q->isHidden())
5023 return false;
5025 // The widget will be shown if any of its ancestors are about to show.
5026 QWidget *parent = q->parentWidget();
5027 return parent ? parent->d_func()->isAboutToShow() : false;
5030 QRegion QWidgetPrivate::prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags)
5032 Q_Q(QWidget);
5033 const bool isVisible = q->isVisible();
5035 // Make sure the widget is laid out correctly.
5036 if (!isVisible && !isAboutToShow()) {
5037 QWidget *topLevel = q->window();
5038 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
5039 topLevel->ensurePolished();
5041 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
5042 // they're not explicitly hidden.
5043 QWidget *widget = q;
5044 QWidgetList hiddenWidgets;
5045 while (widget) {
5046 if (widget->isHidden()) {
5047 widget->setAttribute(Qt::WA_WState_Hidden, false);
5048 hiddenWidgets.append(widget);
5049 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5050 widget->d_func()->updateGeometry_helper(true);
5052 widget = widget->parentWidget();
5055 // Activate top-level layout.
5056 if (topLevel->d_func()->layout)
5057 topLevel->d_func()->layout->activate();
5059 // Adjust size if necessary.
5060 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
5061 if (topLevelExtra && !topLevelExtra->sizeAdjusted
5062 && !topLevel->testAttribute(Qt::WA_Resized)) {
5063 topLevel->adjustSize();
5064 topLevel->setAttribute(Qt::WA_Resized, false);
5067 // Activate child layouts.
5068 topLevel->d_func()->activateChildLayoutsRecursively();
5070 // We're not cheating with WA_WState_Hidden anymore.
5071 for (int i = 0; i < hiddenWidgets.size(); ++i) {
5072 QWidget *widget = hiddenWidgets.at(i);
5073 widget->setAttribute(Qt::WA_WState_Hidden);
5074 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5075 widget->parentWidget()->d_func()->layout->invalidate();
5077 } else if (isVisible) {
5078 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
5081 // Calculate the region to be painted.
5082 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
5083 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
5084 toBePainted &= extra->mask;
5085 return toBePainted;
5088 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
5089 QWidget::RenderFlags renderFlags)
5091 Q_ASSERT(painter);
5092 Q_ASSERT(!toBePainted.isEmpty());
5094 Q_Q(QWidget);
5095 #ifndef Q_WS_MAC
5096 const QTransform originalTransform = painter->worldTransform();
5097 const bool useDeviceCoordinates = originalTransform.isScaling();
5098 if (!useDeviceCoordinates) {
5099 #endif
5100 // Render via a pixmap.
5101 const QRect rect = toBePainted.boundingRect();
5102 const QSize size = rect.size();
5103 if (size.isNull())
5104 return;
5106 QPixmap pixmap(size);
5107 if (!(renderFlags & QWidget::DrawWindowBackground))
5108 pixmap.fill(Qt::transparent);
5109 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
5111 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
5112 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
5114 painter->drawPixmap(targetOffset, pixmap);
5116 if (restore)
5117 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
5119 #ifndef Q_WS_MAC
5120 } else {
5121 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
5122 QTransform transform = originalTransform;
5123 transform.translate(targetOffset.x(), targetOffset.y());
5125 QPaintDevice *device = painter->device();
5126 Q_ASSERT(device);
5128 // Calculate device rect.
5129 const QRectF rect(toBePainted.boundingRect());
5130 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
5131 deviceRect &= QRect(0, 0, device->width(), device->height());
5133 QPixmap pixmap(deviceRect.size());
5134 pixmap.fill(Qt::transparent);
5136 // Create a pixmap device coordinate painter.
5137 QPainter pixmapPainter(&pixmap);
5138 pixmapPainter.setRenderHints(painter->renderHints());
5139 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
5140 pixmapPainter.setTransform(transform);
5142 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
5143 pixmapPainter.end();
5145 // And then draw the pixmap.
5146 painter->setTransform(QTransform());
5147 painter->drawPixmap(deviceRect.topLeft(), pixmap);
5148 painter->setTransform(originalTransform);
5150 #endif
5153 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5154 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5156 if (rgn.isEmpty())
5157 return;
5159 Q_Q(QWidget);
5160 if (graphicsEffect && graphicsEffect->isEnabled()) {
5161 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5162 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5163 (source->d_func());
5164 if (!sourced->context) {
5165 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5166 sourced->context = &context;
5167 if (!sharedPainter) {
5168 QPaintEngine *paintEngine = pdev->paintEngine();
5169 paintEngine->d_func()->systemClip = rgn.translated(offset);
5170 QPainter p(pdev);
5171 p.translate(offset);
5172 context.painter = &p;
5173 graphicsEffect->draw(&p, source);
5174 paintEngine->d_func()->systemClip = QRegion();
5175 } else {
5176 context.painter = sharedPainter;
5177 sharedPainter->save();
5178 sharedPainter->translate(offset);
5179 graphicsEffect->draw(sharedPainter, source);
5180 sharedPainter->restore();
5182 sourced->context = 0;
5183 return;
5187 const bool asRoot = flags & DrawAsRoot;
5188 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5189 const bool recursive = flags & DrawRecursive;
5190 const bool alsoInvisible = flags & DrawInvisible;
5192 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5194 QRegion toBePainted(rgn);
5195 if (asRoot && !alsoInvisible)
5196 toBePainted &= clipRect(); //(rgn & visibleRegion());
5197 if (!(flags & DontSubtractOpaqueChildren))
5198 subtractOpaqueChildren(toBePainted, q->rect());
5200 if (!toBePainted.isEmpty()) {
5201 bool onScreen = paintOnScreen();
5202 if (!onScreen || alsoOnScreen) {
5203 //update the "in paint event" flag
5204 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5205 qWarning("QWidget::repaint: Recursive repaint detected");
5206 q->setAttribute(Qt::WA_WState_InPaintEvent);
5208 //clip away the new area
5209 #ifndef QT_NO_PAINT_DEBUG
5210 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5211 #endif
5212 QPaintEngine *paintEngine = pdev->paintEngine();
5213 if (paintEngine) {
5214 setRedirected(pdev, -offset);
5216 if (sharedPainter)
5217 paintEngine->d_func()->systemClip = toBePainted;
5218 else
5219 paintEngine->d_func()->systemRect = q->data->crect;
5221 //paint the background
5222 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5223 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5225 QPainter p(q);
5226 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5229 if (!sharedPainter)
5230 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5232 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5233 QPainter p(q);
5234 QColor tint = q->palette().window().color();
5235 tint.setAlphaF(qreal(.6));
5236 p.fillRect(toBePainted.boundingRect(), tint);
5240 #if 0
5241 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5242 qDebug() << "clipping to" << toBePainted << "location == " << offset
5243 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5244 #endif
5246 //actually send the paint event
5247 QPaintEvent e(toBePainted);
5248 QCoreApplication::sendSpontaneousEvent(q, &e);
5249 #if !defined(Q_WS_MAC) && !defined(Q_WS_QWS)
5250 if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5251 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5252 #endif
5254 //restore
5255 if (paintEngine) {
5256 restoreRedirected();
5257 if (!sharedPainter)
5258 paintEngine->d_func()->systemRect = QRect();
5259 else
5260 paintEngine->d_func()->currentClipWidget = 0;
5261 paintEngine->d_func()->systemClip = QRegion();
5263 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5264 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5265 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5267 if (paintEngine && paintEngine->autoDestruct()) {
5268 delete paintEngine;
5271 #ifndef QT_NO_PAINT_DEBUG
5272 if (flushed)
5273 QWidgetBackingStore::unflushPaint(q, toBePainted);
5274 #endif
5275 } else if (q->isWindow()) {
5276 QPaintEngine *engine = pdev->paintEngine();
5277 if (engine) {
5278 QPainter p(pdev);
5279 p.setClipRegion(toBePainted);
5280 const QBrush bg = q->palette().brush(QPalette::Window);
5281 if (bg.style() == Qt::TexturePattern)
5282 p.drawTiledPixmap(q->rect(), bg.texture());
5283 else
5284 p.fillRect(q->rect(), bg);
5286 if (engine->autoDestruct())
5287 delete engine;
5292 if (recursive && !children.isEmpty()) {
5293 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5294 #ifdef Q_BACKINGSTORE_SUBSURFACES
5295 , q->windowSurface()
5296 #endif
5297 , sharedPainter, backingStore);
5301 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5302 const QPoint &offset, int flags
5303 #ifdef Q_BACKINGSTORE_SUBSURFACES
5304 , const QWindowSurface *currentSurface
5305 #endif
5306 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5308 QWidget *w = 0;
5309 QRect boundingRect;
5310 bool dirtyBoundingRect = true;
5311 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5313 do {
5314 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5315 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()) {
5316 if (dirtyBoundingRect) {
5317 boundingRect = rgn.boundingRect();
5318 dirtyBoundingRect = false;
5321 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5322 #ifdef Q_BACKINGSTORE_SUBSURFACES
5323 if (x->windowSurface() == currentSurface)
5324 #endif
5326 w = x;
5327 break;
5331 --index;
5332 } while (index >= 0);
5334 if (!w)
5335 return;
5337 QWidgetPrivate *wd = w->d_func();
5338 const QPoint widgetPos(w->data->crect.topLeft());
5339 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5341 if (index > 0) {
5342 QRegion wr(rgn);
5343 if (wd->isOpaque)
5344 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5345 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5346 #ifdef Q_BACKINGSTORE_SUBSURFACES
5347 , currentSurface
5348 #endif
5349 , sharedPainter, backingStore);
5352 if (w->updatesEnabled() && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)) {
5353 QRegion wRegion(rgn);
5354 wRegion &= wd->effectiveRectFor(w->data->crect);
5355 wRegion.translate(-widgetPos);
5356 if (hasMask)
5357 wRegion &= wd->extra->mask;
5358 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5362 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5364 if (system != Qt::DeviceCoordinates)
5365 return m_widget->rect();
5367 if (!context) {
5368 // Device coordinates without context not yet supported.
5369 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5370 return QRectF();
5373 return context->painter->worldTransform().mapRect(m_widget->rect());
5376 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5378 if (!context || context->painter != painter) {
5379 m_widget->render(painter);
5380 return;
5383 // The region saved in the context is neither clipped to the rect
5384 // nor the mask, so we have to clip it here before calling drawWidget.
5385 QRegion toBePainted = context->rgn;
5386 toBePainted &= m_widget->rect();
5387 QWidgetPrivate *wd = qt_widget_private(m_widget);
5388 if (wd->extra && wd->extra->hasMask)
5389 toBePainted &= wd->extra->mask;
5391 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5392 context->sharedPainter, context->backingStore);
5395 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset) const
5397 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5398 if (!context && deviceCoordinates) {
5399 // Device coordinates without context not yet supported.
5400 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5401 return QPixmap();
5404 QPoint pixmapOffset;
5405 QRectF sourceRect = m_widget->rect();
5407 if (deviceCoordinates) {
5408 const QTransform &painterTransform = context->painter->worldTransform();
5409 sourceRect = painterTransform.mapRect(sourceRect);
5410 pixmapOffset = painterTransform.map(pixmapOffset);
5413 QRect effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5414 if (offset)
5415 *offset = effectRect.topLeft();
5417 if (deviceCoordinates) {
5418 // Clip to device rect.
5419 int left, top, right, bottom;
5420 effectRect.getCoords(&left, &top, &right, &bottom);
5421 if (left < 0) {
5422 if (offset)
5423 offset->rx() += -left;
5424 effectRect.setX(0);
5426 if (top < 0) {
5427 if (offset)
5428 offset->ry() += -top;
5429 effectRect.setY(0);
5431 // NB! We use +-1 for historical reasons (see QRect documentation).
5432 QPaintDevice *device = context->painter->device();
5433 const int deviceWidth = device->width();
5434 const int deviceHeight = device->height();
5435 if (right + 1 > deviceWidth)
5436 effectRect.setRight(deviceWidth - 1);
5437 if (bottom + 1 > deviceHeight)
5438 effectRect.setBottom(deviceHeight -1);
5441 pixmapOffset -= effectRect.topLeft();
5443 QPixmap pixmap(effectRect.size());
5444 pixmap.fill(Qt::transparent);
5445 m_widget->render(&pixmap, pixmapOffset);
5446 return pixmap;
5450 \internal
5452 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5453 widget and its ancestors. The search starts at \a origin (inclusive).
5454 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5455 widget was found.
5457 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(QWidget *origin)
5459 if (origin) {
5460 QWExtra *extra = origin->d_func()->extra;
5461 if (extra && extra->proxyWidget)
5462 return extra->proxyWidget;
5463 return nearestGraphicsProxyWidget(origin->parentWidget());
5465 return 0;
5469 \property QWidget::locale
5470 \brief the widget's locale
5471 \since 4.3
5473 As long as no special locale has been set, this is either
5474 the parent's locale or (if this widget is a top level widget),
5475 the default locale.
5477 If the widget displays dates or numbers, these should be formatted
5478 using the widget's locale.
5480 \sa QLocale QLocale::setDefault()
5483 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5485 Q_Q(QWidget);
5486 if (locale == loc && !forceUpdate)
5487 return;
5489 locale = loc;
5491 if (!children.isEmpty()) {
5492 for (int i = 0; i < children.size(); ++i) {
5493 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5494 if (!w)
5495 continue;
5496 if (w->testAttribute(Qt::WA_SetLocale))
5497 continue;
5498 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5499 continue;
5500 w->d_func()->setLocale_helper(loc, forceUpdate);
5503 QEvent e(QEvent::LocaleChange);
5504 QApplication::sendEvent(q, &e);
5507 void QWidget::setLocale(const QLocale &locale)
5509 Q_D(QWidget);
5511 setAttribute(Qt::WA_SetLocale);
5512 d->setLocale_helper(locale);
5515 QLocale QWidget::locale() const
5517 Q_D(const QWidget);
5519 return d->locale;
5522 void QWidgetPrivate::resolveLocale()
5524 Q_Q(const QWidget);
5526 if (!q->testAttribute(Qt::WA_SetLocale)) {
5527 setLocale_helper(q->isWindow()
5528 ? QLocale()
5529 : q->parentWidget()->locale());
5533 void QWidget::unsetLocale()
5535 Q_D(QWidget);
5536 setAttribute(Qt::WA_SetLocale, false);
5537 d->resolveLocale();
5540 static QString constructWindowTitleFromFilePath(const QString &filePath)
5542 QFileInfo fi(filePath);
5543 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5544 #ifndef Q_WS_MAC
5545 QString appName = QApplication::applicationName();
5546 if (!appName.isEmpty())
5547 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5548 #endif
5549 return windowTitle;
5553 \property QWidget::windowTitle
5554 \brief the window title (caption)
5556 This property only makes sense for top-level widgets, such as
5557 windows and dialogs. If no caption has been set, the title is based of the
5558 \l windowFilePath. If neither of these is set, then the title is
5559 an empty string.
5561 If you use the \l windowModified mechanism, the window title must
5562 contain a "[*]" placeholder, which indicates where the '*' should
5563 appear. Normally, it should appear right after the file name
5564 (e.g., "document1.txt[*] - Text Editor"). If the \l
5565 windowModified property is false (the default), the placeholder
5566 is simply removed.
5568 \sa windowIcon, windowIconText, windowModified, windowFilePath
5570 QString QWidget::windowTitle() const
5572 Q_D(const QWidget);
5573 if (d->extra && d->extra->topextra) {
5574 if (!d->extra->topextra->caption.isEmpty())
5575 return d->extra->topextra->caption;
5576 if (!d->extra->topextra->filePath.isEmpty())
5577 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5579 return QString();
5583 Returns a modified window title with the [*] place holder
5584 replaced according to the rules described in QWidget::setWindowTitle
5586 This function assumes that "[*]" can be quoted by another
5587 "[*]", so it will replace two place holders by one and
5588 a single last one by either "*" or nothing depending on
5589 the modified flag.
5591 \internal
5593 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5595 Q_ASSERT(widget);
5597 #ifdef QT_EVAL
5598 extern QString qt_eval_adapt_window_title(const QString &title);
5599 QString cap = qt_eval_adapt_window_title(title);
5600 #else
5601 QString cap = title;
5602 #endif
5604 if (cap.isEmpty())
5605 return cap;
5607 QLatin1String placeHolder("[*]");
5608 int placeHolderLength = 3; // QLatin1String doesn't have length()
5610 int index = cap.indexOf(placeHolder);
5612 // here the magic begins
5613 while (index != -1) {
5614 index += placeHolderLength;
5615 int count = 1;
5616 while (cap.indexOf(placeHolder, index) == index) {
5617 ++count;
5618 index += placeHolderLength;
5621 if (count%2) { // odd number of [*] -> replace last one
5622 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5623 if (widget->isWindowModified()
5624 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5625 cap.replace(lastIndex, 3, QWidget::tr("*"));
5626 else
5627 cap.remove(lastIndex, 3);
5630 index = cap.indexOf(placeHolder, index);
5633 cap.replace(QLatin1String("[*][*]"), placeHolder);
5635 return cap;
5638 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5640 Q_Q(QWidget);
5641 if (!q->testAttribute(Qt::WA_WState_Created))
5642 createWinId();
5643 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5646 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5648 Q_Q(QWidget);
5649 if (q->testAttribute(Qt::WA_WState_Created))
5650 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5653 void QWidget::setWindowIconText(const QString &iconText)
5655 if (QWidget::windowIconText() == iconText)
5656 return;
5658 Q_D(QWidget);
5659 d->topData()->iconText = iconText;
5660 d->setWindowIconText_helper(iconText);
5662 QEvent e(QEvent::IconTextChange);
5663 QApplication::sendEvent(this, &e);
5666 void QWidget::setWindowTitle(const QString &title)
5668 if (QWidget::windowTitle() == title)
5669 return;
5671 Q_D(QWidget);
5672 d->topData()->caption = title;
5673 d->setWindowTitle_helper(title);
5675 QEvent e(QEvent::WindowTitleChange);
5676 QApplication::sendEvent(this, &e);
5681 \property QWidget::windowIcon
5682 \brief the widget's icon
5684 This property only makes sense for windows. If no icon
5685 has been set, windowIcon() returns the application icon
5686 (QApplication::windowIcon()).
5688 \sa windowIconText, windowTitle
5690 QIcon QWidget::windowIcon() const
5692 const QWidget *w = this;
5693 while (w) {
5694 const QWidgetPrivate *d = w->d_func();
5695 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5696 return *d->extra->topextra->icon;
5697 w = w->parentWidget();
5699 return QApplication::windowIcon();
5702 void QWidgetPrivate::setWindowIcon_helper()
5704 QEvent e(QEvent::WindowIconChange);
5705 QApplication::sendEvent(q_func(), &e);
5706 for (int i = 0; i < children.size(); ++i) {
5707 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5708 if (w && !w->isWindow())
5709 QApplication::sendEvent(w, &e);
5713 void QWidget::setWindowIcon(const QIcon &icon)
5715 Q_D(QWidget);
5717 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5718 d->createTLExtra();
5720 if (!d->extra->topextra->icon)
5721 d->extra->topextra->icon = new QIcon();
5722 *d->extra->topextra->icon = icon;
5724 delete d->extra->topextra->iconPixmap;
5725 d->extra->topextra->iconPixmap = 0;
5727 d->setWindowIcon_sys();
5728 d->setWindowIcon_helper();
5733 \property QWidget::windowIconText
5734 \brief the widget's icon text
5736 This property only makes sense for windows. If no icon
5737 text has been set, this functions returns an empty string.
5739 \sa windowIcon, windowTitle
5742 QString QWidget::windowIconText() const
5744 Q_D(const QWidget);
5745 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5749 \property QWidget::windowFilePath
5750 \since 4.4
5751 \brief the file path associated with a widget
5753 This property only makes sense for windows. It associates a file path with
5754 a window. If you set the file path, but have not set the window title, Qt
5755 sets the window title to contain a string created using the following
5756 components.
5758 On Mac OS X:
5760 \list
5761 \o The file name of the specified path, obtained using QFileInfo::fileName().
5762 \endlist
5764 On Windows and X11:
5766 \list
5767 \o The file name of the specified path, obtained using QFileInfo::fileName().
5768 \o An optional \c{*} character, if the \l windowModified property is set.
5769 \o The \c{0x2014} unicode character, padded either side by spaces.
5770 \o The application name, obtained from the application's
5771 \l{QCoreApplication::}{applicationName} property.
5772 \endlist
5774 If the window title is set at any point, then the window title takes precedence and
5775 will be shown instead of the file path string.
5777 Additionally, on Mac OS X, this has an added benefit that it sets the
5778 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5779 for the window, assuming that the file path exists.
5781 If no file path is set, this property contains an empty string.
5783 By default, this property contains an empty string.
5785 \sa windowTitle, windowIcon
5788 QString QWidget::windowFilePath() const
5790 Q_D(const QWidget);
5791 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5794 void QWidget::setWindowFilePath(const QString &filePath)
5796 if (filePath == windowFilePath())
5797 return;
5799 Q_D(QWidget);
5801 d->createTLExtra();
5802 d->extra->topextra->filePath = filePath;
5803 d->setWindowFilePath_helper(filePath);
5806 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5808 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5809 #ifdef Q_WS_MAC
5810 setWindowTitle_helper(QFileInfo(filePath).fileName());
5811 #else
5812 Q_Q(QWidget);
5813 Q_UNUSED(filePath);
5814 setWindowTitle_helper(q->windowTitle());
5815 #endif
5817 #ifdef Q_WS_MAC
5818 setWindowFilePath_sys(filePath);
5819 #endif
5823 Returns the window's role, or an empty string.
5825 \sa windowIcon, windowTitle
5828 QString QWidget::windowRole() const
5830 Q_D(const QWidget);
5831 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5835 Sets the window's role to \a role. This only makes sense for
5836 windows on X11.
5838 void QWidget::setWindowRole(const QString &role)
5840 #if defined(Q_WS_X11)
5841 Q_D(QWidget);
5842 d->topData()->role = role;
5843 d->setWindowRole();
5844 #else
5845 Q_UNUSED(role)
5846 #endif
5850 \property QWidget::mouseTracking
5851 \brief whether mouse tracking is enabled for the widget
5853 If mouse tracking is disabled (the default), the widget only
5854 receives mouse move events when at least one mouse button is
5855 pressed while the mouse is being moved.
5857 If mouse tracking is enabled, the widget receives mouse move
5858 events even if no buttons are pressed.
5860 \sa mouseMoveEvent()
5865 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5866 function resets this widget to have no focus proxy.
5868 Some widgets can "have focus", but create a child widget, such as
5869 QLineEdit, to actually handle the focus. In this case, the widget
5870 can set the line edit to be its focus proxy.
5872 setFocusProxy() sets the widget which will actually get focus when
5873 "this widget" gets it. If there is a focus proxy, setFocus() and
5874 hasFocus() operate on the focus proxy.
5876 \sa focusProxy()
5879 void QWidget::setFocusProxy(QWidget * w)
5881 Q_D(QWidget);
5882 if (!w && !d->extra)
5883 return;
5885 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5886 if (fp == this) {
5887 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5888 return;
5892 d->createExtra();
5893 d->extra->focus_proxy = w;
5898 Returns the focus proxy, or 0 if there is no focus proxy.
5900 \sa setFocusProxy()
5903 QWidget * QWidget::focusProxy() const
5905 Q_D(const QWidget);
5906 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5911 \property QWidget::focus
5912 \brief whether this widget (or its focus proxy) has the keyboard
5913 input focus
5915 By default, this property is false.
5917 \note Obtaining the value of this property for a widget is effectively equivalent
5918 to checking whether QApplication::focusWidget() refers to the widget.
5920 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5922 bool QWidget::hasFocus() const
5924 const QWidget* w = this;
5925 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5926 w = w->d_func()->extra->focus_proxy;
5927 if (QWidget *window = w->window()) {
5928 #ifndef QT_NO_GRAPHICSVIEW
5929 QWExtra *e = window->d_func()->extra;
5930 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5931 return true;
5932 #endif
5934 return (QApplication::focusWidget() == w);
5938 Gives the keyboard input focus to this widget (or its focus
5939 proxy) if this widget or one of its parents is the \link
5940 isActiveWindow() active window\endlink. The \a reason argument will
5941 be passed into any focus event sent from this function, it is used
5942 to give an explanation of what caused the widget to get focus.
5944 First, a focus out event is sent to the focus widget (if any) to
5945 tell it that it is about to lose the focus. Then a focus in event
5946 is sent to this widget to tell it that it just received the focus.
5947 (Nothing happens if the focus in and focus out widgets are the
5948 same.)
5950 setFocus() gives focus to a widget regardless of its focus policy,
5951 but does not clear any keyboard grab (see grabKeyboard()).
5953 Be aware that if the widget is hidden, it will not accept focus
5954 until it is shown.
5956 \warning If you call setFocus() in a function which may itself be
5957 called from focusOutEvent() or focusInEvent(), you may get an
5958 infinite recursion.
5960 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5961 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5962 grabMouse(), {Keyboard Focus}
5965 void QWidget::setFocus(Qt::FocusReason reason)
5967 if (!isEnabled())
5968 return;
5970 QWidget *f = this;
5971 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5972 f = f->d_func()->extra->focus_proxy;
5974 if (QApplication::focusWidget() == f
5975 #if defined(Q_WS_WIN)
5976 && GetFocus() == f->internalWinId()
5977 #endif
5979 return;
5981 #ifndef QT_NO_GRAPHICSVIEW
5982 QWidget *previousProxyFocus = 0;
5983 if (QWExtra *topData = window()->d_func()->extra) {
5984 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5985 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5986 if (previousProxyFocus && previousProxyFocus->focusProxy())
5987 previousProxyFocus = previousProxyFocus->focusProxy();
5990 #endif
5992 QWidget *w = f;
5993 if (isHidden()) {
5994 while (w && w->isHidden()) {
5995 w->d_func()->focus_child = f;
5996 w = w->isWindow() ? 0 : w->parentWidget();
5998 } else {
5999 while (w) {
6000 w->d_func()->focus_child = f;
6001 w = w->isWindow() ? 0 : w->parentWidget();
6005 #ifndef QT_NO_GRAPHICSVIEW
6006 // Update proxy state
6007 if (QWExtra *topData = window()->d_func()->extra) {
6008 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
6009 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
6010 topData->proxyWidget->setFocus(reason);
6011 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
6014 #endif
6016 if (f->isActiveWindow()) {
6017 QApplicationPrivate::setFocusWidget(f, reason);
6018 #ifndef QT_NO_ACCESSIBILITY
6019 # ifdef Q_OS_WIN
6020 // The negation of the condition in setFocus_sys
6021 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
6022 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
6023 # endif
6024 QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
6025 #endif
6026 #ifndef QT_NO_GRAPHICSVIEW
6027 if (QWExtra *topData = window()->d_func()->extra) {
6028 if (topData->proxyWidget) {
6029 if (previousProxyFocus && previousProxyFocus != f) {
6030 // Send event to self
6031 QFocusEvent event(QEvent::FocusOut, reason);
6032 QPointer<QWidget> that = previousProxyFocus;
6033 QApplication::sendEvent(previousProxyFocus, &event);
6034 if (that)
6035 QApplication::sendEvent(that->style(), &event);
6037 if (!isHidden()) {
6038 // Send event to self
6039 QFocusEvent event(QEvent::FocusIn, reason);
6040 QPointer<QWidget> that = f;
6041 QApplication::sendEvent(f, &event);
6042 if (that)
6043 QApplication::sendEvent(that->style(), &event);
6047 #endif
6052 \fn void QWidget::setFocus()
6053 \overload
6055 Gives the keyboard input focus to this widget (or its focus
6056 proxy) if this widget or one of its parents is the
6057 \l{isActiveWindow()}{active window}.
6061 Takes keyboard input focus from the widget.
6063 If the widget has active focus, a \link focusOutEvent() focus out
6064 event\endlink is sent to this widget to tell it that it is about
6065 to lose the focus.
6067 This widget must enable focus setting in order to get the keyboard
6068 input focus, i.e. it must call setFocusPolicy().
6070 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6071 setFocusPolicy(), QApplication::focusWidget()
6074 void QWidget::clearFocus()
6076 QWidget *w = this;
6077 while (w) {
6078 if (w->d_func()->focus_child == this)
6079 w->d_func()->focus_child = 0;
6080 w = w->parentWidget();
6082 #ifndef QT_NO_GRAPHICSVIEW
6083 QWExtra *topData = d_func()->extra;
6084 if (topData && topData->proxyWidget)
6085 topData->proxyWidget->clearFocus();
6086 #endif
6088 if (hasFocus()) {
6089 // Update proxy state
6090 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6091 #if defined(Q_WS_WIN)
6092 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6093 SetFocus(0);
6094 else
6095 #endif
6097 #ifndef QT_NO_ACCESSIBILITY
6098 QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
6099 #endif
6106 \fn bool QWidget::focusNextChild()
6108 Finds a new widget to give the keyboard focus to, as appropriate
6109 for \key Tab, and returns true if it can find a new widget, or
6110 false if it can't.
6112 \sa focusPreviousChild()
6116 \fn bool QWidget::focusPreviousChild()
6118 Finds a new widget to give the keyboard focus to, as appropriate
6119 for \key Shift+Tab, and returns true if it can find a new widget,
6120 or false if it can't.
6122 \sa focusNextChild()
6126 Finds a new widget to give the keyboard focus to, as appropriate
6127 for Tab and Shift+Tab, and returns true if it can find a new
6128 widget, or false if it can't.
6130 If \a next is true, this function searches forward, if \a next
6131 is false, it searches backward.
6133 Sometimes, you will want to reimplement this function. For
6134 example, a web browser might reimplement it to move its "current
6135 active link" forward or backward, and call
6136 focusNextPrevChild() only when it reaches the last or
6137 first link on the "page".
6139 Child widgets call focusNextPrevChild() on their parent widgets,
6140 but only the window that contains the child widgets decides where
6141 to redirect focus. By reimplementing this function for an object,
6142 you thus gain control of focus traversal for all child widgets.
6144 \sa focusNextChild(), focusPreviousChild()
6147 bool QWidget::focusNextPrevChild(bool next)
6149 Q_D(QWidget);
6150 QWidget* p = parentWidget();
6151 bool isSubWindow = (windowType() == Qt::SubWindow);
6152 if (!isWindow() && !isSubWindow && p)
6153 return p->focusNextPrevChild(next);
6154 #ifndef QT_NO_GRAPHICSVIEW
6155 if (d->extra && d->extra->proxyWidget)
6156 return d->extra->proxyWidget->focusNextPrevChild(next);
6157 #endif
6158 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6159 if (!w) return false;
6161 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6162 return true;
6166 Returns the last child of this widget that setFocus had been
6167 called on. For top level widgets this is the widget that will get
6168 focus in case this window gets activated
6170 This is not the same as QApplication::focusWidget(), which returns
6171 the focus widget in the currently active window.
6174 QWidget *QWidget::focusWidget() const
6176 return const_cast<QWidget *>(d_func()->focus_child);
6180 Returns the next widget in this widget's focus chain.
6182 \sa previousInFocusChain()
6184 QWidget *QWidget::nextInFocusChain() const
6186 return const_cast<QWidget *>(d_func()->focus_next);
6190 Returns the previous widget in this widget's focus chain.
6192 \sa nextInFocusChain()
6194 \since 4.6
6196 QWidget *QWidget::previousInFocusChain() const
6198 return const_cast<QWidget *>(d_func()->focus_prev);
6202 \property QWidget::isActiveWindow
6203 \brief whether this widget's window is the active window
6205 The active window is the window that contains the widget that has
6206 keyboard focus (The window may still have focus if it has no
6207 widgets or none of its widgets accepts keyboard focus).
6209 When popup windows are visible, this property is true for both the
6210 active window \e and for the popup.
6212 By default, this property is false.
6214 \sa activateWindow(), QApplication::activeWindow()
6216 bool QWidget::isActiveWindow() const
6218 QWidget *tlw = window();
6219 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6220 return true;
6222 #ifndef QT_NO_GRAPHICSVIEW
6223 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6224 if (isVisible() && tlwExtra->proxyWidget)
6225 return tlwExtra->proxyWidget->isActiveWindow();
6227 #endif
6229 #ifdef Q_WS_MAC
6230 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6231 if(qt_mac_is_macdrawer(tlw) &&
6232 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6233 return true;
6235 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6236 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6237 return true;
6238 #endif
6239 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6240 if(tlw->windowType() == Qt::Tool &&
6241 !tlw->isModal() &&
6242 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6243 return true;
6244 QWidget *w = QApplication::activeWindow();
6245 while(w && tlw->windowType() == Qt::Tool &&
6246 !w->isModal() && w->parentWidget()) {
6247 w = w->parentWidget()->window();
6248 if(w == tlw)
6249 return true;
6252 #if defined(Q_WS_WIN32)
6253 HWND active = GetActiveWindow();
6254 if (!tlw->testAttribute(Qt::WA_WState_Created))
6255 return false;
6256 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6257 #else
6258 return false;
6259 #endif
6263 Puts the \a second widget after the \a first widget in the focus order.
6265 Note that since the tab order of the \a second widget is changed, you
6266 should order a chain like this:
6268 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6270 \e not like this:
6272 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6274 If \a first or \a second has a focus proxy, setTabOrder()
6275 correctly substitutes the proxy.
6277 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6279 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6281 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6282 return;
6284 if (first->window() != second->window()) {
6285 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6286 return;
6289 QWidget *fp = first->focusProxy();
6290 if (fp) {
6291 // If first is redirected, set first to the last child of first
6292 // that can take keyboard focus so that second is inserted after
6293 // that last child, and the focus order within first is (more
6294 // likely to be) preserved.
6295 QList<QWidget *> l = qFindChildren<QWidget *>(first);
6296 for (int i = l.size()-1; i >= 0; --i) {
6297 QWidget * next = l.at(i);
6298 if (next->window() == fp->window()) {
6299 fp = next;
6300 if (fp->focusPolicy() != Qt::NoFocus)
6301 break;
6304 first = fp;
6308 if (QWidget *sp = second->focusProxy())
6309 second = sp;
6311 // QWidget *fp = first->d_func()->focus_prev;
6312 QWidget *fn = first->d_func()->focus_next;
6314 if (fn == second)
6315 return;
6317 QWidget *sp = second->d_func()->focus_prev;
6318 QWidget *sn = second->d_func()->focus_next;
6320 fn->d_func()->focus_prev = second;
6321 first->d_func()->focus_next = second;
6323 second->d_func()->focus_next = fn;
6324 second->d_func()->focus_prev = first;
6326 sp->d_func()->focus_next = sn;
6327 sn->d_func()->focus_prev = sp;
6330 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6331 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6333 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6334 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6337 /*!\internal
6339 Moves the relevant subwidgets of this widget from the \a oldtlw's
6340 tab chain to that of the new parent, if there's anything to move and
6341 we're really moving
6343 This function is called from QWidget::reparent() *after* the widget
6344 has been reparented.
6346 \sa reparent()
6349 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6351 Q_Q(QWidget);
6352 if (oldtlw == q->window())
6353 return; // nothing to do
6355 if(focus_child)
6356 focus_child->clearFocus();
6358 // separate the focus chain into new (children of myself) and old (the rest)
6359 QWidget *firstOld = 0;
6360 //QWidget *firstNew = q; //invariant
6361 QWidget *o = 0; // last in the old list
6362 QWidget *n = q; // last in the new list
6364 bool prevWasNew = true;
6365 QWidget *w = focus_next;
6367 //Note: for efficiency, we do not maintain the list invariant inside the loop
6368 //we append items to the relevant list, and we optimize by not changing pointers
6369 //when subsequent items are going into the same list.
6370 while (w != q) {
6371 bool currentIsNew = q->isAncestorOf(w);
6372 if (currentIsNew) {
6373 if (!prevWasNew) {
6374 //prev was old -- append to new list
6375 n->d_func()->focus_next = w;
6376 w->d_func()->focus_prev = n;
6378 n = w;
6379 } else {
6380 if (prevWasNew) {
6381 //prev was new -- append to old list, if there is one
6382 if (o) {
6383 o->d_func()->focus_next = w;
6384 w->d_func()->focus_prev = o;
6385 } else {
6386 // "create" the old list
6387 firstOld = w;
6390 o = w;
6392 w = w->d_func()->focus_next;
6393 prevWasNew = currentIsNew;
6396 //repair the old list:
6397 if (firstOld) {
6398 o->d_func()->focus_next = firstOld;
6399 firstOld->d_func()->focus_prev = o;
6402 if (!q->isWindow()) {
6403 QWidget *topLevel = q->window();
6404 //insert new chain into toplevel's chain
6406 QWidget *prev = topLevel->d_func()->focus_prev;
6408 topLevel->d_func()->focus_prev = n;
6409 prev->d_func()->focus_next = q;
6411 focus_prev = prev;
6412 n->d_func()->focus_next = topLevel;
6413 } else {
6414 //repair the new list
6415 n->d_func()->focus_next = q;
6416 focus_prev = n;
6421 /*!\internal
6423 Measures the shortest distance from a point to a rect.
6425 This function is called from QDesktopwidget::screen(QPoint) to find the
6426 closest screen for a point.
6428 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6430 int dx = 0;
6431 int dy = 0;
6432 if (p.x() < r.left())
6433 dx = r.left() - p.x();
6434 else if (p.x() > r.right())
6435 dx = p.x() - r.right();
6436 if (p.y() < r.top())
6437 dy = r.top() - p.y();
6438 else if (p.y() > r.bottom())
6439 dy = p.y() - r.bottom();
6440 return dx + dy;
6444 \property QWidget::frameSize
6445 \brief the size of the widget including any window frame
6447 By default, this property contains a value that depends on the user's
6448 platform and screen geometry.
6450 QSize QWidget::frameSize() const
6452 Q_D(const QWidget);
6453 if (isWindow() && !(windowType() == Qt::Popup)) {
6454 QRect fs = d->frameStrut();
6455 return QSize(data->crect.width() + fs.left() + fs.right(),
6456 data->crect.height() + fs.top() + fs.bottom());
6458 return data->crect.size();
6461 /*! \fn void QWidget::move(int x, int y)
6463 \overload
6465 This corresponds to move(QPoint(\a x, \a y)).
6468 void QWidget::move(const QPoint &p)
6470 Q_D(QWidget);
6471 setAttribute(Qt::WA_Moved);
6472 if (isWindow())
6473 d->topData()->posFromMove = true;
6474 if (testAttribute(Qt::WA_WState_Created)) {
6475 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6476 p.y() + geometry().y() - QWidget::y(),
6477 width(), height(), true);
6478 d->setDirtyOpaqueRegion();
6479 } else {
6480 data->crect.moveTopLeft(p); // no frame yet
6481 setAttribute(Qt::WA_PendingMoveEvent);
6485 /*! \fn void QWidget::resize(int w, int h)
6486 \overload
6488 This corresponds to resize(QSize(\a w, \a h)).
6491 void QWidget::resize(const QSize &s)
6493 Q_D(QWidget);
6494 setAttribute(Qt::WA_Resized);
6495 if (testAttribute(Qt::WA_WState_Created)) {
6496 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6497 d->setDirtyOpaqueRegion();
6498 } else {
6499 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6500 setAttribute(Qt::WA_PendingResizeEvent);
6504 void QWidget::setGeometry(const QRect &r)
6506 Q_D(QWidget);
6507 setAttribute(Qt::WA_Resized);
6508 setAttribute(Qt::WA_Moved);
6509 if (isWindow())
6510 d->topData()->posFromMove = false;
6511 if (testAttribute(Qt::WA_WState_Created)) {
6512 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6513 d->setDirtyOpaqueRegion();
6514 } else {
6515 data->crect.setTopLeft(r.topLeft());
6516 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6517 setAttribute(Qt::WA_PendingMoveEvent);
6518 setAttribute(Qt::WA_PendingResizeEvent);
6523 \since 4.2
6524 Saves the current geometry and state for top-level widgets.
6526 To save the geometry when the window closes, you can
6527 implement a close event like this:
6529 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6531 See the \l{Window Geometry} documentation for an overview of geometry
6532 issues with windows.
6534 Use QMainWindow::saveState() to save the geometry and the state of
6535 toolbars and dock widgets.
6537 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6539 QByteArray QWidget::saveGeometry() const
6541 QByteArray array;
6542 QDataStream stream(&array, QIODevice::WriteOnly);
6543 stream.setVersion(QDataStream::Qt_4_0);
6544 const quint32 magicNumber = 0x1D9D0CB;
6545 quint16 majorVersion = 1;
6546 quint16 minorVersion = 0;
6547 stream << magicNumber
6548 << majorVersion
6549 << minorVersion
6550 << frameGeometry()
6551 << normalGeometry()
6552 << qint32(QApplication::desktop()->screenNumber(this))
6553 << quint8(windowState() & Qt::WindowMaximized)
6554 << quint8(windowState() & Qt::WindowFullScreen);
6555 return array;
6559 \since 4.2
6561 Restores the geometry and state top-level widgets stored in the
6562 byte array \a geometry. Returns true on success; otherwise
6563 returns false.
6565 If the restored geometry is off-screen, it will be modified to be
6566 inside the available screen geometry.
6568 To restore geometry saved using QSettings, you can use code like
6569 this:
6571 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6573 See the \l{Window Geometry} documentation for an overview of geometry
6574 issues with windows.
6576 Use QMainWindow::restoreState() to restore the geometry and the
6577 state of toolbars and dock widgets.
6579 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6581 bool QWidget::restoreGeometry(const QByteArray &geometry)
6583 if (geometry.size() < 4)
6584 return false;
6585 QDataStream stream(geometry);
6586 stream.setVersion(QDataStream::Qt_4_0);
6588 const quint32 magicNumber = 0x1D9D0CB;
6589 quint32 storedMagicNumber;
6590 stream >> storedMagicNumber;
6591 if (storedMagicNumber != magicNumber)
6592 return false;
6594 const quint16 currentMajorVersion = 1;
6595 quint16 majorVersion = 0;
6596 quint16 minorVersion = 0;
6598 stream >> majorVersion >> minorVersion;
6600 if (majorVersion != currentMajorVersion)
6601 return false;
6602 // (Allow all minor versions.)
6604 QRect restoredFrameGeometry;
6605 QRect restoredNormalGeometry;
6606 qint32 restoredScreenNumber;
6607 quint8 maximized;
6608 quint8 fullScreen;
6610 stream >> restoredFrameGeometry
6611 >> restoredNormalGeometry
6612 >> restoredScreenNumber
6613 >> maximized
6614 >> fullScreen;
6616 const int frameHeight = 20;
6617 if (!restoredFrameGeometry.isValid())
6618 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6620 if (!restoredNormalGeometry.isValid())
6621 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6622 if (!restoredNormalGeometry.isValid()) {
6623 // use the widget's adjustedSize if the sizeHint() doesn't help
6624 restoredNormalGeometry.setSize(restoredNormalGeometry
6625 .size()
6626 .expandedTo(d_func()->adjustedSize()));
6629 const QDesktopWidget * const desktop = QApplication::desktop();
6630 if (restoredScreenNumber >= desktop->numScreens())
6631 restoredScreenNumber = desktop->primaryScreen();
6633 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6635 // Modify the restored geometry if we are about to restore to coordinates
6636 // that would make the window "lost". This happens if:
6637 // - The restored geometry is completely oustside the available geometry
6638 // - The title bar is outside the available geometry.
6639 // - (Mac only) The window is higher than the available geometry. It must
6640 // be possible to bring the size grip on screen by moving the window.
6641 #ifdef Q_WS_MAC
6642 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6643 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6644 #endif
6646 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6647 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6648 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6649 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6651 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6653 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6654 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6655 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6656 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6658 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6660 if (maximized || fullScreen) {
6661 // set geomerty before setting the window state to make
6662 // sure the window is maximized to the right screen.
6663 setGeometry(restoredNormalGeometry);
6664 Qt::WindowStates ws = windowState();
6665 if (maximized)
6666 ws |= Qt::WindowMaximized;
6667 if (fullScreen)
6668 ws |= Qt::WindowFullScreen;
6669 setWindowState(ws);
6670 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6671 } else {
6672 QPoint offset;
6673 #ifdef Q_WS_X11
6674 if (isFullScreen())
6675 offset = d_func()->topData()->fullScreenOffset;
6676 #endif
6677 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6678 move(restoredFrameGeometry.topLeft() + offset);
6679 resize(restoredNormalGeometry.size());
6681 return true;
6684 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6685 \overload
6687 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6691 Sets the margins around the contents of the widget to have the
6692 sizes \a left, \a top, \a right, and \a bottom. The margins are
6693 used by the layout system, and may be used by subclasses to
6694 specify the area to draw in (e.g. excluding the frame).
6696 Changing the margins will trigger a resizeEvent().
6698 \sa contentsRect(), getContentsMargins()
6700 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6702 Q_D(QWidget);
6703 if (left == d->leftmargin && top == d->topmargin
6704 && right == d->rightmargin && bottom == d->bottommargin)
6705 return;
6706 d->leftmargin = left;
6707 d->topmargin = top;
6708 d->rightmargin = right;
6709 d->bottommargin = bottom;
6711 if (QLayout *l=d->layout)
6712 l->update(); //force activate; will do updateGeometry
6713 else
6714 updateGeometry();
6716 // ### Qt 5: compat, remove
6717 if (isVisible()) {
6718 update();
6719 QResizeEvent e(data->crect.size(), data->crect.size());
6720 QApplication::sendEvent(this, &e);
6721 } else {
6722 setAttribute(Qt::WA_PendingResizeEvent, true);
6725 QEvent e(QEvent::ContentsRectChange);
6726 QApplication::sendEvent(this, &e);
6729 /*! Returns the widget's contents margins for \a left, \a top, \a
6730 right, and \a bottom.
6732 \sa setContentsMargins(), contentsRect()
6734 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6736 Q_D(const QWidget);
6737 if (left)
6738 *left = d->leftmargin;
6739 if (top)
6740 *top = d->topmargin;
6741 if (right)
6742 *right = d->rightmargin;
6743 if (bottom)
6744 *bottom = d->bottommargin;
6748 Returns the area inside the widget's margins.
6750 \sa setContentsMargins(), getContentsMargins()
6752 QRect QWidget::contentsRect() const
6754 Q_D(const QWidget);
6755 return QRect(QPoint(d->leftmargin, d->topmargin),
6756 QPoint(data->crect.width() - 1 - d->rightmargin,
6757 data->crect.height() - 1 - d->bottommargin));
6764 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6766 This signal is emitted when the widget's \l contextMenuPolicy is
6767 Qt::CustomContextMenu, and the user has requested a context menu on
6768 the widget. The position \a pos is the position of the context menu
6769 event that the widget receives. Normally this is in widget
6770 coordinates. The exception to this rule is QAbstractScrollArea and
6771 its subclasses that map the context menu event to coordinates of the
6772 \link QAbstractScrollArea::viewport() viewport() \endlink .
6775 \sa mapToGlobal() QMenu contextMenuPolicy
6780 \property QWidget::contextMenuPolicy
6781 \brief how the widget shows a context menu
6783 The default value of this property is Qt::DefaultContextMenu,
6784 which means the contextMenuEvent() handler is called. Other values
6785 are Qt::NoContextMenu, Qt::PreventContextMenu,
6786 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6787 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6788 emitted.
6790 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6793 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6795 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6798 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6800 data->context_menu_policy = (uint) policy;
6804 \property QWidget::focusPolicy
6805 \brief the way the widget accepts keyboard focus
6807 The policy is Qt::TabFocus if the widget accepts keyboard
6808 focus by tabbing, Qt::ClickFocus if the widget accepts
6809 focus by clicking, Qt::StrongFocus if it accepts both, and
6810 Qt::NoFocus (the default) if it does not accept focus at
6811 all.
6813 You must enable keyboard focus for a widget if it processes
6814 keyboard events. This is normally done from the widget's
6815 constructor. For instance, the QLineEdit constructor calls
6816 setFocusPolicy(Qt::StrongFocus).
6818 If the widget has a focus proxy, then the focus policy will
6819 be propagated to it.
6821 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6825 Qt::FocusPolicy QWidget::focusPolicy() const
6827 return (Qt::FocusPolicy)data->focus_policy;
6830 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6832 data->focus_policy = (uint) policy;
6833 Q_D(QWidget);
6834 if (d->extra && d->extra->focus_proxy)
6835 d->extra->focus_proxy->setFocusPolicy(policy);
6839 \property QWidget::updatesEnabled
6840 \brief whether updates are enabled
6842 An updates enabled widget receives paint events and has a system
6843 background; a disabled widget does not. This also implies that
6844 calling update() and repaint() has no effect if updates are
6845 disabled.
6847 By default, this property is true.
6849 setUpdatesEnabled() is normally used to disable updates for a
6850 short period of time, for instance to avoid screen flicker during
6851 large changes. In Qt, widgets normally do not generate screen
6852 flicker, but on X11 the server might erase regions on the screen
6853 when widgets get hidden before they can be replaced by other
6854 widgets. Disabling updates solves this.
6856 Example:
6857 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6859 Disabling a widget implicitly disables all its children. Enabling a widget
6860 enables all child widgets \e except top-level widgets or those that
6861 have been explicitly disabled. Re-enabling updates implicitly calls
6862 update() on the widget.
6864 \sa paintEvent()
6866 void QWidget::setUpdatesEnabled(bool enable)
6868 Q_D(QWidget);
6869 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6870 d->setUpdatesEnabled_helper(enable);
6873 /*! \fn void QWidget::show()
6875 Shows the widget and its child widgets. This function is
6876 equivalent to setVisible(true).
6878 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6879 showNormal(), isVisible()
6883 /*! \internal
6885 Makes the widget visible in the isVisible() meaning of the word.
6886 It is only called for toplevels or widgets with visible parents.
6888 void QWidgetPrivate::show_recursive()
6890 Q_Q(QWidget);
6891 // polish if necessary
6893 if (!q->testAttribute(Qt::WA_WState_Created))
6894 createRecursively();
6895 q->ensurePolished();
6897 #ifdef QT3_SUPPORT
6898 if(sendChildEvents)
6899 QApplication::sendPostedEvents(q, QEvent::ChildInserted);
6900 #endif
6901 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6902 q->parentWidget()->d_func()->layout->activate();
6903 // activate our layout before we and our children become visible
6904 if (layout)
6905 layout->activate();
6907 show_helper();
6910 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6912 Q_Q(QWidget);
6914 disableUpdates = disableUpdates && q->updatesEnabled();
6915 if (disableUpdates)
6916 q->setAttribute(Qt::WA_UpdatesDisabled);
6918 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6919 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6920 QApplication::sendEvent(q, &e);
6921 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6924 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6925 QResizeEvent e(data.crect.size(), QSize());
6926 QApplication::sendEvent(q, &e);
6927 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6930 if (disableUpdates)
6931 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6933 if (!recursive)
6934 return;
6936 for (int i = 0; i < children.size(); ++i) {
6937 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6938 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6942 void QWidgetPrivate::activateChildLayoutsRecursively()
6944 sendPendingMoveAndResizeEvents(false, true);
6946 for (int i = 0; i < children.size(); ++i) {
6947 QWidget *child = qobject_cast<QWidget *>(children.at(i));
6948 if (!child || child->isHidden() || child->isWindow())
6949 continue;
6951 child->ensurePolished();
6953 // Activate child's layout
6954 QWidgetPrivate *childPrivate = child->d_func();
6955 if (childPrivate->layout)
6956 childPrivate->layout->activate();
6958 // Pretend we're visible.
6959 const bool wasVisible = child->isVisible();
6960 if (!wasVisible)
6961 child->setAttribute(Qt::WA_WState_Visible);
6963 // Do the same for all my children.
6964 childPrivate->activateChildLayoutsRecursively();
6966 // We're not cheating anymore.
6967 if (!wasVisible)
6968 child->setAttribute(Qt::WA_WState_Visible, false);
6972 void QWidgetPrivate::show_helper()
6974 Q_Q(QWidget);
6975 data.in_show = true; // qws optimization
6976 // make sure we receive pending move and resize events
6977 sendPendingMoveAndResizeEvents();
6979 // become visible before showing all children
6980 q->setAttribute(Qt::WA_WState_Visible);
6982 // finally show all children recursively
6983 showChildren(false);
6985 #ifdef QT3_SUPPORT
6986 if (q->parentWidget() && sendChildEvents)
6987 QApplication::sendPostedEvents(q->parentWidget(),
6988 QEvent::ChildInserted);
6989 #endif
6992 // popup handling: new popups and tools need to be raised, and
6993 // existing popups must be closed. Also propagate the current
6994 // windows's KeyboardFocusChange status.
6995 if (q->isWindow()) {
6996 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
6997 q->raise();
6998 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
6999 q->setAttribute(Qt::WA_KeyboardFocusChange);
7000 } else {
7001 while (QApplication::activePopupWidget()) {
7002 if (!QApplication::activePopupWidget()->close())
7003 break;
7008 // Automatic embedding of child windows of widgets already embedded into
7009 // QGraphicsProxyWidget when they are shown the first time.
7010 bool isEmbedded = false;
7011 #ifndef QT_NO_GRAPHICSVIEW
7012 if (q->isWindow()) {
7013 isEmbedded = q->graphicsProxyWidget() ? true : false;
7014 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7015 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7016 if (ancestorProxy) {
7017 isEmbedded = true;
7018 ancestorProxy->d_func()->embedSubWindow(q);
7022 #else
7023 Q_UNUSED(isEmbedded);
7024 #endif
7026 // On Windows, show the popup now so that our own focus handling
7027 // stores the correct old focus widget even if it's stolen in the
7028 // showevent
7029 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
7030 if (!isEmbedded && q->windowType() == Qt::Popup)
7031 qApp->d_func()->openPopup(q);
7032 #endif
7034 // send the show event before showing the window
7035 QShowEvent showEvent;
7036 QApplication::sendEvent(q, &showEvent);
7038 if (!isEmbedded && q->isModal() && q->isWindow())
7039 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7040 // stacking might be wrong
7041 QApplicationPrivate::enterModal(q);
7044 show_sys();
7046 #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
7047 if (!isEmbedded && q->windowType() == Qt::Popup)
7048 qApp->d_func()->openPopup(q);
7049 #endif
7051 #ifndef QT_NO_ACCESSIBILITY
7052 if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
7053 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
7054 #endif
7056 if (QApplicationPrivate::hidden_focus_widget == q) {
7057 QApplicationPrivate::hidden_focus_widget = 0;
7058 q->setFocus(Qt::OtherFocusReason);
7061 // Process events when showing a Qt::SplashScreen widget before the event loop
7062 // is spinnning; otherwise it might not show up on particular platforms.
7063 // This makes QSplashScreen behave the same on all platforms.
7064 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7065 QApplication::processEvents();
7067 data.in_show = false; // reset qws optimization
7070 /*! \fn void QWidget::hide()
7072 Hides the widget. This function is equivalent to
7073 setVisible(false).
7076 \note If you are working with QDialog or its subclasses and you invoke
7077 the show() function after this function, the dialog will be displayed in
7078 its original position.
7080 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7083 /*!\internal
7085 void QWidgetPrivate::hide_helper()
7087 Q_Q(QWidget);
7089 bool isEmbedded = false;
7090 #if !defined QT_NO_GRAPHICSVIEW
7091 isEmbedded = q->isWindow() && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7092 #else
7093 Q_UNUSED(isEmbedded);
7094 #endif
7096 if (!isEmbedded && (q->windowType() == Qt::Popup))
7097 qApp->d_func()->closePopup(q);
7099 // Move test modal here. Otherwise, a modal dialog could get
7100 // destroyed and we lose all access to its parent because we haven't
7101 // left modality. (Eg. modal Progress Dialog)
7102 if (!isEmbedded && q->isModal() && q->isWindow())
7103 QApplicationPrivate::leaveModal(q);
7105 #if defined(Q_WS_WIN)
7106 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7107 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7108 q->parentWidget()->activateWindow(); // Activate parent
7109 #endif
7111 q->setAttribute(Qt::WA_Mapped, false);
7112 hide_sys();
7114 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7116 if (wasVisible) {
7117 q->setAttribute(Qt::WA_WState_Visible, false);
7121 QHideEvent hideEvent;
7122 QApplication::sendEvent(q, &hideEvent);
7123 hideChildren(false);
7125 // next bit tries to move the focus if the focus widget is now
7126 // hidden.
7127 if (wasVisible) {
7128 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
7129 qApp->d_func()->sendSyntheticEnterLeave(q);
7130 #endif
7132 QWidget *fw = QApplication::focusWidget();
7133 while (fw && !fw->isWindow()) {
7134 if (fw == q) {
7135 q->focusNextPrevChild(true);
7136 break;
7138 fw = fw->parentWidget();
7142 if (QWidgetBackingStore *bs = maybeBackingStore())
7143 bs->removeDirtyWidget(q);
7145 #ifndef QT_NO_ACCESSIBILITY
7146 if (wasVisible)
7147 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
7148 #endif
7152 \fn bool QWidget::isHidden() const
7154 Returns true if the widget is hidden, otherwise returns false.
7156 A hidden widget will only become visible when show() is called on
7157 it. It will not be automatically shown when the parent is shown.
7159 To check visiblity, use !isVisible() instead (notice the exclamation mark).
7161 isHidden() implies !isVisible(), but a widget can be not visible
7162 and not hidden at the same time. This is the case for widgets that are children of
7163 widgets that are not visible.
7166 Widgets are hidden if:
7167 \list
7168 \o they were created as independent windows,
7169 \o they were created as children of visible widgets,
7170 \o hide() or setVisible(false) was called.
7171 \endlist
7175 void QWidget::setVisible(bool visible)
7177 if (visible) { // show
7178 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7179 return;
7181 Q_D(QWidget);
7183 // Designer uses a trick to make grabWidget work without showing
7184 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7185 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7186 parentWidget()->window()->d_func()->createRecursively();
7188 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7189 //but not children of non-visible parents
7190 QWidget *pw = parentWidget();
7191 if (!testAttribute(Qt::WA_WState_Created)
7192 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7193 create();
7196 #if defined(Q_WS_X11)
7197 if (windowType() == Qt::Window)
7198 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7199 #elif defined(Q_WS_QWS)
7200 if (windowType() == Qt::Window)
7201 QApplicationPrivate::applyQWSSpecificCommandLineArguments(this);
7202 #endif
7204 bool wasResized = testAttribute(Qt::WA_Resized);
7205 Qt::WindowStates initialWindowState = windowState();
7207 // polish if necessary
7208 ensurePolished();
7210 // remember that show was called explicitly
7211 setAttribute(Qt::WA_WState_ExplicitShowHide);
7212 // whether we need to inform the parent widget immediately
7213 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7214 // we are no longer hidden
7215 setAttribute(Qt::WA_WState_Hidden, false);
7217 if (needUpdateGeometry)
7218 d->updateGeometry_helper(true);
7220 #ifdef QT3_SUPPORT
7221 QApplication::sendPostedEvents(this, QEvent::ChildInserted);
7222 #endif
7223 // activate our layout before we and our children become visible
7224 if (d->layout)
7225 d->layout->activate();
7227 if (!isWindow()) {
7228 QWidget *parent = parentWidget();
7229 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7230 parent->d_func()->layout->activate();
7231 if (parent->isWindow())
7232 break;
7233 parent = parent->parentWidget();
7235 if (parent && !d->getOpaqueRegion().isEmpty())
7236 parent->d_func()->setDirtyOpaqueRegion();
7239 // adjust size if necessary
7240 if (!wasResized
7241 && (isWindow() || !parentWidget()->d_func()->layout)) {
7242 if (isWindow()) {
7243 adjustSize();
7244 if (windowState() != initialWindowState)
7245 setWindowState(initialWindowState);
7246 } else {
7247 adjustSize();
7249 setAttribute(Qt::WA_Resized, false);
7252 setAttribute(Qt::WA_KeyboardFocusChange, false);
7254 if (isWindow() || parentWidget()->isVisible()) {
7255 // remove posted quit events when showing a new window
7256 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
7258 d->show_helper();
7260 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
7261 qApp->d_func()->sendSyntheticEnterLeave(this);
7262 #endif
7265 QEvent showToParentEvent(QEvent::ShowToParent);
7266 QApplication::sendEvent(this, &showToParentEvent);
7267 } else { // hide
7268 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7269 return;
7270 #if defined(Q_WS_WIN)
7271 // reset WS_DISABLED style in a Blocked window
7272 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7273 && QApplicationPrivate::isBlockedByModal(this))
7275 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7276 dwStyle &= ~WS_DISABLED;
7277 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7279 #endif
7280 if (QApplicationPrivate::hidden_focus_widget == this)
7281 QApplicationPrivate::hidden_focus_widget = 0;
7283 Q_D(QWidget);
7285 // hw: The test on getOpaqueRegion() needs to be more intelligent
7286 // currently it doesn't work if the widget is hidden (the region will
7287 // be clipped). The real check should be testing the cached region
7288 // (and dirty flag) directly.
7289 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7290 parentWidget()->d_func()->setDirtyOpaqueRegion();
7292 setAttribute(Qt::WA_WState_Hidden);
7293 setAttribute(Qt::WA_WState_ExplicitShowHide);
7294 if (testAttribute(Qt::WA_WState_Created))
7295 d->hide_helper();
7297 // invalidate layout similar to updateGeometry()
7298 if (!isWindow() && parentWidget()) {
7299 if (parentWidget()->d_func()->layout)
7300 parentWidget()->d_func()->layout->invalidate();
7301 else if (parentWidget()->isVisible())
7302 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7305 QEvent hideToParentEvent(QEvent::HideToParent);
7306 QApplication::sendEvent(this, &hideToParentEvent);
7310 /*!\fn void QWidget::setHidden(bool hidden)
7312 Convenience function, equivalent to setVisible(!\a hidden).
7315 /*!\fn void QWidget::setShown(bool shown)
7317 Use setVisible(\a shown) instead.
7321 void QWidgetPrivate::_q_showIfNotHidden()
7323 Q_Q(QWidget);
7324 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7325 q->setVisible(true);
7328 void QWidgetPrivate::showChildren(bool spontaneous)
7330 QList<QObject*> childList = children;
7331 for (int i = 0; i < childList.size(); ++i) {
7332 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7333 if (!widget
7334 || widget->isWindow()
7335 || widget->testAttribute(Qt::WA_WState_Hidden))
7336 continue;
7337 if (spontaneous) {
7338 widget->setAttribute(Qt::WA_Mapped);
7339 widget->d_func()->showChildren(true);
7340 QShowEvent e;
7341 QApplication::sendSpontaneousEvent(widget, &e);
7342 } else {
7343 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7344 widget->d_func()->show_recursive();
7345 else
7346 widget->show();
7351 void QWidgetPrivate::hideChildren(bool spontaneous)
7353 QList<QObject*> childList = children;
7354 for (int i = 0; i < childList.size(); ++i) {
7355 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7356 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7357 continue;
7358 if (spontaneous)
7359 widget->setAttribute(Qt::WA_Mapped, false);
7360 else
7361 widget->setAttribute(Qt::WA_WState_Visible, false);
7362 widget->d_func()->hideChildren(spontaneous);
7363 QHideEvent e;
7364 if (spontaneous) {
7365 QApplication::sendSpontaneousEvent(widget, &e);
7366 } else {
7367 QApplication::sendEvent(widget, &e);
7368 if (widget->internalWinId()
7369 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7370 // hide_sys() on an ancestor won't have any affect on this
7371 // widget, so it needs an explicit hide_sys() of its own
7372 widget->d_func()->hide_sys();
7375 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
7376 qApp->d_func()->sendSyntheticEnterLeave(widget);
7377 #endif
7378 #ifndef QT_NO_ACCESSIBILITY
7379 if (!spontaneous)
7380 QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
7381 #endif
7385 bool QWidgetPrivate::close_helper(CloseMode mode)
7387 if (data.is_closing)
7388 return true;
7390 Q_Q(QWidget);
7391 data.is_closing = 1;
7393 QPointer<QWidget> that = q;
7394 QPointer<QWidget> parentWidget = q->parentWidget();
7396 #ifdef QT3_SUPPORT
7397 bool isMain = (QApplicationPrivate::main_widget == q);
7398 #endif
7399 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7400 if (mode != CloseNoEvent) {
7401 QCloseEvent e;
7402 if (mode == CloseWithSpontaneousEvent)
7403 QApplication::sendSpontaneousEvent(q, &e);
7404 else
7405 QApplication::sendEvent(q, &e);
7406 if (!that.isNull() && !e.isAccepted()) {
7407 data.is_closing = 0;
7408 return false;
7412 if (!that.isNull() && !q->isHidden())
7413 q->hide();
7415 #ifdef QT3_SUPPORT
7416 if (isMain)
7417 QApplication::quit();
7418 #endif
7419 // Attempt to close the application only if this widget has the
7420 // WA_QuitOnClose flag set set and has a non-visible parent
7421 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible() || parentWidget->testAttribute(Qt::WA_DontShowOnScreen));
7423 if (quitOnClose) {
7424 // If there is no non-withdrawn primary window left (except
7425 // the ones without QuitOnClose or with WA_DontShowOnScreen),
7426 // we emit the lastWindowClosed signal
7427 QWidgetList list = QApplication::topLevelWidgets();
7428 bool lastWindowClosed = true;
7429 for (int i = 0; i < list.size(); ++i) {
7430 QWidget *w = list.at(i);
7431 if ((w->isVisible() && !w->testAttribute(Qt::WA_DontShowOnScreen))
7432 && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose)) {
7433 lastWindowClosed = false;
7434 break;
7437 if (lastWindowClosed)
7438 QApplicationPrivate::emitLastWindowClosed();
7441 if (!that.isNull()) {
7442 data.is_closing = 0;
7443 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7444 q->setAttribute(Qt::WA_DeleteOnClose, false);
7445 q->deleteLater();
7448 return true;
7453 Closes this widget. Returns true if the widget was closed;
7454 otherwise returns false.
7456 First it sends the widget a QCloseEvent. The widget is \link
7457 hide() hidden\endlink if it \link QCloseEvent::accept()
7458 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7459 ignores\endlink the event, nothing happens. The default
7460 implementation of QWidget::closeEvent() accepts the close event.
7462 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7463 is also deleted. A close events is delivered to the widget no
7464 matter if the widget is visible or not.
7466 The \l QApplication::lastWindowClosed() signal is emitted when the
7467 last visible primary window (i.e. window with no parent) with the
7468 Qt::WA_QuitOnClose attribute set is closed. By default this
7469 attribute is set for all widgets except transient windows such as
7470 splash screens, tool windows, and popup menus.
7474 bool QWidget::close()
7476 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7480 \property QWidget::visible
7481 \brief whether the widget is visible
7483 Calling setVisible(true) or show() sets the widget to visible
7484 status if all its parent widgets up to the window are visible. If
7485 an ancestor is not visible, the widget won't become visible until
7486 all its ancestors are shown. If its size or position has changed,
7487 Qt guarantees that a widget gets move and resize events just
7488 before it is shown. If the widget has not been resized yet, Qt
7489 will adjust the widget's size to a useful default using
7490 adjustSize().
7492 Calling setVisible(false) or hide() hides a widget explicitly. An
7493 explicitly hidden widget will never become visible, even if all
7494 its ancestors become visible, unless you show it.
7496 A widget receives show and hide events when its visibility status
7497 changes. Between a hide and a show event, there is no need to
7498 waste CPU cycles preparing or displaying information to the user.
7499 A video application, for example, might simply stop generating new
7500 frames.
7502 A widget that happens to be obscured by other windows on the
7503 screen is considered to be visible. The same applies to iconified
7504 windows and windows that exist on another virtual
7505 desktop (on platforms that support this concept). A widget
7506 receives spontaneous show and hide events when its mapping status
7507 is changed by the window system, e.g. a spontaneous hide event
7508 when the user minimizes the window, and a spontaneous show event
7509 when the window is restored again.
7511 You almost never have to reimplement the setVisible() function. If
7512 you need to change some settings before a widget is shown, use
7513 showEvent() instead. If you need to do some delayed initialization
7514 use the Polish event delivered to the event() function.
7516 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7517 showEvent(), hideEvent()
7522 Returns true if this widget would become visible if \a ancestor is
7523 shown; otherwise returns false.
7525 The true case occurs if neither the widget itself nor any parent
7526 up to but excluding \a ancestor has been explicitly hidden.
7528 This function will still return true if the widget is obscured by
7529 other windows on the screen, but could be physically visible if it
7530 or they were to be moved.
7532 isVisibleTo(0) is identical to isVisible().
7534 \sa show() hide() isVisible()
7537 bool QWidget::isVisibleTo(QWidget* ancestor) const
7539 if (!ancestor)
7540 return isVisible();
7541 const QWidget * w = this;
7542 while (!w->isHidden()
7543 && !w->isWindow()
7544 && w->parentWidget()
7545 && w->parentWidget() != ancestor)
7546 w = w->parentWidget();
7547 return !w->isHidden();
7550 #ifdef QT3_SUPPORT
7552 Use visibleRegion() instead.
7554 QRect QWidget::visibleRect() const
7556 return d_func()->clipRect();
7558 #endif
7561 Returns the unobscured region where paint events can occur.
7563 For visible widgets, this is an approximation of the area not
7564 covered by other widgets; otherwise, this is an empty region.
7566 The repaint() function calls this function if necessary, so in
7567 general you do not need to call it.
7570 QRegion QWidget::visibleRegion() const
7572 Q_D(const QWidget);
7574 QRect clipRect = d->clipRect();
7575 if (clipRect.isEmpty())
7576 return QRegion();
7577 QRegion r(clipRect);
7578 d->subtractOpaqueChildren(r, clipRect);
7579 d->subtractOpaqueSiblings(r);
7580 #ifdef Q_WS_QWS
7581 const QWSWindowSurface *surface = static_cast<const QWSWindowSurface*>(windowSurface());
7582 if (surface) {
7583 const QPoint offset = mapTo(surface->window(), QPoint());
7584 r &= surface->clipRegion().translated(-offset);
7586 #endif
7587 return r;
7591 QSize QWidgetPrivate::adjustedSize() const
7593 Q_Q(const QWidget);
7595 QSize s = q->sizeHint();
7597 if (q->isWindow()) {
7598 Qt::Orientations exp;
7599 if (layout) {
7600 if (layout->hasHeightForWidth())
7601 s.setHeight(layout->totalHeightForWidth(s.width()));
7602 exp = layout->expandingDirections();
7603 } else
7605 if (q->sizePolicy().hasHeightForWidth())
7606 s.setHeight(q->heightForWidth(s.width()));
7607 exp = q->sizePolicy().expandingDirections();
7609 if (exp & Qt::Horizontal)
7610 s.setWidth(qMax(s.width(), 200));
7611 if (exp & Qt::Vertical)
7612 s.setHeight(qMax(s.height(), 100));
7613 #if defined(Q_WS_X11)
7614 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7615 #else // all others
7616 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7617 #endif
7618 #if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN)
7619 s.setWidth(qMin(s.width(), screen.width()));
7620 s.setHeight(qMin(s.height(), screen.height()));
7621 #else
7622 s.setWidth(qMin(s.width(), screen.width()*2/3));
7623 s.setHeight(qMin(s.height(), screen.height()*2/3));
7624 #endif
7625 if (QTLWExtra *extra = maybeTopData())
7626 extra->sizeAdjusted = true;
7629 if (!s.isValid()) {
7630 QRect r = q->childrenRect(); // get children rectangle
7631 if (r.isNull())
7632 return s;
7633 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7636 return s;
7640 Adjusts the size of the widget to fit its contents.
7642 This function uses sizeHint() if it is valid, i.e., the size hint's width
7643 and height are \>= 0. Otherwise, it sets the size to the children
7644 rectangle that covers all child widgets (the union of all child widget
7645 rectangles).
7647 For windows, the screen size is also taken into account. If the sizeHint()
7648 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7649 {expanding}, the window will be at least (200, 100). The maximum size of
7650 a window is 2/3 of the screen's width and height.
7652 \sa sizeHint(), childrenRect()
7655 void QWidget::adjustSize()
7657 Q_D(QWidget);
7658 ensurePolished();
7659 QSize s = d->adjustedSize();
7660 if (s.isValid())
7661 resize(s);
7666 \property QWidget::sizeHint
7667 \brief the recommended size for the widget
7669 If the value of this property is an invalid size, no size is
7670 recommended.
7672 The default implementation of sizeHint() returns an invalid size
7673 if there is no layout for this widget, and returns the layout's
7674 preferred size otherwise.
7676 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7677 setMinimumSize(), updateGeometry()
7680 QSize QWidget::sizeHint() const
7682 Q_D(const QWidget);
7683 if (d->layout)
7684 return d->layout->totalSizeHint();
7685 return QSize(-1, -1);
7689 \property QWidget::minimumSizeHint
7690 \brief the recommended minimum size for the widget
7692 If the value of this property is an invalid size, no minimum size
7693 is recommended.
7695 The default implementation of minimumSizeHint() returns an invalid
7696 size if there is no layout for this widget, and returns the
7697 layout's minimum size otherwise. Most built-in widgets reimplement
7698 minimumSizeHint().
7700 \l QLayout will never resize a widget to a size smaller than the
7701 minimum size hint unless minimumSize() is set or the size policy is
7702 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7703 size hint will be ignored.
7705 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7707 QSize QWidget::minimumSizeHint() const
7709 Q_D(const QWidget);
7710 if (d->layout)
7711 return d->layout->totalMinimumSize();
7712 return QSize(-1, -1);
7717 \fn QWidget *QWidget::parentWidget() const
7719 Returns the parent of this widget, or 0 if it does not have any
7720 parent widget.
7725 Returns true if this widget is a parent, (or grandparent and so on
7726 to any level), of the given \a child, and both widgets are within
7727 the same window; otherwise returns false.
7730 bool QWidget::isAncestorOf(const QWidget *child) const
7732 while (child) {
7733 if (child == this)
7734 return true;
7735 if (child->isWindow())
7736 return false;
7737 child = child->parentWidget();
7739 return false;
7742 #if defined(Q_WS_WIN)
7743 inline void setDisabledStyle(QWidget *w, bool setStyle)
7745 // set/reset WS_DISABLED style.
7746 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7747 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7748 if (setStyle)
7749 dwStyle |= WS_DISABLED;
7750 else
7751 dwStyle &= ~WS_DISABLED;
7752 SetWindowLong(w->winId(), GWL_STYLE, dwStyle);
7753 // we might need to repaint in some situations (eg. menu)
7754 w->repaint();
7757 #endif
7759 /*****************************************************************************
7760 QWidget event handling
7761 *****************************************************************************/
7764 This is the main event handler; it handles event \a event. You can
7765 reimplement this function in a subclass, but we recommend using
7766 one of the specialized event handlers instead.
7768 Key press and release events are treated differently from other
7769 events. event() checks for Tab and Shift+Tab and tries to move the
7770 focus appropriately. If there is no widget to move the focus to
7771 (or the key press is not Tab or Shift+Tab), event() calls
7772 keyPressEvent().
7774 Mouse and tablet event handling is also slightly special: only
7775 when the widget is \l enabled, event() will call the specialized
7776 handlers such as mousePressEvent(); otherwise it will discard the
7777 event.
7779 This function returns true if the event was recognized, otherwise
7780 it returns false. If the recognized event was accepted (see \l
7781 QEvent::accepted), any further processing such as event
7782 propagation to the parent widget stops.
7784 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7785 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7786 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7787 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7788 QObject::event(), QObject::timerEvent()
7791 bool QWidget::event(QEvent *event)
7793 Q_D(QWidget);
7795 // ignore mouse events when disabled
7796 if (!isEnabled()) {
7797 switch(event->type()) {
7798 case QEvent::TabletPress:
7799 case QEvent::TabletRelease:
7800 case QEvent::TabletMove:
7801 case QEvent::MouseButtonPress:
7802 case QEvent::MouseButtonRelease:
7803 case QEvent::MouseButtonDblClick:
7804 case QEvent::MouseMove:
7805 case QEvent::TouchBegin:
7806 case QEvent::TouchUpdate:
7807 case QEvent::TouchEnd:
7808 case QEvent::ContextMenu:
7809 #ifndef QT_NO_WHEELEVENT
7810 case QEvent::Wheel:
7811 #endif
7812 return false;
7813 default:
7814 break;
7817 switch (event->type()) {
7818 case QEvent::MouseMove:
7819 mouseMoveEvent((QMouseEvent*)event);
7820 break;
7822 case QEvent::MouseButtonPress:
7823 // Don't reset input context here. Whether reset or not is
7824 // a responsibility of input method. reset() will be
7825 // called by mouseHandler() of input method if necessary
7826 // via mousePressEvent() of text widgets.
7827 #if 0
7828 resetInputContext();
7829 #endif
7830 mousePressEvent((QMouseEvent*)event);
7831 break;
7833 case QEvent::MouseButtonRelease:
7834 mouseReleaseEvent((QMouseEvent*)event);
7835 break;
7837 case QEvent::MouseButtonDblClick:
7838 mouseDoubleClickEvent((QMouseEvent*)event);
7839 break;
7840 #ifndef QT_NO_WHEELEVENT
7841 case QEvent::Wheel:
7842 wheelEvent((QWheelEvent*)event);
7843 break;
7844 #endif
7845 #ifndef QT_NO_TABLETEVENT
7846 case QEvent::TabletMove:
7847 case QEvent::TabletPress:
7848 case QEvent::TabletRelease:
7849 tabletEvent((QTabletEvent*)event);
7850 break;
7851 #endif
7852 #ifdef QT3_SUPPORT
7853 case QEvent::Accel:
7854 event->ignore();
7855 return false;
7856 #endif
7857 case QEvent::KeyPress: {
7858 QKeyEvent *k = (QKeyEvent *)event;
7859 bool res = false;
7860 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7861 if (k->key() == Qt::Key_Backtab
7862 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7863 res = focusNextPrevChild(false);
7864 else if (k->key() == Qt::Key_Tab)
7865 res = focusNextPrevChild(true);
7866 if (res)
7867 break;
7869 keyPressEvent(k);
7870 #ifdef QT_KEYPAD_NAVIGATION
7871 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7872 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7873 if (k->key() == Qt::Key_Up)
7874 res = focusNextPrevChild(false);
7875 else if (k->key() == Qt::Key_Down)
7876 res = focusNextPrevChild(true);
7877 if (res) {
7878 k->accept();
7879 break;
7882 #endif
7883 #ifndef QT_NO_WHATSTHIS
7884 if (!k->isAccepted()
7885 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7886 && d->whatsThis.size()) {
7887 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImMicroFocus).toRect().center()), d->whatsThis, this);
7888 k->accept();
7890 #endif
7892 break;
7894 case QEvent::KeyRelease:
7895 keyReleaseEvent((QKeyEvent*)event);
7896 // fall through
7897 case QEvent::ShortcutOverride:
7898 break;
7900 case QEvent::InputMethod:
7901 inputMethodEvent((QInputMethodEvent *) event);
7902 break;
7904 case QEvent::PolishRequest:
7905 ensurePolished();
7906 break;
7908 case QEvent::Polish: {
7909 style()->polish(this);
7910 setAttribute(Qt::WA_WState_Polished);
7911 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7912 d->resolveFont();
7913 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7914 d->resolvePalette();
7915 #ifdef QT3_SUPPORT
7916 if(d->sendChildEvents)
7917 QApplication::sendPostedEvents(this, QEvent::ChildInserted);
7918 #endif
7920 break;
7922 case QEvent::ApplicationWindowIconChange:
7923 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7924 d->setWindowIcon_sys();
7925 d->setWindowIcon_helper();
7927 break;
7928 case QEvent::FocusIn:
7929 d->setSoftKeys_sys(softKeys());
7930 focusInEvent((QFocusEvent*)event);
7931 break;
7933 case QEvent::FocusOut:
7934 focusOutEvent((QFocusEvent*)event);
7935 break;
7937 case QEvent::Enter:
7938 #ifndef QT_NO_STATUSTIP
7939 if (d->statusTip.size()) {
7940 QStatusTipEvent tip(d->statusTip);
7941 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7943 #endif
7944 enterEvent(event);
7945 break;
7947 case QEvent::Leave:
7948 #ifndef QT_NO_STATUSTIP
7949 if (d->statusTip.size()) {
7950 QString empty;
7951 QStatusTipEvent tip(empty);
7952 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7954 #endif
7955 leaveEvent(event);
7956 break;
7958 case QEvent::HoverEnter:
7959 case QEvent::HoverLeave:
7960 update();
7961 break;
7963 case QEvent::Paint:
7964 // At this point the event has to be delivered, regardless
7965 // whether the widget isVisible() or not because it
7966 // already went through the filters
7967 paintEvent((QPaintEvent*)event);
7968 break;
7970 case QEvent::Move:
7971 moveEvent((QMoveEvent*)event);
7972 break;
7974 case QEvent::Resize:
7975 resizeEvent((QResizeEvent*)event);
7976 break;
7978 case QEvent::Close:
7979 closeEvent((QCloseEvent *)event);
7980 break;
7982 #ifndef QT_NO_CONTEXTMENU
7983 case QEvent::ContextMenu:
7984 switch (data->context_menu_policy) {
7985 case Qt::PreventContextMenu:
7986 break;
7987 case Qt::DefaultContextMenu:
7988 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
7989 break;
7990 case Qt::CustomContextMenu:
7991 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
7992 break;
7993 #ifndef QT_NO_MENU
7994 case Qt::ActionsContextMenu:
7995 if (d->actions.count()) {
7996 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
7997 0, this);
7998 break;
8000 // fall through
8001 #endif
8002 default:
8003 event->ignore();
8004 break;
8006 break;
8007 #endif // QT_NO_CONTEXTMENU
8009 #ifndef QT_NO_DRAGANDDROP
8010 case QEvent::Drop:
8011 dropEvent((QDropEvent*) event);
8012 break;
8014 case QEvent::DragEnter:
8015 dragEnterEvent((QDragEnterEvent*) event);
8016 break;
8018 case QEvent::DragMove:
8019 dragMoveEvent((QDragMoveEvent*) event);
8020 break;
8022 case QEvent::DragLeave:
8023 dragLeaveEvent((QDragLeaveEvent*) event);
8024 break;
8025 #endif
8027 case QEvent::Show:
8028 showEvent((QShowEvent*) event);
8029 break;
8031 case QEvent::Hide:
8032 hideEvent((QHideEvent*) event);
8033 break;
8035 case QEvent::ShowWindowRequest:
8036 if (!isHidden())
8037 d->show_sys();
8038 break;
8040 case QEvent::ApplicationFontChange:
8041 d->resolveFont();
8042 break;
8043 case QEvent::ApplicationPaletteChange:
8044 if (!(windowType() == Qt::Desktop))
8045 d->resolvePalette();
8046 break;
8048 case QEvent::ToolBarChange:
8049 case QEvent::ActivationChange:
8050 case QEvent::EnabledChange:
8051 case QEvent::FontChange:
8052 case QEvent::StyleChange:
8053 case QEvent::PaletteChange:
8054 case QEvent::WindowTitleChange:
8055 case QEvent::IconTextChange:
8056 case QEvent::ModifiedChange:
8057 case QEvent::MouseTrackingChange:
8058 case QEvent::ParentChange:
8059 case QEvent::WindowStateChange:
8060 case QEvent::LocaleChange:
8061 case QEvent::MacSizeChange:
8062 case QEvent::ContentsRectChange:
8063 changeEvent(event);
8064 break;
8066 case QEvent::WindowActivate:
8067 case QEvent::WindowDeactivate: {
8068 #ifdef QT3_SUPPORT
8069 windowActivationChange(event->type() != QEvent::WindowActivate);
8070 #endif
8071 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8072 update();
8073 QList<QObject*> childList = d->children;
8074 for (int i = 0; i < childList.size(); ++i) {
8075 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8076 if (w && w->isVisible() && !w->isWindow())
8077 QApplication::sendEvent(w, event);
8080 if (isWindow() && isActiveWindow())
8081 d->setSoftKeys_sys(softKeys());
8083 break; }
8085 case QEvent::LanguageChange:
8086 #ifdef QT3_SUPPORT
8087 languageChange();
8088 #endif
8089 changeEvent(event);
8091 QList<QObject*> childList = d->children;
8092 for (int i = 0; i < childList.size(); ++i) {
8093 QObject *o = childList.at(i);
8094 QApplication::sendEvent(o, event);
8097 update();
8098 break;
8100 case QEvent::ApplicationLayoutDirectionChange:
8101 d->resolveLayoutDirection();
8102 break;
8104 case QEvent::LayoutDirectionChange:
8105 if (d->layout)
8106 d->layout->invalidate();
8107 update();
8108 changeEvent(event);
8109 break;
8110 case QEvent::UpdateRequest:
8111 d->syncBackingStore();
8112 break;
8113 case QEvent::UpdateLater:
8114 update(static_cast<QUpdateLaterEvent*>(event)->region());
8115 break;
8117 case QEvent::WindowBlocked:
8118 case QEvent::WindowUnblocked:
8120 QList<QObject*> childList = d->children;
8121 for (int i = 0; i < childList.size(); ++i) {
8122 QObject *o = childList.at(i);
8123 if (o != QApplication::activeModalWidget()) {
8124 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8125 // do not forward the event to child windows,
8126 // QApplication does this for us
8127 continue;
8129 QApplication::sendEvent(o, event);
8132 #if defined(Q_WS_WIN)
8133 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8134 #endif
8136 break;
8137 #ifndef QT_NO_TOOLTIP
8138 case QEvent::ToolTip:
8139 if (!d->toolTip.isEmpty())
8140 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8141 else
8142 event->ignore();
8143 break;
8144 #endif
8145 #ifndef QT_NO_WHATSTHIS
8146 case QEvent::WhatsThis:
8147 if (d->whatsThis.size())
8148 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8149 else
8150 event->ignore();
8151 break;
8152 case QEvent::QueryWhatsThis:
8153 if (d->whatsThis.isEmpty())
8154 event->ignore();
8155 break;
8156 #endif
8157 #ifndef QT_NO_ACCESSIBILITY
8158 case QEvent::AccessibilityDescription:
8159 case QEvent::AccessibilityHelp: {
8160 QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event);
8161 if (ev->child())
8162 return false;
8163 switch (ev->type()) {
8164 #ifndef QT_NO_TOOLTIP
8165 case QEvent::AccessibilityDescription:
8166 ev->setValue(d->toolTip);
8167 break;
8168 #endif
8169 #ifndef QT_NO_WHATSTHIS
8170 case QEvent::AccessibilityHelp:
8171 ev->setValue(d->whatsThis);
8172 break;
8173 #endif
8174 default:
8175 return false;
8177 break; }
8178 #endif
8179 case QEvent::EmbeddingControl:
8180 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8181 data->fstrut_dirty = false;
8182 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8183 d->topData()->embedded = 1;
8184 #endif
8185 break;
8186 #ifndef QT_NO_ACTION
8187 case QEvent::ActionAdded:
8188 case QEvent::ActionRemoved:
8189 case QEvent::ActionChanged:
8190 actionEvent((QActionEvent*)event);
8191 break;
8192 #endif
8194 case QEvent::KeyboardLayoutChange:
8196 changeEvent(event);
8198 // inform children of the change
8199 QList<QObject*> childList = d->children;
8200 for (int i = 0; i < childList.size(); ++i) {
8201 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8202 if (w && w->isVisible() && !w->isWindow())
8203 QApplication::sendEvent(w, event);
8205 break;
8207 #ifdef Q_WS_MAC
8208 case QEvent::MacGLWindowChange:
8209 d->needWindowChange = false;
8210 break;
8211 #endif
8212 case QEvent::TouchBegin:
8213 case QEvent::TouchUpdate:
8214 case QEvent::TouchEnd:
8216 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
8217 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first();
8218 if (touchPoint.isPrimary())
8219 break;
8221 // fake a mouse event!
8222 QEvent::Type eventType = QEvent::None;
8223 switch (touchEvent->type()) {
8224 case QEvent::TouchBegin:
8225 eventType = QEvent::MouseButtonPress;
8226 break;
8227 case QEvent::TouchUpdate:
8228 eventType = QEvent::MouseMove;
8229 break;
8230 case QEvent::TouchEnd:
8231 eventType = QEvent::MouseButtonRelease;
8232 break;
8233 default:
8234 Q_ASSERT(!true);
8235 break;
8237 if (eventType == QEvent::None)
8238 break;
8240 QMouseEvent mouseEvent(eventType,
8241 touchPoint.pos().toPoint(),
8242 touchPoint.screenPos().toPoint(),
8243 Qt::LeftButton,
8244 Qt::LeftButton,
8245 touchEvent->modifiers());
8246 (void) QApplication::sendEvent(this, &mouseEvent);
8247 break;
8249 case QEvent::SymbianDeferredFocusChanged: {
8250 #ifdef Q_OS_SYMBIAN
8251 d->handleSymbianDeferredFocusChanged();
8252 #endif
8253 break;
8255 #ifndef QT_NO_PROPERTIES
8256 case QEvent::DynamicPropertyChange: {
8257 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8258 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8259 uint value = property(propName.constData()).toUInt();
8260 if (!d->extra)
8261 d->createExtra();
8262 const char axis = propName.at(12);
8263 if (axis == 'X')
8264 d->extra->customDpiX = value;
8265 else if (axis == 'Y')
8266 d->extra->customDpiY = value;
8267 d->updateFont(d->data.fnt);
8269 // fall through
8271 #endif
8272 default:
8273 return QObject::event(event);
8275 return true;
8279 This event handler can be reimplemented to handle state changes.
8281 The state being changed in this event can be retrieved through event \a
8282 event.
8284 Change events include: QEvent::ToolBarChange,
8285 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8286 QEvent::StyleChange, QEvent::PaletteChange,
8287 QEvent::WindowTitleChange, QEvent::IconTextChange,
8288 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8289 QEvent::ParentChange, QEvent::WindowStateChange,
8290 QEvent::LanguageChange, QEvent::LocaleChange,
8291 QEvent::LayoutDirectionChange.
8294 void QWidget::changeEvent(QEvent * event)
8296 switch(event->type()) {
8297 case QEvent::EnabledChange:
8298 update();
8299 #ifndef QT_NO_ACCESSIBILITY
8300 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
8301 #endif
8302 break;
8304 case QEvent::FontChange:
8305 case QEvent::StyleChange: {
8306 Q_D(QWidget);
8307 update();
8308 updateGeometry();
8309 if (d->layout)
8310 d->layout->invalidate();
8311 #ifdef Q_WS_QWS
8312 if (isWindow())
8313 d->data.fstrut_dirty = true;
8314 #endif
8315 break;
8318 case QEvent::PaletteChange:
8319 update();
8320 break;
8322 #ifdef Q_WS_MAC
8323 case QEvent::MacSizeChange:
8324 updateGeometry();
8325 break;
8326 case QEvent::ToolTipChange:
8327 case QEvent::MouseTrackingChange:
8328 qt_mac_update_mouseTracking(this);
8329 break;
8330 #endif
8332 default:
8333 break;
8338 This event handler, for event \a event, can be reimplemented in a
8339 subclass to receive mouse move events for the widget.
8341 If mouse tracking is switched off, mouse move events only occur if
8342 a mouse button is pressed while the mouse is being moved. If mouse
8343 tracking is switched on, mouse move events occur even if no mouse
8344 button is pressed.
8346 QMouseEvent::pos() reports the position of the mouse cursor,
8347 relative to this widget. For press and release events, the
8348 position is usually the same as the position of the last mouse
8349 move event, but it might be different if the user's hand shakes.
8350 This is a feature of the underlying window system, not Qt.
8352 If you want to show a tooltip immediately, while the mouse is
8353 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8354 and show them as a tooltip), you must first enable mouse tracking
8355 as described above. Then, to ensure that the tooltip is updated
8356 immediately, you must call QToolTip::showText() instead of
8357 setToolTip() in your implementation of mouseMoveEvent().
8359 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8360 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8363 void QWidget::mouseMoveEvent(QMouseEvent *event)
8365 event->ignore();
8369 This event handler, for event \a event, can be reimplemented in a
8370 subclass to receive mouse press events for the widget.
8372 If you create new widgets in the mousePressEvent() the
8373 mouseReleaseEvent() may not end up where you expect, depending on
8374 the underlying window system (or X11 window manager), the widgets'
8375 location and maybe more.
8377 The default implementation implements the closing of popup widgets
8378 when you click outside the window. For other widget types it does
8379 nothing.
8381 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8382 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8385 void QWidget::mousePressEvent(QMouseEvent *event)
8387 event->ignore();
8388 if ((windowType() == Qt::Popup)) {
8389 event->accept();
8390 QWidget* w;
8391 while ((w = QApplication::activePopupWidget()) && w != this){
8392 w->close();
8393 if (QApplication::activePopupWidget() == w) // widget does not want to dissappear
8394 w->hide(); // hide at least
8396 if (!rect().contains(event->pos())){
8397 close();
8403 This event handler, for event \a event, can be reimplemented in a
8404 subclass to receive mouse release events for the widget.
8406 \sa mousePressEvent(), mouseDoubleClickEvent(),
8407 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8410 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8412 event->ignore();
8416 This event handler, for event \a event, can be reimplemented in a
8417 subclass to receive mouse double click events for the widget.
8419 The default implementation generates a normal mouse press event.
8421 Note that the widgets gets a mousePressEvent() and a
8422 mouseReleaseEvent() before the mouseDoubleClickEvent().
8424 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8425 event(), QMouseEvent
8428 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8430 mousePressEvent(event); // try mouse press event
8433 #ifndef QT_NO_WHEELEVENT
8435 This event handler, for event \a event, can be reimplemented in a
8436 subclass to receive wheel events for the widget.
8438 If you reimplement this handler, it is very important that you
8439 \link QWheelEvent ignore()\endlink the event if you do not handle
8440 it, so that the widget's parent can interpret it.
8442 The default implementation ignores the event.
8444 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8445 QWheelEvent
8448 void QWidget::wheelEvent(QWheelEvent *event)
8450 event->ignore();
8452 #endif // QT_NO_WHEELEVENT
8454 #ifndef QT_NO_TABLETEVENT
8456 This event handler, for event \a event, can be reimplemented in a
8457 subclass to receive tablet events for the widget.
8459 If you reimplement this handler, it is very important that you
8460 \link QTabletEvent ignore()\endlink the event if you do not handle
8461 it, so that the widget's parent can interpret it.
8463 The default implementation ignores the event.
8465 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8466 QTabletEvent
8469 void QWidget::tabletEvent(QTabletEvent *event)
8471 event->ignore();
8473 #endif // QT_NO_TABLETEVENT
8476 This event handler, for event \a event, can be reimplemented in a
8477 subclass to receive key press events for the widget.
8479 A widget must call setFocusPolicy() to accept focus initially and
8480 have focus in order to receive a key press event.
8482 If you reimplement this handler, it is very important that you
8483 call the base class implementation if you do not act upon the key.
8485 The default implementation closes popup widgets if the user
8486 presses Esc. Otherwise the event is ignored, so that the widget's
8487 parent can interpret it.
8489 Note that QKeyEvent starts with isAccepted() == true, so you do not
8490 need to call QKeyEvent::accept() - just do not call the base class
8491 implementation if you act upon the key.
8493 \sa keyReleaseEvent(), setFocusPolicy(),
8494 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8497 void QWidget::keyPressEvent(QKeyEvent *event)
8499 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8500 event->accept();
8501 close();
8502 } else {
8503 event->ignore();
8508 This event handler, for event \a event, can be reimplemented in a
8509 subclass to receive key release events for the widget.
8511 A widget must \link setFocusPolicy() accept focus\endlink
8512 initially and \link hasFocus() have focus\endlink in order to
8513 receive a key release event.
8515 If you reimplement this handler, it is very important that you
8516 call the base class implementation if you do not act upon the key.
8518 The default implementation ignores the event, so that the widget's
8519 parent can interpret it.
8521 Note that QKeyEvent starts with isAccepted() == true, so you do not
8522 need to call QKeyEvent::accept() - just do not call the base class
8523 implementation if you act upon the key.
8525 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8526 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8529 void QWidget::keyReleaseEvent(QKeyEvent *event)
8531 event->ignore();
8535 \fn void QWidget::focusInEvent(QFocusEvent *event)
8537 This event handler can be reimplemented in a subclass to receive
8538 keyboard focus events (focus received) for the widget. The event
8539 is passed in the \a event parameter
8541 A widget normally must setFocusPolicy() to something other than
8542 Qt::NoFocus in order to receive focus events. (Note that the
8543 application programmer can call setFocus() on any widget, even
8544 those that do not normally accept focus.)
8546 The default implementation updates the widget (except for windows
8547 that do not specify a focusPolicy()).
8549 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8550 keyReleaseEvent(), event(), QFocusEvent
8553 void QWidget::focusInEvent(QFocusEvent *)
8555 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8556 update();
8561 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8563 This event handler can be reimplemented in a subclass to receive
8564 keyboard focus events (focus lost) for the widget. The events is
8565 passed in the \a event parameter.
8567 A widget normally must setFocusPolicy() to something other than
8568 Qt::NoFocus in order to receive focus events. (Note that the
8569 application programmer can call setFocus() on any widget, even
8570 those that do not normally accept focus.)
8572 The default implementation updates the widget (except for windows
8573 that do not specify a focusPolicy()).
8575 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8576 keyReleaseEvent(), event(), QFocusEvent
8579 void QWidget::focusOutEvent(QFocusEvent *)
8581 if (focusPolicy() != Qt::NoFocus || !isWindow())
8582 update();
8586 \fn void QWidget::enterEvent(QEvent *event)
8588 This event handler can be reimplemented in a subclass to receive
8589 widget enter events which are passed in the \a event parameter.
8591 An event is sent to the widget when the mouse cursor enters the
8592 widget.
8594 \sa leaveEvent(), mouseMoveEvent(), event()
8597 void QWidget::enterEvent(QEvent *)
8602 \fn void QWidget::leaveEvent(QEvent *event)
8604 This event handler can be reimplemented in a subclass to receive
8605 widget leave events which are passed in the \a event parameter.
8607 A leave event is sent to the widget when the mouse cursor leaves
8608 the widget.
8610 \sa enterEvent(), mouseMoveEvent(), event()
8613 void QWidget::leaveEvent(QEvent *)
8618 \fn void QWidget::paintEvent(QPaintEvent *event)
8620 This event handler can be reimplemented in a subclass to receive paint
8621 events passed in \a event.
8623 A paint event is a request to repaint all or part of a widget. It can
8624 happen for one of the following reasons:
8626 \list
8627 \o repaint() or update() was invoked,
8628 \o the widget was obscured and has now been uncovered, or
8629 \o many other reasons.
8630 \endlist
8632 Many widgets can simply repaint their entire surface when asked to, but
8633 some slow widgets need to optimize by painting only the requested region:
8634 QPaintEvent::region(). This speed optimization does not change the result,
8635 as painting is clipped to that region during event processing. QListView
8636 and QTableView do this, for example.
8638 Qt also tries to speed up painting by merging multiple paint events into
8639 one. When update() is called several times or the window system sends
8640 several paint events, Qt merges these events into one event with a larger
8641 region (see QRegion::united()). The repaint() function does not permit this
8642 optimization, so we suggest using update() whenever possible.
8644 When the paint event occurs, the update region has normally been erased, so
8645 you are painting on the widget's background.
8647 The background can be set using setBackgroundRole() and setPalette().
8649 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8650 is no need to write double-buffering code in paintEvent() to avoid flicker.
8652 \bold{Note for the X11 platform}: It is possible to toggle global double
8653 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8655 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8657 \note Generally, you should refrain from calling update() or repaint()
8658 \bold{inside} a paintEvent(). For example, calling update() or repaint() on
8659 children inside a paintevent() results in undefined behavior; the child may
8660 or may not get a paint event.
8662 \warning If you are using a custom paint engine without Qt's backingstore,
8663 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8664 never be called; the backingstore will be used instead.
8666 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8667 {Analog Clock Example}
8670 void QWidget::paintEvent(QPaintEvent *)
8676 \fn void QWidget::moveEvent(QMoveEvent *event)
8678 This event handler can be reimplemented in a subclass to receive
8679 widget move events which are passed in the \a event parameter.
8680 When the widget receives this event, it is already at the new
8681 position.
8683 The old position is accessible through QMoveEvent::oldPos().
8685 \sa resizeEvent(), event(), move(), QMoveEvent
8688 void QWidget::moveEvent(QMoveEvent *)
8694 This event handler can be reimplemented in a subclass to receive
8695 widget resize events which are passed in the \a event parameter.
8696 When resizeEvent() is called, the widget already has its new
8697 geometry. The old size is accessible through
8698 QResizeEvent::oldSize().
8700 The widget will be erased and receive a paint event immediately
8701 after processing the resize event. No drawing need be (or should
8702 be) done inside this handler.
8705 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8706 {Scribble Example}
8709 void QWidget::resizeEvent(QResizeEvent * /* event */)
8713 #ifndef QT_NO_ACTION
8715 \fn void QWidget::actionEvent(QActionEvent *event)
8717 This event handler is called with the given \a event whenever the
8718 widget's actions are changed.
8720 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8722 void QWidget::actionEvent(QActionEvent *)
8726 #endif
8729 This event handler is called with the given \a event when Qt receives a window
8730 close request for a top-level widget from the window system.
8732 By default, the event is accepted and the widget is closed. You can reimplement
8733 this function to change the way the widget responds to window close requests.
8734 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8735 on all events.
8737 Main window applications typically use reimplementations of this function to check
8738 whether the user's work has been saved and ask for permission before closing.
8739 For example, the \l{Application Example} uses a helper function to determine whether
8740 or not to close the window:
8742 \snippet mainwindows/application/mainwindow.cpp 3
8743 \snippet mainwindows/application/mainwindow.cpp 4
8745 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8748 void QWidget::closeEvent(QCloseEvent *event)
8750 event->accept();
8753 #ifndef QT_NO_CONTEXTMENU
8755 This event handler, for event \a event, can be reimplemented in a
8756 subclass to receive widget context menu events.
8758 The handler is called when the widget's \l contextMenuPolicy is
8759 Qt::DefaultContextMenu.
8761 The default implementation ignores the context event.
8762 See the \l QContextMenuEvent documentation for more details.
8764 \sa event(), QContextMenuEvent customContextMenuRequested()
8767 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8769 event->ignore();
8771 #endif // QT_NO_CONTEXTMENU
8775 This event handler, for event \a event, can be reimplemented in a
8776 subclass to receive Input Method composition events. This handler
8777 is called when the state of the input method changes.
8779 Note that when creating custom text editing widgets, the
8780 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8781 (using the setAttribute() function) in order to receive input
8782 method events.
8784 The default implementation calls event->ignore(), which rejects the
8785 Input Method event. See the \l QInputMethodEvent documentation for more
8786 details.
8788 \sa event(), QInputMethodEvent
8790 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8792 event->ignore();
8796 This method is only relevant for input widgets. It is used by the
8797 input method to query a set of properties of the widget to be
8798 able to support complex input method operations as support for
8799 surrounding text and reconversions.
8801 \a query specifies which property is queried.
8803 \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
8805 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8807 switch(query) {
8808 case Qt::ImMicroFocus:
8809 return QRect(width()/2, 0, 1, height());
8810 case Qt::ImFont:
8811 return font();
8812 case Qt::ImAnchorPosition:
8813 // Fallback.
8814 return inputMethodQuery(Qt::ImCursorPosition);
8815 default:
8816 return QVariant();
8821 \property QWidget::inputMethodHints
8822 \brief What input method specific hints the widget has.
8824 This is only relevant for input widgets. It is used by
8825 the input method to retrieve hints as to how the input method
8826 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8827 is set, the input method may change its visual components to reflect
8828 that only numbers can be entered.
8830 \note The flags are only hints, so the particular input method
8831 implementation is free to ignore them. If you want to be
8832 sure that a certain type of characters are entered,
8833 you should also set a QValidator on the widget.
8835 The default value is Qt::ImhNone.
8837 \since 4.6
8839 \sa inputMethodQuery(), QInputContext
8841 Qt::InputMethodHints QWidget::inputMethodHints() const
8843 Q_D(const QWidget);
8844 return d->imHints;
8847 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8849 Q_D(QWidget);
8850 d->imHints = hints;
8851 // Optimisation to update input context only it has already been created.
8852 if (d->ic || qApp->d_func()->inputContext) {
8853 QInputContext *ic = inputContext();
8854 if (ic)
8855 ic->update();
8860 #ifndef QT_NO_DRAGANDDROP
8863 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8865 This event handler is called when a drag is in progress and the
8866 mouse enters this widget. The event is passed in the \a event parameter.
8868 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8869 move events}.
8871 See the \link dnd.html Drag-and-drop documentation\endlink for an
8872 overview of how to provide drag-and-drop in your application.
8874 \sa QDrag, QDragEnterEvent
8876 void QWidget::dragEnterEvent(QDragEnterEvent *)
8881 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8883 This event handler is called if a drag is in progress, and when
8884 any of the following conditions occur: the cursor enters this widget,
8885 the cursor moves within this widget, or a modifier key is pressed on
8886 the keyboard while this widget has the focus. The event is passed
8887 in the \a event parameter.
8889 See the \link dnd.html Drag-and-drop documentation\endlink for an
8890 overview of how to provide drag-and-drop in your application.
8892 \sa QDrag, QDragMoveEvent
8894 void QWidget::dragMoveEvent(QDragMoveEvent *)
8899 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8901 This event handler is called when a drag is in progress and the
8902 mouse leaves this widget. The event is passed in the \a event
8903 parameter.
8905 See the \link dnd.html Drag-and-drop documentation\endlink for an
8906 overview of how to provide drag-and-drop in your application.
8908 \sa QDrag, QDragLeaveEvent
8910 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8915 \fn void QWidget::dropEvent(QDropEvent *event)
8917 This event handler is called when the drag is dropped on this
8918 widget. The event is passed in the \a event parameter.
8920 See the \link dnd.html Drag-and-drop documentation\endlink for an
8921 overview of how to provide drag-and-drop in your application.
8923 \sa QDrag, QDropEvent
8925 void QWidget::dropEvent(QDropEvent *)
8929 #endif // QT_NO_DRAGANDDROP
8932 \fn void QWidget::showEvent(QShowEvent *event)
8934 This event handler can be reimplemented in a subclass to receive
8935 widget show events which are passed in the \a event parameter.
8937 Non-spontaneous show events are sent to widgets immediately
8938 before they are shown. The spontaneous show events of windows are
8939 delivered afterwards.
8941 Note: A widget receives spontaneous show and hide events when its
8942 mapping status is changed by the window system, e.g. a spontaneous
8943 hide event when the user minimizes the window, and a spontaneous
8944 show event when the window is restored again. After receiving a
8945 spontaneous hide event, a widget is still considered visible in
8946 the sense of isVisible().
8948 \sa visible, event(), QShowEvent
8950 void QWidget::showEvent(QShowEvent *)
8955 \fn void QWidget::hideEvent(QHideEvent *event)
8957 This event handler can be reimplemented in a subclass to receive
8958 widget hide events. The event is passed in the \a event parameter.
8960 Hide events are sent to widgets immediately after they have been
8961 hidden.
8963 Note: A widget receives spontaneous show and hide events when its
8964 mapping status is changed by the window system, e.g. a spontaneous
8965 hide event when the user minimizes the window, and a spontaneous
8966 show event when the window is restored again. After receiving a
8967 spontaneous hide event, a widget is still considered visible in
8968 the sense of isVisible().
8970 \sa visible, event(), QHideEvent
8972 void QWidget::hideEvent(QHideEvent *)
8977 \fn QWidget::x11Event(MSG *)
8979 This special event handler can be reimplemented in a subclass to receive
8980 native X11 events.
8982 In your reimplementation of this function, if you want to stop Qt from
8983 handling the event, return true. If you return false, this native event
8984 is passed back to Qt, which translates it into a Qt event and sends it to
8985 the widget.
8987 \note Events are only delivered to this event handler if the widget is
8988 native.
8990 \warning This function is not portable.
8992 \sa QApplication::x11EventFilter(), QWidget::winId()
8996 #if defined(Q_WS_MAC)
8999 \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event)
9001 This special event handler can be reimplemented in a subclass to
9002 receive native Macintosh events.
9004 The parameters are a bit different depending if Qt is build against Carbon
9005 or Cocoa. In Carbon, \a caller and \a event are the corresponding
9006 EventHandlerCallRef and EventRef that correspond to the Carbon event
9007 handlers that are installed. In Cocoa, \a caller is always 0 and the
9008 EventRef is the EventRef generated from the NSEvent.
9010 In your reimplementation of this function, if you want to stop the
9011 event being handled by Qt, return true. If you return false, this
9012 native event is passed back to Qt, which translates the event into
9013 a Qt event and sends it to the widget.
9015 \warning This function is not portable.
9017 \warning This function was not called inside of Qt until Qt 4.4.
9018 If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead.
9020 \sa QApplication::macEventFilter()
9023 bool QWidget::macEvent(EventHandlerCallRef, EventRef)
9025 return false;
9028 #endif
9029 #if defined(Q_WS_WIN)
9032 This special event handler can be reimplemented in a subclass to
9033 receive native Windows events which are passed in the \a message
9034 parameter.
9036 In your reimplementation of this function, if you want to stop the
9037 event being handled by Qt, return true and set \a result to the value
9038 that the window procedure should return. If you return false, this
9039 native event is passed back to Qt, which translates the event into
9040 a Qt event and sends it to the widget.
9042 \warning This function is not portable.
9044 \sa QApplication::winEventFilter()
9046 bool QWidget::winEvent(MSG *message, long *result)
9048 Q_UNUSED(message);
9049 Q_UNUSED(result);
9050 return false;
9053 #endif
9054 #if defined(Q_WS_X11)
9057 \fn bool QWidget::x11Event(XEvent *event)
9059 This special event handler can be reimplemented in a subclass to receive
9060 native X11 events passed in the \a event parameter.
9062 In your reimplementation of this function, if you want to stop Qt from
9063 handling the event, return true. If you return false, this native event
9064 is passed back to Qt, which translates it into a Qt event and sends it to
9065 the widget.
9067 \note Events are only delivered to this event handler if the widget is
9068 native.
9070 \warning This function is not portable.
9072 \sa QApplication::x11EventFilter(), QWidget::winId()
9074 bool QWidget::x11Event(XEvent *)
9076 return false;
9079 #endif
9080 #if defined(Q_WS_QWS)
9083 \fn bool QWidget::qwsEvent(QWSEvent *event)
9085 This special event handler can be reimplemented in a subclass to
9086 receive native Qt for Embedded Linux events which are passed in the
9087 \a event parameter.
9089 In your reimplementation of this function, if you want to stop the
9090 event being handled by Qt, return true. If you return false, this
9091 native event is passed back to Qt, which translates the event into
9092 a Qt event and sends it to the widget.
9094 \warning This function is not portable.
9096 \sa QApplication::qwsEventFilter()
9098 bool QWidget::qwsEvent(QWSEvent *)
9100 return false;
9103 #endif
9107 Ensures that the widget has been polished by QStyle (i.e., has a
9108 proper font and palette).
9110 QWidget calls this function after it has been fully constructed
9111 but before it is shown the very first time. You can call this
9112 function if you want to ensure that the widget is polished before
9113 doing an operation, e.g., the correct font size might be needed in
9114 the widget's sizeHint() reimplementation. Note that this function
9115 \e is called from the default implementation of sizeHint().
9117 Polishing is useful for final initialization that must happen after
9118 all constructors (from base classes as well as from subclasses)
9119 have been called.
9121 If you need to change some settings when a widget is polished,
9122 reimplement event() and handle the QEvent::Polish event type.
9124 \bold{Note:} The function is declared const so that it can be called from
9125 other const functions (e.g., sizeHint()).
9127 \sa event()
9129 void QWidget::ensurePolished() const
9131 Q_D(const QWidget);
9133 const QMetaObject *m = metaObject();
9134 if (m == d->polished)
9135 return;
9136 d->polished = m;
9138 QEvent e(QEvent::Polish);
9139 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9141 // polish children after 'this'
9142 QList<QObject*> children = d->children;
9143 for (int i = 0; i < children.size(); ++i) {
9144 QObject *o = children.at(i);
9145 if(!o->isWidgetType())
9146 continue;
9147 if (QWidget *w = qobject_cast<QWidget *>(o))
9148 w->ensurePolished();
9151 if (d->parent && d->sendChildEvents) {
9152 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9153 QCoreApplication::sendEvent(d->parent, &e);
9158 Returns the mask currently set on a widget. If no mask is set the
9159 return value will be an empty region.
9161 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9163 QRegion QWidget::mask() const
9165 Q_D(const QWidget);
9166 return d->extra ? d->extra->mask : QRegion();
9170 Returns the layout manager that is installed on this widget, or 0
9171 if no layout manager is installed.
9173 The layout manager sets the geometry of the widget's children
9174 that have been added to the layout.
9176 \sa setLayout(), sizePolicy(), {Layout Management}
9178 QLayout *QWidget::layout() const
9180 return d_func()->layout;
9185 \fn void QWidget::setLayout(QLayout *layout)
9187 Sets the layout manager for this widget to \a layout.
9189 If there already is a layout manager installed on this widget,
9190 QWidget won't let you install another. You must first delete the
9191 existing layout manager (returned by layout()) before you can
9192 call setLayout() with the new layout.
9194 If \a layout is the layout manger on a different widget, setLayout()
9195 will reparent the layout and make it the layout manager for this widget.
9197 Example:
9199 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9201 An alternative to calling this function is to pass this widget to
9202 the layout's constructor.
9204 The QWidget will take ownership of \a layout.
9206 \sa layout(), {Layout Management}
9209 void QWidget::setLayout(QLayout *l)
9211 if (!l) {
9212 qWarning("QWidget::setLayout: Cannot set layout to 0");
9213 return;
9215 if (layout()) {
9216 if (layout() != l)
9217 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9218 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9219 objectName().toLocal8Bit().data());
9220 return;
9223 QObject *oldParent = l->parent();
9224 if (oldParent && oldParent != this) {
9225 if (oldParent->isWidgetType()) {
9226 // Steal the layout off a widget parent. Takes effect when
9227 // morphing laid-out container widgets in Designer.
9228 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9229 oldParentWidget->takeLayout();
9230 } else {
9231 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9232 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9233 objectName().toLocal8Bit().data());
9234 return;
9238 Q_D(QWidget);
9239 l->d_func()->topLevel = true;
9240 d->layout = l;
9241 if (oldParent != this) {
9242 l->setParent(this);
9243 l->d_func()->reparentChildWidgets(this);
9244 l->invalidate();
9247 if (isWindow() && d->maybeTopData())
9248 d->topData()->sizeAdjusted = false;
9252 \fn QLayout *QWidget::takeLayout()
9254 Remove the layout from the widget.
9255 \since 4.5
9258 QLayout *QWidget::takeLayout()
9260 Q_D(QWidget);
9261 QLayout *l = layout();
9262 if (!l)
9263 return 0;
9264 d->layout = 0;
9265 l->setParent(0);
9266 return l;
9270 \property QWidget::sizePolicy
9271 \brief the default layout behavior of the widget
9273 If there is a QLayout that manages this widget's children, the
9274 size policy specified by that layout is used. If there is no such
9275 QLayout, the result of this function is used.
9277 The default policy is Preferred/Preferred, which means that the
9278 widget can be freely resized, but prefers to be the size
9279 sizeHint() returns. Button-like widgets set the size policy to
9280 specify that they may stretch horizontally, but are fixed
9281 vertically. The same applies to lineedit controls (such as
9282 QLineEdit, QSpinBox or an editable QComboBox) and other
9283 horizontally orientated widgets (such as QProgressBar).
9284 QToolButton's are normally square, so they allow growth in both
9285 directions. Widgets that support different directions (such as
9286 QSlider, QScrollBar or QHeader) specify stretching in the
9287 respective direction only. Widgets that can provide scroll bars
9288 (usually subclasses of QScrollArea) tend to specify that they can
9289 use additional space, and that they can make do with less than
9290 sizeHint().
9292 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9294 QSizePolicy QWidget::sizePolicy() const
9296 Q_D(const QWidget);
9297 return d->size_policy;
9300 void QWidget::setSizePolicy(QSizePolicy policy)
9302 Q_D(QWidget);
9303 setAttribute(Qt::WA_WState_OwnSizePolicy);
9304 if (policy == d->size_policy)
9305 return;
9306 d->size_policy = policy;
9308 #ifndef QT_NO_GRAPHICSVIEW
9309 if (QWExtra *extra = d->extra) {
9310 if (extra->proxyWidget)
9311 extra->proxyWidget->setSizePolicy(policy);
9313 #endif
9315 updateGeometry();
9317 if (isWindow() && d->maybeTopData())
9318 d->topData()->sizeAdjusted = false;
9322 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9323 \overload
9325 Sets the size policy of the widget to \a horizontal and \a
9326 vertical, with standard stretch and no height-for-width.
9328 \sa QSizePolicy::QSizePolicy()
9332 Returns the preferred height for this widget, given the width \a w.
9334 If this widget has a layout, the default implementation returns
9335 the layout's preferred height. if there is no layout, the default
9336 implementation returns -1 indicating that the preferred height
9337 does not depend on the width.
9340 int QWidget::heightForWidth(int w) const
9342 if (layout() && layout()->hasHeightForWidth())
9343 return layout()->totalHeightForWidth(w);
9344 return -1;
9348 \fn QWidget *QWidget::childAt(int x, int y) const
9350 Returns the visible child widget at the position (\a{x}, \a{y})
9351 in the widget's coordinate system. If there is no visible child
9352 widget at the specified position, the function returns 0.
9356 \overload
9358 Returns the visible child widget at point \a p in the widget's own
9359 coordinate system.
9362 QWidget *QWidget::childAt(const QPoint &p) const
9364 return d_func()->childAt_helper(p, false);
9367 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9369 Q_Q(const QWidget);
9370 #ifdef Q_WS_MAC
9371 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9372 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9373 #endif
9375 if (
9376 #ifdef Q_WS_MAC
9377 !includeFrame &&
9378 #endif
9379 !q->rect().contains(p))
9380 return 0;
9382 for (int i = children.size(); i > 0 ;) {
9383 --i;
9384 QWidget *w = qobject_cast<QWidget *>(children.at(i));
9385 if (w && !w->isWindow() && !w->isHidden()
9386 && (w->geometry().contains(p)
9387 #ifdef Q_WS_MAC
9388 || (includeFrame && w->geometry().contains(qt_mac_nativeMapFromParent(w, p)))
9389 #endif
9390 )) {
9391 if (ignoreChildrenInDestructor && w->data->in_destructor)
9392 continue;
9393 if (w->testAttribute(Qt::WA_TransparentForMouseEvents))
9394 continue;
9395 QPoint childPoint = w->mapFromParent(p);
9396 #ifdef Q_WS_MAC
9397 if (includeFrame && !w->geometry().contains(p))
9398 childPoint = qt_mac_nativeMapFromParent(w, p);
9399 #endif
9400 if (QWidget *t = w->d_func()->childAt_helper(childPoint, ignoreChildrenInDestructor))
9401 return t;
9402 // if WMouseNoMask is set the widget mask is ignored, if
9403 // the widget has no mask then the WMouseNoMask flag has no
9404 // effect
9405 if (w->testAttribute(Qt::WA_MouseNoMask) || w->mask().contains(childPoint)
9406 || w->mask().isEmpty())
9407 return w;
9410 return 0;
9413 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9415 Q_Q(QWidget);
9416 if (widgetItem)
9417 widgetItem->invalidateSizeCache();
9418 QWidget *parent;
9419 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9420 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9421 if (parent->d_func()->layout)
9422 parent->d_func()->layout->invalidate();
9423 else if (parent->isVisible())
9424 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9430 Notifies the layout system that this widget has changed and may
9431 need to change geometry.
9433 Call this function if the sizeHint() or sizePolicy() have changed.
9435 For explicitly hidden widgets, updateGeometry() is a no-op. The
9436 layout system will be notified as soon as the widget is shown.
9439 void QWidget::updateGeometry()
9441 Q_D(QWidget);
9442 d->updateGeometry_helper(false);
9445 /*! \property QWidget::windowFlags
9447 Window flags are a combination of a type (e.g. Qt::Dialog) and
9448 zero or more hints to the window system (e.g.
9449 Qt::FramelessWindowHint).
9451 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9452 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9453 0) on the desktop. If the widget is a window and becomes a
9454 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9455 relative to its parent widget.
9457 \note This function calls setParent() when changing the flags for
9458 a window, causing the widget to be hidden. You must call show() to make
9459 the widget visible again..
9461 \sa windowType(), {Window Flags Example}
9463 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9465 if (data->window_flags == flags)
9466 return;
9468 Q_D(QWidget);
9470 if ((data->window_flags | flags) & Qt::Window) {
9471 // the old type was a window and/or the new type is a window
9472 QPoint oldPos = pos();
9473 bool visible = isVisible();
9474 setParent(parentWidget(), flags);
9476 // if both types are windows or neither of them are, we restore
9477 // the old position
9478 if (!((data->window_flags ^ flags) & Qt::Window)
9479 && (visible || testAttribute(Qt::WA_Moved))) {
9480 move(oldPos);
9482 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9483 d->adjustQuitOnCloseAttribute();
9484 } else {
9485 data->window_flags = flags;
9490 Sets the window flags for the widget to \a flags,
9491 \e without telling the window system.
9493 \warning Do not call this function unless you really know what
9494 you're doing.
9496 \sa setWindowFlags()
9498 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9500 data->window_flags = flags;
9504 \fn Qt::WindowType QWidget::windowType() const
9506 Returns the window type of this widget. This is identical to
9507 windowFlags() & Qt::WindowType_Mask.
9509 \sa windowFlags
9513 Sets the parent of the widget to \a parent, and resets the window
9514 flags. The widget is moved to position (0, 0) in its new parent.
9516 If the new parent widget is in a different window, the
9517 reparented widget and its children are appended to the end of the
9518 \l{setFocusPolicy()}{tab chain} of the new parent
9519 widget, in the same internal order as before. If one of the moved
9520 widgets had keyboard focus, setParent() calls clearFocus() for that
9521 widget.
9523 If the new parent widget is in the same window as the
9524 old parent, setting the parent doesn't change the tab order or
9525 keyboard focus.
9527 If the "new" parent widget is the old parent widget, this function
9528 does nothing.
9530 \note The widget becomes invisible as part of changing its parent,
9531 even if it was previously visible. You must call show() to make the
9532 widget visible again.
9534 \warning It is very unlikely that you will ever need this
9535 function. If you have a widget that changes its content
9536 dynamically, it is far easier to use \l QStackedWidget.
9538 \sa setWindowFlags()
9540 void QWidget::setParent(QWidget *parent)
9542 if (parent == parentWidget())
9543 return;
9544 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9548 \overload
9550 This function also takes widget flags, \a f as an argument.
9553 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9555 Q_D(QWidget);
9556 bool resized = testAttribute(Qt::WA_Resized);
9557 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9558 QWidget *oldtlw = window();
9560 QWidget *desktopWidget = 0;
9561 if (parent && parent->windowType() == Qt::Desktop)
9562 desktopWidget = parent;
9563 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9565 #if defined(Q_WS_X11) || defined(Q_WS_WIN)
9566 if (newParent && parent && !desktopWidget) {
9567 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings))
9568 parent->d_func()->enforceNativeChildren();
9569 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9570 setAttribute(Qt::WA_NativeWindow);
9572 #endif
9574 if (wasCreated) {
9575 if (!testAttribute(Qt::WA_WState_Hidden)) {
9576 hide();
9577 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9579 if (newParent) {
9580 QEvent e(QEvent::ParentAboutToChange);
9581 QApplication::sendEvent(this, &e);
9584 if (newParent && isAncestorOf(focusWidget()))
9585 focusWidget()->clearFocus();
9587 d->setParent_sys(parent, f);
9588 if (desktopWidget)
9589 parent = 0;
9591 #ifdef Q_BACKINGSTORE_SUBSURFACES
9592 QTLWExtra *extra = d->maybeTopData();
9593 QWindowSurface *windowSurface = (extra ? extra->windowSurface : 0);
9594 if (newParent && windowSurface) {
9595 QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore();
9596 if (oldBs)
9597 oldBs->subSurfaces.removeAll(windowSurface);
9599 if (parent) {
9600 QWidgetBackingStore *newBs = parent->d_func()->maybeBackingStore();
9601 if (newBs)
9602 newBs->subSurfaces.append(windowSurface);
9605 #endif
9607 if (newParent) {
9608 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9609 oldBs->removeDirtyWidget(this);
9610 // Move the widget and all its static children from
9611 // the old backing store to the new one.
9612 oldBs->moveStaticWidgets(this);
9616 if ((QApplicationPrivate::app_compile_version < 0x040200
9617 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
9618 && !testAttribute(Qt::WA_WState_Created))
9619 create();
9621 d->reparentFocusWidgets(oldtlw);
9622 setAttribute(Qt::WA_Resized, resized);
9623 if (!testAttribute(Qt::WA_StyleSheet)
9624 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9625 d->resolveFont();
9626 d->resolvePalette();
9628 d->resolveLayoutDirection();
9629 d->resolveLocale();
9631 // Note: GL widgets under WGL or EGL will always need a ParentChange
9632 // event to handle recreation/rebinding of the GL context, hence the
9633 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9634 // platforms).
9635 if (newParent
9636 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9637 || (f & Qt::MSWindowsOwnDC)
9638 #endif
9640 // propagate enabled updates enabled state to non-windows
9641 if (!isWindow()) {
9642 if (!testAttribute(Qt::WA_ForceDisabled))
9643 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9644 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9645 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9647 d->inheritStyle();
9649 // send and post remaining QObject events
9650 if (parent && d->sendChildEvents) {
9651 QChildEvent e(QEvent::ChildAdded, this);
9652 QApplication::sendEvent(parent, &e);
9653 #ifdef QT3_SUPPORT
9654 if (parent->d_func()->pendingChildInsertedEvents.isEmpty()) {
9655 QApplication::postEvent(parent,
9656 new QEvent(QEvent::ChildInsertedRequest),
9657 Qt::HighEventPriority);
9659 parent->d_func()->pendingChildInsertedEvents.append(this);
9660 #endif
9663 //### already hidden above ---> must probably do something smart on the mac
9664 // #ifdef Q_WS_MAC
9665 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9666 // if(!qt_mac_is_macdrawer(q)) //special case
9667 // q->setAttribute(Qt::WA_WState_Hidden);
9668 // #else
9669 // q->setAttribute(Qt::WA_WState_Hidden);
9670 //#endif
9672 if (parent && d->sendChildEvents && d->polished) {
9673 QChildEvent e(QEvent::ChildPolished, this);
9674 QCoreApplication::sendEvent(parent, &e);
9677 QEvent e(QEvent::ParentChange);
9678 QApplication::sendEvent(this, &e);
9681 if (!wasCreated) {
9682 if (isWindow() || parentWidget()->isVisible())
9683 setAttribute(Qt::WA_WState_Hidden, true);
9684 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9685 setAttribute(Qt::WA_WState_Hidden, false);
9688 d->updateIsOpaque();
9690 #ifndef QT_NO_GRAPHICSVIEW
9691 // Embed the widget into a proxy if the parent is embedded.
9692 // ### Doesn't handle reparenting out of an embedded widget.
9693 if (oldtlw->graphicsProxyWidget()) {
9694 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9695 ancestorProxy->d_func()->unembedSubWindow(this);
9697 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9698 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9699 ancestorProxy->d_func()->embedSubWindow(this);
9701 #endif
9705 Scrolls the widget including its children \a dx pixels to the
9706 right and \a dy downward. Both \a dx and \a dy may be negative.
9708 After scrolling, the widgets will receive paint events for
9709 the areas that need to be repainted. For widgets that Qt knows to
9710 be opaque, this is only the newly exposed parts.
9711 For example, if an opaque widget is scrolled 8 pixels to the left,
9712 only an 8-pixel wide stripe at the right edge needs updating.
9714 Since widgets propagate the contents of their parents by default,
9715 you need to set the \l autoFillBackground property, or use
9716 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9717 a widget opaque.
9719 For widgets that use contents propagation, a scroll will cause an
9720 update of the entire scroll area.
9722 \sa {Transparency and Double Buffering}
9725 void QWidget::scroll(int dx, int dy)
9727 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9728 return;
9729 if (dx == 0 && dy == 0)
9730 return;
9731 Q_D(QWidget);
9732 #ifndef QT_NO_GRAPHICSVIEW
9733 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9734 // Graphics View maintains its own dirty region as a list of rects;
9735 // until we can connect item updates directly to the view, we must
9736 // separately add a translated dirty region.
9737 if (!d->dirty.isEmpty()) {
9738 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9739 proxy->update(rect);
9741 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9742 return;
9744 #endif
9745 d->setDirtyOpaqueRegion();
9746 d->scroll_sys(dx, dy);
9750 \overload
9752 This version only scrolls \a r and does not move the children of
9753 the widget.
9755 If \a r is empty or invalid, the result is undefined.
9757 \sa QScrollArea
9759 void QWidget::scroll(int dx, int dy, const QRect &r)
9762 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9763 return;
9764 if (dx == 0 && dy == 0)
9765 return;
9766 Q_D(QWidget);
9767 #ifndef QT_NO_GRAPHICSVIEW
9768 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9769 // Graphics View maintains its own dirty region as a list of rects;
9770 // until we can connect item updates directly to the view, we must
9771 // separately add a translated dirty region.
9772 if (!d->dirty.isEmpty()) {
9773 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9774 proxy->update(rect);
9776 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9777 return;
9779 #endif
9780 d->scroll_sys(dx, dy, r);
9784 Repaints the widget directly by calling paintEvent() immediately,
9785 unless updates are disabled or the widget is hidden.
9787 We suggest only using repaint() if you need an immediate repaint,
9788 for example during animation. In almost all circumstances update()
9789 is better, as it permits Qt to optimize for speed and minimize
9790 flicker.
9792 \warning If you call repaint() in a function which may itself be
9793 called from paintEvent(), you may get infinite recursion. The
9794 update() function never causes recursion.
9796 \sa update(), paintEvent(), setUpdatesEnabled()
9799 void QWidget::repaint()
9801 repaint(rect());
9804 /*! \overload
9806 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9807 the widget.
9809 If \a w is negative, it is replaced with \c{width() - x}, and if
9810 \a h is negative, it is replaced width \c{height() - y}.
9812 void QWidget::repaint(int x, int y, int w, int h)
9814 if (x > data->crect.width() || y > data->crect.height())
9815 return;
9817 if (w < 0)
9818 w = data->crect.width() - x;
9819 if (h < 0)
9820 h = data->crect.height() - y;
9822 repaint(QRect(x, y, w, h));
9825 /*! \overload
9827 This version repaints a rectangle \a rect inside the widget.
9829 void QWidget::repaint(const QRect &rect)
9831 Q_D(QWidget);
9833 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9834 update(rect);
9835 return;
9838 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9839 return;
9841 if (hasBackingStoreSupport()) {
9842 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9843 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9844 tlwExtra->inRepaint = true;
9845 tlwExtra->backingStore->markDirty(rect, this, true);
9846 tlwExtra->inRepaint = false;
9848 } else {
9849 d->repaint_sys(rect);
9854 \overload
9856 This version repaints a region \a rgn inside the widget.
9858 void QWidget::repaint(const QRegion &rgn)
9860 Q_D(QWidget);
9862 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9863 update(rgn);
9864 return;
9867 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9868 return;
9870 if (hasBackingStoreSupport()) {
9871 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9872 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9873 tlwExtra->inRepaint = true;
9874 tlwExtra->backingStore->markDirty(rgn, this, true);
9875 tlwExtra->inRepaint = false;
9877 } else {
9878 d->repaint_sys(rgn);
9883 Updates the widget unless updates are disabled or the widget is
9884 hidden.
9886 This function does not cause an immediate repaint; instead it
9887 schedules a paint event for processing when Qt returns to the main
9888 event loop. This permits Qt to optimize for more speed and less
9889 flicker than a call to repaint() does.
9891 Calling update() several times normally results in just one
9892 paintEvent() call.
9894 Qt normally erases the widget's area before the paintEvent() call.
9895 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9896 responsible for painting all its pixels with an opaque color.
9898 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9900 void QWidget::update()
9902 update(rect());
9905 /*! \fn void QWidget::update(int x, int y, int w, int h)
9906 \overload
9908 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9909 the widget.
9913 \overload
9915 This version updates a rectangle \a rect inside the widget.
9917 void QWidget::update(const QRect &rect)
9919 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9920 return;
9922 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9923 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9924 return;
9927 if (hasBackingStoreSupport()) {
9928 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9929 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9930 tlwExtra->backingStore->markDirty(rect, this);
9931 } else {
9932 d_func()->repaint_sys(rect);
9937 \overload
9939 This version repaints a region \a rgn inside the widget.
9941 void QWidget::update(const QRegion &rgn)
9943 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9944 return;
9946 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9947 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9948 return;
9951 if (hasBackingStoreSupport()) {
9952 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9953 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9954 tlwExtra->backingStore->markDirty(rgn, this);
9955 } else {
9956 d_func()->repaint_sys(rgn);
9960 #ifdef QT3_SUPPORT
9962 Clear the rectangle at point (\a x, \a y) of width \a w and height
9963 \a h.
9965 \warning This is best done in a paintEvent().
9967 void QWidget::erase_helper(int x, int y, int w, int h)
9969 if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
9970 return;
9971 if (w < 0)
9972 w = data->crect.width() - x;
9973 if (h < 0)
9974 h = data->crect.height() - y;
9975 if (w != 0 && h != 0) {
9976 QPainter p(this);
9977 p.eraseRect(QRect(x, y, w, h));
9982 \overload
9984 Clear the given region, \a rgn.
9986 Drawing may only take place in a QPaintEvent. Overload
9987 paintEvent() to do your erasing and call update() to schedule a
9988 replaint whenever necessary. See also QPainter.
9990 void QWidget::erase(const QRegion& rgn)
9992 if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
9993 return;
9995 QPainter p(this);
9996 p.setClipRegion(rgn);
9997 p.eraseRect(rgn.boundingRect());
10000 void QWidget::drawText_helper(int x, int y, const QString &str)
10002 if(!testAttribute(Qt::WA_WState_Visible))
10003 return;
10004 QPainter paint(this);
10005 paint.drawText(x, y, str);
10010 Closes the widget.
10012 Use the no-argument overload instead.
10014 bool QWidget::close(bool alsoDelete)
10016 QPointer<QWidget> that = this;
10017 bool accepted = close();
10018 if (alsoDelete && accepted && that)
10019 deleteLater();
10020 return accepted;
10023 void QWidget::setIcon(const QPixmap &i)
10025 setWindowIcon(i);
10029 Return's the widget's icon.
10031 Use windowIcon() instead.
10033 const QPixmap *QWidget::icon() const
10035 Q_D(const QWidget);
10036 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconPixmap : 0;
10039 #endif // QT3_SUPPORT
10042 Sets the attribute \a attribute on this widget if \a on is true;
10043 otherwise clears the attribute.
10045 \sa testAttribute()
10047 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
10049 if (testAttribute(attribute) == on)
10050 return;
10052 Q_D(QWidget);
10053 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
10054 "QWidget::setAttribute(WidgetAttribute, bool)",
10055 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
10057 #ifdef Q_WS_WIN
10058 if (attribute == Qt::WA_PaintOnScreen && on) {
10059 // see qwidget_win.cpp, ::paintEngine for details
10060 paintEngine();
10061 if (d->noPaintOnScreen)
10062 return;
10064 #endif
10066 if (attribute < int(8*sizeof(uint))) {
10067 if (on)
10068 data->widget_attributes |= (1<<attribute);
10069 else
10070 data->widget_attributes &= ~(1<<attribute);
10071 } else {
10072 const int x = attribute - 8*sizeof(uint);
10073 const int int_off = x / (8*sizeof(uint));
10074 if (on)
10075 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
10076 else
10077 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
10080 switch (attribute) {
10082 #ifndef QT_NO_DRAGANDDROP
10083 case Qt::WA_AcceptDrops: {
10084 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
10085 setAttribute(Qt::WA_DropSiteRegistered, true);
10086 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
10087 setAttribute(Qt::WA_DropSiteRegistered, false);
10088 QEvent e(QEvent::AcceptDropsChange);
10089 QApplication::sendEvent(this, &e);
10090 break;
10092 case Qt::WA_DropSiteRegistered: {
10093 d->registerDropSite(on);
10094 for (int i = 0; i < d->children.size(); ++i) {
10095 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
10096 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
10097 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10099 break;
10101 #endif
10103 case Qt::WA_NoChildEventsForParent:
10104 d->sendChildEvents = !on;
10105 break;
10106 case Qt::WA_NoChildEventsFromChildren:
10107 d->receiveChildEvents = !on;
10108 break;
10109 case Qt::WA_MacBrushedMetal:
10110 #ifdef Q_WS_MAC
10111 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10112 // fall through since changing the metal attribute affects the opaque size grip.
10113 case Qt::WA_MacOpaqueSizeGrip:
10114 d->macUpdateOpaqueSizeGrip();
10115 break;
10116 case Qt::WA_MacShowFocusRect:
10117 if (hasFocus()) {
10118 clearFocus();
10119 setFocus();
10121 break;
10122 case Qt::WA_Hover:
10123 qt_mac_update_mouseTracking(this);
10124 break;
10125 #endif
10126 case Qt::WA_MacAlwaysShowToolWindow:
10127 #ifdef Q_WS_MAC
10128 d->macUpdateHideOnSuspend();
10129 #endif
10130 break;
10131 case Qt::WA_MacNormalSize:
10132 case Qt::WA_MacSmallSize:
10133 case Qt::WA_MacMiniSize:
10134 #ifdef Q_WS_MAC
10136 // We can only have one of these set at a time
10137 static const int MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10138 Qt::WA_MacMiniSize, 0 };
10139 for (int i = 0; MacSizes[i] != 0; ++i) {
10140 if (MacSizes[i] == attribute)
10141 continue;
10142 int macsize_x = MacSizes[i] - 8*sizeof(uint);
10143 int macsize_int_off = macsize_x / (8*sizeof(uint));
10144 d->high_attributes[macsize_int_off] &= ~(1<<(macsize_x-(macsize_int_off*8*sizeof(uint))));
10146 d->macUpdateSizeAttribute();
10148 #endif
10149 break;
10150 case Qt::WA_ShowModal:
10151 if (!on) {
10152 if (isVisible())
10153 QApplicationPrivate::leaveModal(this);
10154 // reset modality type to Modeless when clearing WA_ShowModal
10155 data->window_modality = Qt::NonModal;
10156 } else if (data->window_modality == Qt::NonModal) {
10157 // determine the modality type if it hasn't been set prior
10158 // to setting WA_ShowModal. set the default to WindowModal
10159 // if we are the child of a group leader; otherwise use
10160 // ApplicationModal.
10161 QWidget *w = parentWidget();
10162 if (w)
10163 w = w->window();
10164 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10165 w = w->parentWidget();
10166 if (w)
10167 w = w->window();
10169 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10170 ? Qt::WindowModal
10171 : Qt::ApplicationModal;
10172 // Some window managers does not allow us to enter modal after the
10173 // window is showing. Therefore, to be consistent, we cannot call
10174 // QApplicationPrivate::enterModal(this) here. The window must be
10175 // hidden before changing modality.
10177 if (testAttribute(Qt::WA_WState_Created)) {
10178 // don't call setModal_sys() before create_sys()
10179 d->setModal_sys();
10181 break;
10182 case Qt::WA_MouseTracking: {
10183 QEvent e(QEvent::MouseTrackingChange);
10184 QApplication::sendEvent(this, &e);
10185 break; }
10186 case Qt::WA_NativeWindow: {
10187 QInputContext *ic = 0;
10188 if (on && !internalWinId() && testAttribute(Qt::WA_InputMethodEnabled) && hasFocus()) {
10189 ic = d->inputContext();
10190 ic->reset();
10191 ic->setFocusWidget(0);
10193 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget())
10194 parentWidget()->d_func()->enforceNativeChildren();
10195 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10196 d->createWinId();
10197 if (ic && isEnabled())
10198 ic->setFocusWidget(this);
10199 break;
10201 case Qt::WA_PaintOnScreen:
10202 d->updateIsOpaque();
10203 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
10204 // Recreate the widget if it's already created as an alien widget and
10205 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10206 // So must their children.
10207 if (on) {
10208 setAttribute(Qt::WA_NativeWindow);
10209 d->enforceNativeChildren();
10211 #endif
10212 // fall through
10213 case Qt::WA_OpaquePaintEvent:
10214 d->updateIsOpaque();
10215 break;
10216 case Qt::WA_NoSystemBackground:
10217 d->updateIsOpaque();
10218 // fall through...
10219 case Qt::WA_UpdatesDisabled:
10220 d->updateSystemBackground();
10221 break;
10222 case Qt::WA_TransparentForMouseEvents:
10223 #ifdef Q_WS_MAC
10224 d->macUpdateIgnoreMouseEvents();
10225 #endif
10226 break;
10227 case Qt::WA_InputMethodEnabled: {
10228 QInputContext *ic = d->ic;
10229 if (!ic && (!on || hasFocus()))
10230 ic = d->inputContext();
10231 if (ic) {
10232 if (on && hasFocus() && ic->focusWidget() != this && isEnabled()) {
10233 ic->setFocusWidget(this);
10234 } else if (!on && ic->focusWidget() == this) {
10235 ic->reset();
10236 ic->setFocusWidget(0);
10239 break;
10241 case Qt::WA_WindowPropagation:
10242 d->resolvePalette();
10243 d->resolveFont();
10244 d->resolveLocale();
10245 break;
10246 #ifdef Q_WS_X11
10247 case Qt::WA_NoX11EventCompression:
10248 if (!d->extra)
10249 d->createExtra();
10250 d->extra->compress_events = on;
10251 break;
10252 case Qt::WA_X11OpenGLOverlay:
10253 d->updateIsOpaque();
10254 break;
10255 #endif
10256 case Qt::WA_DontShowOnScreen: {
10257 if (on && isVisible()) {
10258 // Make sure we keep the current state and only hide the widget
10259 // from the desktop. show_sys will only update platform specific
10260 // attributes at this point.
10261 d->hide_sys();
10262 #ifdef Q_WS_QWS
10263 // Release the region for this window from qws if the widget has
10264 // been shown before the attribute was set.
10265 if (QWSWindowSurface *surface = static_cast<QWSWindowSurface *>(windowSurface())) {
10266 QWidget::qwsDisplay()->requestRegion(surface->winId(), surface->key(),
10267 surface->permanentState(), QRegion());
10269 #endif
10270 d->show_sys();
10272 break;
10275 #ifdef Q_WS_X11
10276 case Qt::WA_X11NetWmWindowTypeDesktop:
10277 case Qt::WA_X11NetWmWindowTypeDock:
10278 case Qt::WA_X11NetWmWindowTypeToolBar:
10279 case Qt::WA_X11NetWmWindowTypeMenu:
10280 case Qt::WA_X11NetWmWindowTypeUtility:
10281 case Qt::WA_X11NetWmWindowTypeSplash:
10282 case Qt::WA_X11NetWmWindowTypeDialog:
10283 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10284 case Qt::WA_X11NetWmWindowTypePopupMenu:
10285 case Qt::WA_X11NetWmWindowTypeToolTip:
10286 case Qt::WA_X11NetWmWindowTypeNotification:
10287 case Qt::WA_X11NetWmWindowTypeCombo:
10288 case Qt::WA_X11NetWmWindowTypeDND:
10289 if (testAttribute(Qt::WA_WState_Created))
10290 d->setNetWmWindowTypes();
10291 break;
10292 #endif
10294 case Qt::WA_StaticContents:
10295 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10296 if (on)
10297 bs->addStaticWidget(this);
10298 else
10299 bs->removeStaticWidget(this);
10301 break;
10302 case Qt::WA_TranslucentBackground:
10303 if (on) {
10304 setAttribute(Qt::WA_NoSystemBackground);
10305 d->updateIsTranslucent();
10308 break;
10309 case Qt::WA_AcceptTouchEvents:
10310 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10311 if (on)
10312 d->registerTouchWindow();
10313 #endif
10314 break;
10315 default:
10316 break;
10320 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10322 Returns true if attribute \a attribute is set on this widget;
10323 otherwise returns false.
10325 \sa setAttribute()
10327 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10329 Q_D(const QWidget);
10330 const int x = attribute - 8*sizeof(uint);
10331 const int int_off = x / (8*sizeof(uint));
10332 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10336 \property QWidget::windowOpacity
10338 \brief The level of opacity for the window.
10340 The valid range of opacity is from 1.0 (completely opaque) to
10341 0.0 (completely transparent).
10343 By default the value of this property is 1.0.
10345 This feature is available on Embedded Linux, Mac OS X, Windows,
10346 and X11 platforms that support the Composite extension.
10348 This feature is not available on Windows CE.
10350 Note that under X11 you need to have a composite manager running,
10351 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10352 supported by the window manager you are using.
10354 \warning Changing this property from opaque to transparent might issue a
10355 paint event that needs to be processed before the window is displayed
10356 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10357 that semi-transparent windows update and resize significantly slower than
10358 opaque windows.
10360 \sa setMask()
10362 qreal QWidget::windowOpacity() const
10364 Q_D(const QWidget);
10365 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10368 void QWidget::setWindowOpacity(qreal opacity)
10370 Q_D(QWidget);
10371 if (!isWindow())
10372 return;
10374 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10375 QTLWExtra *extra = d->topData();
10376 extra->opacity = uint(opacity * 255);
10377 setAttribute(Qt::WA_WState_WindowOpacitySet);
10379 #ifndef Q_WS_QWS
10380 if (!testAttribute(Qt::WA_WState_Created))
10381 return;
10382 #endif
10384 #ifndef QT_NO_GRAPHICSVIEW
10385 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10386 // Avoid invalidating the cache if set.
10387 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10388 proxy->update();
10389 else if (QGraphicsScene *scene = proxy->scene())
10390 scene->update(proxy->sceneBoundingRect());
10391 return;
10393 #endif
10395 d->setWindowOpacity_sys(opacity);
10399 \property QWidget::windowModified
10400 \brief whether the document shown in the window has unsaved changes
10402 A modified window is a window whose content has changed but has
10403 not been saved to disk. This flag will have different effects
10404 varied by the platform. On Mac OS X the close button will have a
10405 modified look; on other platforms, the window title will have an
10406 '*' (asterisk).
10408 The window title must contain a "[*]" placeholder, which
10409 indicates where the '*' should appear. Normally, it should appear
10410 right after the file name (e.g., "document1.txt[*] - Text
10411 Editor"). If the window isn't modified, the placeholder is simply
10412 removed.
10414 Note that if a widget is set as modified, all its ancestors will
10415 also be set as modified. However, if you call \c
10416 {setWindowModified(false)} on a widget, this will not propagate to
10417 its parent because other children of the parent might have been
10418 modified.
10420 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10422 bool QWidget::isWindowModified() const
10424 return testAttribute(Qt::WA_WindowModified);
10427 void QWidget::setWindowModified(bool mod)
10429 Q_D(QWidget);
10430 setAttribute(Qt::WA_WindowModified, mod);
10432 #ifndef Q_WS_MAC
10433 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10434 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10435 #endif
10436 d->setWindowTitle_helper(windowTitle());
10437 d->setWindowIconText_helper(windowIconText());
10438 #ifdef Q_WS_MAC
10439 d->setWindowModified_sys(mod);
10440 #endif
10442 QEvent e(QEvent::ModifiedChange);
10443 QApplication::sendEvent(this, &e);
10446 #ifndef QT_NO_TOOLTIP
10448 \property QWidget::toolTip
10450 \brief the widget's tooltip
10452 Note that by default tooltips are only shown for widgets that are
10453 children of the active window. You can change this behavior by
10454 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10455 not on the widget with the tooltip.
10457 If you want to control a tooltip's behavior, you can intercept the
10458 event() function and catch the QEvent::ToolTip event (e.g., if you
10459 want to customize the area for which the tooltip should be shown).
10461 By default, this property contains an empty string.
10463 \sa QToolTip statusTip whatsThis
10465 void QWidget::setToolTip(const QString &s)
10467 Q_D(QWidget);
10468 d->toolTip = s;
10470 QEvent event(QEvent::ToolTipChange);
10471 QApplication::sendEvent(this, &event);
10474 QString QWidget::toolTip() const
10476 Q_D(const QWidget);
10477 return d->toolTip;
10479 #endif // QT_NO_TOOLTIP
10482 #ifndef QT_NO_STATUSTIP
10484 \property QWidget::statusTip
10485 \brief the widget's status tip
10487 By default, this property contains an empty string.
10489 \sa toolTip whatsThis
10491 void QWidget::setStatusTip(const QString &s)
10493 Q_D(QWidget);
10494 d->statusTip = s;
10497 QString QWidget::statusTip() const
10499 Q_D(const QWidget);
10500 return d->statusTip;
10502 #endif // QT_NO_STATUSTIP
10504 #ifndef QT_NO_WHATSTHIS
10506 \property QWidget::whatsThis
10508 \brief the widget's What's This help text.
10510 By default, this property contains an empty string.
10512 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10514 void QWidget::setWhatsThis(const QString &s)
10516 Q_D(QWidget);
10517 d->whatsThis = s;
10520 QString QWidget::whatsThis() const
10522 Q_D(const QWidget);
10523 return d->whatsThis;
10525 #endif // QT_NO_WHATSTHIS
10527 #ifndef QT_NO_ACCESSIBILITY
10529 \property QWidget::accessibleName
10531 \brief the widget's name as seen by assistive technologies
10533 This property is used by accessible clients to identify, find, or announce
10534 the widget for accessible clients.
10536 By default, this property contains an empty string.
10538 \sa QAccessibleInterface::text()
10540 void QWidget::setAccessibleName(const QString &name)
10542 Q_D(QWidget);
10543 d->accessibleName = name;
10546 QString QWidget::accessibleName() const
10548 Q_D(const QWidget);
10549 return d->accessibleName;
10553 \property QWidget::accessibleDescription
10555 \brief the widget's description as seen by assistive technologies
10557 By default, this property contains an empty string.
10559 \sa QAccessibleInterface::text()
10561 void QWidget::setAccessibleDescription(const QString &description)
10563 Q_D(QWidget);
10564 d->accessibleDescription = description;
10567 QString QWidget::accessibleDescription() const
10569 Q_D(const QWidget);
10570 return d->accessibleDescription;
10572 #endif // QT_NO_ACCESSIBILITY
10574 #ifndef QT_NO_SHORTCUT
10576 Adds a shortcut to Qt's shortcut system that watches for the given
10577 \a key sequence in the given \a context. If the \a context is
10578 Qt::ApplicationShortcut, the shortcut applies to the application as a
10579 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10580 or to the window itself, Qt::WindowShortcut.
10582 If the same \a key sequence has been grabbed by several widgets,
10583 when the \a key sequence occurs a QEvent::Shortcut event is sent
10584 to all the widgets to which it applies in a non-deterministic
10585 order, but with the ``ambiguous'' flag set to true.
10587 \warning You should not normally need to use this function;
10588 instead create \l{QAction}s with the shortcut key sequences you
10589 require (if you also want equivalent menu options and toolbar
10590 buttons), or create \l{QShortcut}s if you just need key sequences.
10591 Both QAction and QShortcut handle all the event filtering for you,
10592 and provide signals which are triggered when the user triggers the
10593 key sequence, so are much easier to use than this low-level
10594 function.
10596 \sa releaseShortcut() setShortcutEnabled()
10598 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10600 Q_ASSERT(qApp);
10601 if (key.isEmpty())
10602 return 0;
10603 setAttribute(Qt::WA_GrabbedShortcut);
10604 return qApp->d_func()->shortcutMap.addShortcut(this, key, context);
10608 Removes the shortcut with the given \a id from Qt's shortcut
10609 system. The widget will no longer receive QEvent::Shortcut events
10610 for the shortcut's key sequence (unless it has other shortcuts
10611 with the same key sequence).
10613 \warning You should not normally need to use this function since
10614 Qt's shortcut system removes shortcuts automatically when their
10615 parent widget is destroyed. It is best to use QAction or
10616 QShortcut to handle shortcuts, since they are easier to use than
10617 this low-level function. Note also that this is an expensive
10618 operation.
10620 \sa grabShortcut() setShortcutEnabled()
10622 void QWidget::releaseShortcut(int id)
10624 Q_ASSERT(qApp);
10625 if (id)
10626 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10630 If \a enable is true, the shortcut with the given \a id is
10631 enabled; otherwise the shortcut is disabled.
10633 \warning You should not normally need to use this function since
10634 Qt's shortcut system enables/disables shortcuts automatically as
10635 widgets become hidden/visible and gain or lose focus. It is best
10636 to use QAction or QShortcut to handle shortcuts, since they are
10637 easier to use than this low-level function.
10639 \sa grabShortcut() releaseShortcut()
10641 void QWidget::setShortcutEnabled(int id, bool enable)
10643 Q_ASSERT(qApp);
10644 if (id)
10645 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10649 \since 4.2
10651 If \a enable is true, auto repeat of the shortcut with the
10652 given \a id is enabled; otherwise it is disabled.
10654 \sa grabShortcut() releaseShortcut()
10656 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10658 Q_ASSERT(qApp);
10659 if (id)
10660 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10662 #endif // QT_NO_SHORTCUT
10664 Updates the widget's micro focus.
10666 \sa QInputContext
10668 void QWidget::updateMicroFocus()
10670 #if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN))
10671 Q_D(QWidget);
10672 // and optimisation to update input context only it has already been created.
10673 if (d->ic || qApp->d_func()->inputContext) {
10674 QInputContext *ic = inputContext();
10675 if (ic)
10676 ic->update();
10678 #endif
10679 #ifndef QT_NO_ACCESSIBILITY
10680 // ##### is this correct
10681 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
10682 #endif
10686 #if defined (Q_WS_WIN)
10688 Returns the window system handle of the widget, for low-level
10689 access. Using this function is not portable.
10691 An HDC acquired with getDC() has to be released with releaseDC().
10693 \warning Using this function is not portable.
10695 HDC QWidget::getDC() const
10697 Q_D(const QWidget);
10698 if (d->hd)
10699 return (HDC) d->hd;
10700 return GetDC(winId());
10704 Releases the HDC \a hdc acquired by a previous call to getDC().
10706 \warning Using this function is not portable.
10708 void QWidget::releaseDC(HDC hdc) const
10710 Q_D(const QWidget);
10711 // If its the widgets own dc, it will be released elsewhere. If
10712 // its a different HDC we release it and issue a warning if it
10713 // fails.
10714 if (hdc != d->hd && !ReleaseDC(winId(), hdc))
10715 qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
10717 #else
10719 Returns the window system handle of the widget, for low-level
10720 access. Using this function is not portable.
10722 The HANDLE type varies with platform; see \c qwindowdefs.h for
10723 details.
10725 Qt::HANDLE QWidget::handle() const
10727 Q_D(const QWidget);
10728 if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
10729 (void)winId(); // enforce native window
10730 return d->hd;
10732 #endif
10736 Raises this widget to the top of the parent widget's stack.
10738 After this call the widget will be visually in front of any
10739 overlapping sibling widgets.
10741 \note When using activateWindow(), you can call this function to
10742 ensure that the window is stacked on top.
10744 \sa lower(), stackUnder()
10747 void QWidget::raise()
10749 Q_D(QWidget);
10750 if (!isWindow()) {
10751 QWidget *p = parentWidget();
10752 const int parentChildCount = p->d_func()->children.size();
10753 if (parentChildCount < 2)
10754 return;
10755 const int from = p->d_func()->children.indexOf(this);
10756 Q_ASSERT(from >= 0);
10757 // Do nothing if the widget is already in correct stacking order _and_ created.
10758 if (from != parentChildCount -1)
10759 p->d_func()->children.move(from, parentChildCount - 1);
10760 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10761 create();
10762 else if (from == parentChildCount - 1)
10763 return;
10765 QRegion region(rect());
10766 d->subtractOpaqueSiblings(region);
10767 d->invalidateBuffer(region);
10769 if (testAttribute(Qt::WA_WState_Created))
10770 d->raise_sys();
10772 QEvent e(QEvent::ZOrderChange);
10773 QApplication::sendEvent(this, &e);
10777 Lowers the widget to the bottom of the parent widget's stack.
10779 After this call the widget will be visually behind (and therefore
10780 obscured by) any overlapping sibling widgets.
10782 \sa raise(), stackUnder()
10785 void QWidget::lower()
10787 Q_D(QWidget);
10788 if (!isWindow()) {
10789 QWidget *p = parentWidget();
10790 const int parentChildCount = p->d_func()->children.size();
10791 if (parentChildCount < 2)
10792 return;
10793 const int from = p->d_func()->children.indexOf(this);
10794 Q_ASSERT(from >= 0);
10795 // Do nothing if the widget is already in correct stacking order _and_ created.
10796 if (from != 0)
10797 p->d_func()->children.move(from, 0);
10798 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10799 create();
10800 else if (from == 0)
10801 return;
10803 if (testAttribute(Qt::WA_WState_Created))
10804 d->lower_sys();
10806 QEvent e(QEvent::ZOrderChange);
10807 QApplication::sendEvent(this, &e);
10812 Places the widget under \a w in the parent widget's stack.
10814 To make this work, the widget itself and \a w must be siblings.
10816 \sa raise(), lower()
10818 void QWidget::stackUnder(QWidget* w)
10820 Q_D(QWidget);
10821 QWidget *p = parentWidget();
10822 if (!w || isWindow() || p != w->parentWidget() || this == w)
10823 return;
10824 if (p) {
10825 int from = p->d_func()->children.indexOf(this);
10826 int to = p->d_func()->children.indexOf(w);
10827 Q_ASSERT(from >= 0);
10828 Q_ASSERT(to >= 0);
10829 if (from < to)
10830 --to;
10831 // Do nothing if the widget is already in correct stacking order _and_ created.
10832 if (from != to)
10833 p->d_func()->children.move(from, to);
10834 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10835 create();
10836 else if (from == to)
10837 return;
10839 if (testAttribute(Qt::WA_WState_Created))
10840 d->stackUnder_sys(w);
10842 QEvent e(QEvent::ZOrderChange);
10843 QApplication::sendEvent(this, &e);
10846 void QWidget::styleChange(QStyle&) { }
10847 void QWidget::enabledChange(bool) { } // compat
10848 void QWidget::paletteChange(const QPalette &) { } // compat
10849 void QWidget::fontChange(const QFont &) { } // compat
10850 void QWidget::windowActivationChange(bool) { } // compat
10851 void QWidget::languageChange() { } // compat
10855 \enum QWidget::BackgroundOrigin
10857 \compat
10859 \value WidgetOrigin
10860 \value ParentOrigin
10861 \value WindowOrigin
10862 \value AncestorOrigin
10867 \fn bool QWidget::isVisibleToTLW() const
10869 Use isVisible() instead.
10873 \fn void QWidget::iconify()
10875 Use showMinimized() instead.
10879 \fn void QWidget::constPolish() const
10881 Use ensurePolished() instead.
10885 \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt)
10887 Use setParent() to change the parent or the widget's widget flags;
10888 use move() to move the widget, and use show() to show the widget.
10892 \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt)
10894 Use setParent() to change the parent; use move() to move the
10895 widget, and use show() to show the widget.
10899 \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt)
10901 Use setParent() to change the parent or the widget's widget flags;
10902 use move() to move the widget, and use show() to show the widget.
10906 \fn bool QWidget::hasMouse() const
10908 Use testAttribute(Qt::WA_UnderMouse) instead.
10912 \fn bool QWidget::ownCursor() const
10914 Use testAttribute(Qt::WA_SetCursor) instead.
10918 \fn bool QWidget::ownFont() const
10920 Use testAttribute(Qt::WA_SetFont) instead.
10924 \fn void QWidget::unsetFont()
10926 Use setFont(QFont()) instead.
10930 \fn bool QWidget::ownPalette() const
10932 Use testAttribute(Qt::WA_SetPalette) instead.
10936 \fn void QWidget::unsetPalette()
10938 Use setPalette(QPalette()) instead.
10942 \fn void QWidget::setEraseColor(const QColor &color)
10944 Use the palette instead.
10946 \oldcode
10947 widget->setEraseColor(color);
10948 \newcode
10949 QPalette palette;
10950 palette.setColor(widget->backgroundRole(), color);
10951 widget->setPalette(palette);
10952 \endcode
10956 \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
10958 Use the palette instead.
10960 \oldcode
10961 widget->setErasePixmap(pixmap);
10962 \newcode
10963 QPalette palette;
10964 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
10965 widget->setPalette(palette);
10966 \endcode
10970 \fn void QWidget::setPaletteForegroundColor(const QColor &color)
10972 Use the palette directly.
10974 \oldcode
10975 widget->setPaletteForegroundColor(color);
10976 \newcode
10977 QPalette palette;
10978 palette.setColor(widget->foregroundRole(), color);
10979 widget->setPalette(palette);
10980 \endcode
10984 \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
10986 Use the palette directly.
10988 \oldcode
10989 widget->setPaletteBackgroundColor(color);
10990 \newcode
10991 QPalette palette;
10992 palette.setColor(widget->backgroundRole(), color);
10993 widget->setPalette(palette);
10994 \endcode
10998 \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
11000 Use the palette directly.
11002 \oldcode
11003 widget->setPaletteBackgroundPixmap(pixmap);
11004 \newcode
11005 QPalette palette;
11006 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11007 widget->setPalette(palette);
11008 \endcode
11012 \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
11014 Use the palette instead.
11016 \oldcode
11017 widget->setBackgroundPixmap(pixmap);
11018 \newcode
11019 QPalette palette;
11020 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11021 widget->setPalette(palette);
11022 \endcode
11026 \fn void QWidget::setBackgroundColor(const QColor &color)
11028 Use the palette instead.
11030 \oldcode
11031 widget->setBackgroundColor(color);
11032 \newcode
11033 QPalette palette;
11034 palette.setColor(widget->backgroundRole(), color);
11035 widget->setPalette(palette);
11036 \endcode
11040 \fn QColorGroup QWidget::colorGroup() const
11042 Use QColorGroup(palette()) instead.
11046 \fn QWidget *QWidget::parentWidget(bool sameWindow) const
11048 Use the no-argument overload instead.
11052 \fn void QWidget::setKeyCompression(bool b)
11054 Use setAttribute(Qt::WA_KeyCompression, b) instead.
11058 \fn void QWidget::setFont(const QFont &f, bool b)
11060 Use the single-argument overload instead.
11064 \fn void QWidget::setPalette(const QPalette &p, bool b)
11066 Use the single-argument overload instead.
11070 \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background)
11072 \obsolete
11076 \fn BackgroundOrigin QWidget::backgroundOrigin() const
11078 \obsolete
11080 Always returns \c WindowOrigin.
11084 \fn QPoint QWidget::backgroundOffset() const
11086 \obsolete
11088 Always returns QPoint().
11092 \fn void QWidget::repaint(bool b)
11094 The boolean parameter \a b is ignored. Use the no-argument overload instead.
11098 \fn void QWidget::repaint(int x, int y, int w, int h, bool b)
11100 The boolean parameter \a b is ignored. Use the four-argument overload instead.
11104 \fn void QWidget::repaint(const QRect &r, bool b)
11106 The boolean parameter \a b is ignored. Use the single rect-argument overload instead.
11110 \fn void QWidget::repaint(const QRegion &rgn, bool b)
11112 The boolean parameter \a b is ignored. Use the single region-argument overload instead.
11116 \fn void QWidget::erase()
11118 Drawing may only take place in a QPaintEvent. Overload
11119 paintEvent() to do your erasing and call update() to schedule a
11120 replaint whenever necessary. See also QPainter.
11124 \fn void QWidget::erase(int x, int y, int w, int h)
11126 Drawing may only take place in a QPaintEvent. Overload
11127 paintEvent() to do your erasing and call update() to schedule a
11128 replaint whenever necessary. See also QPainter.
11132 \fn void QWidget::erase(const QRect &rect)
11134 Drawing may only take place in a QPaintEvent. Overload
11135 paintEvent() to do your erasing and call update() to schedule a
11136 replaint whenever necessary. See also QPainter.
11140 \fn void QWidget::drawText(const QPoint &p, const QString &s)
11142 Drawing may only take place in a QPaintEvent. Overload
11143 paintEvent() to do your drawing and call update() to schedule a
11144 replaint whenever necessary. See also QPainter.
11148 \fn void QWidget::drawText(int x, int y, const QString &s)
11150 Drawing may only take place in a QPaintEvent. Overload
11151 paintEvent() to do your drawing and call update() to schedule a
11152 replaint whenever necessary. See also QPainter.
11156 \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const
11158 Use the single point argument overload instead.
11162 \fn void QWidget::setCaption(const QString &c)
11164 Use setWindowTitle() instead.
11168 \fn void QWidget::setIcon(const QPixmap &i)
11170 Use setWindowIcon() instead.
11174 \fn void QWidget::setIconText(const QString &it)
11176 Use setWindowIconText() instead.
11180 \fn QString QWidget::caption() const
11182 Use windowTitle() instead.
11186 \fn QString QWidget::iconText() const
11188 Use windowIconText() instead.
11192 \fn bool QWidget::isTopLevel() const
11193 \obsolete
11195 Use isWindow() instead.
11199 \fn bool QWidget::isRightToLeft() const
11200 \internal
11204 \fn bool QWidget::isLeftToRight() const
11205 \internal
11209 \fn void QWidget::setInputMethodEnabled(bool enabled)
11211 Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead.
11215 \fn bool QWidget::isInputMethodEnabled() const
11217 Use testAttribute(Qt::WA_InputMethodEnabled) instead.
11221 \fn void QWidget::setActiveWindow()
11223 Use activateWindow() instead.
11227 \fn bool QWidget::isShown() const
11229 Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible.
11233 \fn bool QWidget::isDialog() const
11235 Use windowType() == Qt::Dialog instead.
11239 \fn bool QWidget::isPopup() const
11241 Use windowType() == Qt::Popup instead.
11245 \fn bool QWidget::isDesktop() const
11247 Use windowType() == Qt::Desktop instead.
11251 \fn void QWidget::polish()
11253 Use ensurePolished() instead.
11257 \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const
11259 Use the childAt() overload that doesn't have an \a includeThis parameter.
11261 \oldcode
11262 return widget->childAt(x, y, true);
11263 \newcode
11264 QWidget *child = widget->childAt(x, y, true);
11265 if (child)
11266 return child;
11267 if (widget->rect().contains(x, y))
11268 return widget;
11269 \endcode
11273 \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
11274 \compat
11276 Use the \l sizePolicy property and heightForWidth() function instead.
11280 \fn bool QWidget::isUpdatesEnabled() const
11281 \compat
11283 Use the \l updatesEnabled property instead.
11287 \macro QWIDGETSIZE_MAX
11288 \relates QWidget
11290 Defines the maximum size for a QWidget object.
11292 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
11293 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
11295 \sa QWidget::setMaximumSize()
11298 QRect QWidgetPrivate::frameStrut() const
11300 Q_Q(const QWidget);
11301 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
11302 // x2 = x1 + w - 1, so w/h = 1
11303 return QRect(0, 0, 1, 1);
11306 if (data.fstrut_dirty
11307 #ifndef Q_WS_WIN
11308 // ### Fix properly for 4.3
11309 && q->isVisible()
11310 #endif
11311 && q->testAttribute(Qt::WA_WState_Created))
11312 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
11314 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
11318 \preliminary
11319 \since 4.2
11320 \obsolete
11322 Sets the window surface to be the \a surface specified.
11323 The QWidget takes will ownership of the \a surface.
11324 widget itself is deleted.
11326 void QWidget::setWindowSurface(QWindowSurface *surface)
11328 // ### createWinId() ??
11330 #ifndef Q_BACKINGSTORE_SUBSURFACES
11331 if (!isTopLevel())
11332 return;
11333 #endif
11335 Q_D(QWidget);
11337 QTLWExtra *topData = d->topData();
11338 if (topData->windowSurface == surface)
11339 return;
11341 QWindowSurface *oldSurface = topData->windowSurface;
11342 delete topData->windowSurface;
11343 topData->windowSurface = surface;
11345 QWidgetBackingStore *bs = d->maybeBackingStore();
11346 if (!bs)
11347 return;
11349 if (isTopLevel()) {
11350 if (bs->windowSurface != oldSurface && bs->windowSurface != surface)
11351 delete bs->windowSurface;
11352 bs->windowSurface = surface;
11354 #ifdef Q_BACKINGSTORE_SUBSURFACES
11355 else {
11356 bs->subSurfaces.append(surface);
11358 bs->subSurfaces.removeOne(oldSurface);
11359 #endif
11363 \preliminary
11364 \since 4.2
11366 Returns the QWindowSurface this widget will be drawn into.
11368 QWindowSurface *QWidget::windowSurface() const
11370 Q_D(const QWidget);
11371 QTLWExtra *extra = d->maybeTopData();
11372 if (extra && extra->windowSurface)
11373 return extra->windowSurface;
11375 QWidgetBackingStore *bs = d->maybeBackingStore();
11377 #ifdef Q_BACKINGSTORE_SUBSURFACES
11378 if (bs && bs->subSurfaces.isEmpty())
11379 return bs->windowSurface;
11381 if (!isTopLevel()) {
11382 const QWidget *w = parentWidget();
11383 while (w) {
11384 QTLWExtra *extra = w->d_func()->maybeTopData();
11385 if (extra && extra->windowSurface)
11386 return extra->windowSurface;
11387 if (w->isTopLevel())
11388 break;
11389 w = w->parentWidget();
11392 #endif // Q_BACKINGSTORE_SUBSURFACES
11394 return bs ? bs->windowSurface : 0;
11397 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
11399 if (left)
11400 *left = (int)leftLayoutItemMargin;
11401 if (top)
11402 *top = (int)topLayoutItemMargin;
11403 if (right)
11404 *right = (int)rightLayoutItemMargin;
11405 if (bottom)
11406 *bottom = (int)bottomLayoutItemMargin;
11409 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
11411 if (leftLayoutItemMargin == left
11412 && topLayoutItemMargin == top
11413 && rightLayoutItemMargin == right
11414 && bottomLayoutItemMargin == bottom)
11415 return;
11417 Q_Q(QWidget);
11418 leftLayoutItemMargin = (signed char)left;
11419 topLayoutItemMargin = (signed char)top;
11420 rightLayoutItemMargin = (signed char)right;
11421 bottomLayoutItemMargin = (signed char)bottom;
11422 q->updateGeometry();
11425 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
11427 Q_Q(QWidget);
11428 QStyleOption myOpt;
11429 if (!opt) {
11430 myOpt.initFrom(q);
11431 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
11432 opt = &myOpt;
11435 QRect liRect = q->style()->subElementRect(element, opt, q);
11436 if (liRect.isValid()) {
11437 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
11438 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
11439 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
11440 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
11441 } else {
11442 leftLayoutItemMargin = 0;
11443 topLayoutItemMargin = 0;
11444 rightLayoutItemMargin = 0;
11445 bottomLayoutItemMargin = 0;
11448 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
11449 void QWidgetPrivate::adjustQuitOnCloseAttribute()
11451 Q_Q(QWidget);
11453 if (!q->parentWidget()) {
11454 Qt::WindowType type = q->windowType();
11455 if (type == Qt::Widget || type == Qt::SubWindow)
11456 type = Qt::Window;
11457 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
11458 q->setAttribute(Qt::WA_QuitOnClose, false);
11464 Q_GUI_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
11466 return widget->data;
11469 Q_GUI_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
11471 return widget->d_func();
11475 #ifndef QT_NO_GRAPHICSVIEW
11477 \since 4.5
11479 Returns the proxy widget for the corresponding embedded widget in a graphics
11480 view; otherwise returns 0.
11482 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11483 QGraphicsScene::addWidget()
11485 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11487 Q_D(const QWidget);
11488 if (d->extra) {
11489 return d->extra->proxyWidget;
11491 return 0;
11493 #endif
11497 \typedef QWidgetList
11498 \relates QWidget
11500 Synonym for QList<QWidget *>.
11503 QT_END_NAMESPACE
11505 #include "moc_qwidget.cpp"
11508 \typedef WId
11509 \relates QWidget
11511 Platform dependent window identifier.
11515 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11517 Frees up window system resources. Destroys the widget window if \a
11518 destroyWindow is true.
11520 destroy() calls itself recursively for all the child widgets,
11521 passing \a destroySubWindows for the \a destroyWindow parameter.
11522 To have more control over destruction of subwidgets, destroy
11523 subwidgets selectively first.
11525 This function is usually called from the QWidget destructor.
11529 \fn QPaintEngine *QWidget::paintEngine() const
11531 Returns the widget's paint engine.
11533 Note that this function should not be called explicitly by the
11534 user, since it's meant for reimplementation purposes only. The
11535 function is called by Qt internally, and the default
11536 implementation may not always return a valid pointer.
11540 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11542 Translates the widget coordinate \a pos to global screen
11543 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11544 the global coordinates of the top-left pixel of the widget.
11546 \sa mapFromGlobal() mapTo() mapToParent()
11550 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11552 Translates the global screen coordinate \a pos to widget
11553 coordinates.
11555 \sa mapToGlobal() mapFrom() mapFromParent()
11559 \fn void QWidget::grabMouse()
11561 Grabs the mouse input.
11563 This widget receives all mouse events until releaseMouse() is
11564 called; other widgets get no mouse events at all. Keyboard
11565 events are not affected. Use grabKeyboard() if you want to grab
11566 that.
11568 \warning Bugs in mouse-grabbing applications very often lock the
11569 terminal. Use this function with extreme caution, and consider
11570 using the \c -nograb command line option while debugging.
11572 It is almost never necessary to grab the mouse when using Qt, as
11573 Qt grabs and releases it sensibly. In particular, Qt grabs the
11574 mouse when a mouse button is pressed and keeps it until the last
11575 button is released.
11577 Note that only visible widgets can grab mouse input. If
11578 isVisible() returns false for a widget, that widget cannot call
11579 grabMouse().
11581 \sa releaseMouse() grabKeyboard() releaseKeyboard() grabKeyboard()
11582 focusWidget()
11586 \fn void QWidget::grabMouse(const QCursor &cursor)
11587 \overload
11589 Grabs the mouse input and changes the cursor shape.
11591 The cursor will assume shape \a cursor (for as long as the mouse
11592 focus is grabbed) and this widget will be the only one to receive
11593 mouse events until releaseMouse() is called().
11595 \warning Grabbing the mouse might lock the terminal.
11597 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11601 \fn void QWidget::releaseMouse()
11603 Releases the mouse grab.
11605 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11609 \fn void QWidget::grabKeyboard()
11611 Grabs the keyboard input.
11613 This widget receives all keyboard events until releaseKeyboard()
11614 is called; other widgets get no keyboard events at all. Mouse
11615 events are not affected. Use grabMouse() if you want to grab that.
11617 The focus widget is not affected, except that it doesn't receive
11618 any keyboard events. setFocus() moves the focus as usual, but the
11619 new focus widget receives keyboard events only after
11620 releaseKeyboard() is called.
11622 If a different widget is currently grabbing keyboard input, that
11623 widget's grab is released first.
11625 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11629 \fn void QWidget::releaseKeyboard()
11631 Releases the keyboard grab.
11633 \sa grabKeyboard(), grabMouse(), releaseMouse()
11637 \fn QWidget *QWidget::mouseGrabber()
11639 Returns the widget that is currently grabbing the mouse input.
11641 If no widget in this application is currently grabbing the mouse,
11642 0 is returned.
11644 \sa grabMouse(), keyboardGrabber()
11648 \fn QWidget *QWidget::keyboardGrabber()
11650 Returns the widget that is currently grabbing the keyboard input.
11652 If no widget in this application is currently grabbing the
11653 keyboard, 0 is returned.
11655 \sa grabMouse(), mouseGrabber()
11659 \fn void QWidget::activateWindow()
11661 Sets the top-level widget containing this widget to be the active
11662 window.
11664 An active window is a visible top-level window that has the
11665 keyboard input focus.
11667 This function performs the same operation as clicking the mouse on
11668 the title bar of a top-level window. On X11, the result depends on
11669 the Window Manager. If you want to ensure that the window is
11670 stacked on top as well you should also call raise(). Note that the
11671 window must be visible, otherwise activateWindow() has no effect.
11673 On Windows, if you are calling this when the application is not
11674 currently the active one then it will not make it the active
11675 window. It will change the color of the taskbar entry to indicate
11676 that the window has changed in some way. This is because Microsoft
11677 does not allow an application to interrupt what the user is currently
11678 doing in another application.
11680 \sa isActiveWindow(), window(), show()
11684 \fn int QWidget::metric(PaintDeviceMetric m) const
11686 Internal implementation of the virtual QPaintDevice::metric()
11687 function.
11689 \a m is the metric to get.
11693 \fn void QWidget::setMask(const QRegion &region)
11694 \overload
11696 Causes only the parts of the widget which overlap \a region to be
11697 visible. If the region includes pixels outside the rect() of the
11698 widget, window system controls in that area may or may not be
11699 visible, depending on the platform.
11701 Note that this effect can be slow if the region is particularly
11702 complex.
11704 \sa windowOpacity
11706 void QWidget::setMask(const QRegion &newMask)
11708 Q_D(QWidget);
11710 d->createExtra();
11711 if (newMask == d->extra->mask)
11712 return;
11714 #ifndef QT_NO_BACKINGSTORE
11715 const QRegion oldMask(d->extra->mask);
11716 #endif
11718 d->extra->mask = newMask;
11719 d->extra->hasMask = !newMask.isEmpty();
11721 #ifndef QT_MAC_USE_COCOA
11722 if (!testAttribute(Qt::WA_WState_Created))
11723 return;
11724 #endif
11726 d->setMask_sys(newMask);
11728 #ifndef QT_NO_BACKINGSTORE
11729 if (!isVisible())
11730 return;
11732 if (!d->extra->hasMask) {
11733 // Mask was cleared; update newly exposed area.
11734 QRegion expose(rect());
11735 expose -= oldMask;
11736 if (!expose.isEmpty()) {
11737 d->setDirtyOpaqueRegion();
11738 update(expose);
11740 return;
11743 if (!isWindow()) {
11744 // Update newly exposed area on the parent widget.
11745 QRegion parentExpose(rect());
11746 parentExpose -= newMask;
11747 if (!parentExpose.isEmpty()) {
11748 d->setDirtyOpaqueRegion();
11749 parentExpose.translate(data->crect.topLeft());
11750 parentWidget()->update(parentExpose);
11753 // Update newly exposed area on this widget
11754 if (!oldMask.isEmpty())
11755 update(newMask - oldMask);
11757 #endif
11761 \fn void QWidget::setMask(const QBitmap &bitmap)
11763 Causes only the pixels of the widget for which \a bitmap has a
11764 corresponding 1 bit to be visible. If the region includes pixels
11765 outside the rect() of the widget, window system controls in that
11766 area may or may not be visible, depending on the platform.
11768 Note that this effect can be slow if the region is particularly
11769 complex.
11771 The following code shows how an image with an alpha channel can be
11772 used to generate a mask for a widget:
11774 \snippet doc/src/snippets/widget-mask/main.cpp 0
11776 The label shown by this code is masked using the image it contains,
11777 giving the appearance that an irregularly-shaped image is being drawn
11778 directly onto the screen.
11780 Masked widgets receive mouse events only on their visible
11781 portions.
11783 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11785 void QWidget::setMask(const QBitmap &bitmap)
11787 setMask(QRegion(bitmap));
11791 \fn void QWidget::clearMask()
11793 Removes any mask set by setMask().
11795 \sa setMask()
11797 void QWidget::clearMask()
11799 setMask(QRegion());
11803 \preliminary
11804 \since 4.6
11806 Returns the (possibly empty) list of this widget's softkeys.
11807 Returned list cannot be changed. Softkeys should be added
11808 and removed via method called setSoftKeys
11810 \sa setSoftKey(), setSoftKeys()
11812 const QList<QAction*>& QWidget::softKeys() const
11814 Q_D(const QWidget);
11815 if( d->softKeys.count() > 0)
11816 return d->softKeys;
11817 if (isWindow() || !parentWidget())
11818 return d->softKeys;
11820 return parentWidget()->softKeys();
11824 \preliminary
11825 \since 4.6
11827 Sets the softkey \a softkey to this widget's list of softkeys,
11828 Setting 0 as softkey will clear all the existing softkeys set
11829 to the widget
11830 A QWidget can have 0 or more softkeys
11832 \sa softKeys(), setSoftKeys()
11834 void QWidget::setSoftKey(QAction *softKey)
11836 Q_D(QWidget);
11837 qDeleteAll(d->softKeys);
11838 d->softKeys.clear();
11839 if (softKey)
11840 d->softKeys.append(softKey);
11841 if ((!QApplication::focusWidget() && this == QApplication::activeWindow())
11842 || QApplication::focusWidget() == this)
11843 d->setSoftKeys_sys(this->softKeys());
11847 Sets the list of softkeys \a softkeys to this widget's list of softkeys,
11848 A QWidget can have 0 or more softkeys
11850 \sa softKeys(), setSoftKey()
11852 void QWidget::setSoftKeys(const QList<QAction*> &softKeys)
11854 Q_D(QWidget);
11855 qDeleteAll(d->softKeys);
11856 d->softKeys.clear();
11857 d->softKeys = softKeys;
11859 if ((!QApplication::focusWidget() && this == QApplication::activeWindow())
11860 || QApplication::focusWidget() == this)
11861 d->setSoftKeys_sys(this->softKeys());
11864 /*! \fn const QX11Info &QWidget::x11Info() const
11865 Returns information about the configuration of the X display used to display
11866 the widget.
11868 \warning This function is only available on X11.
11871 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11872 Returns the X11 Picture handle of the widget for XRender
11873 support. Use of this function is not portable. This function will
11874 return 0 if XRender support is not compiled into Qt, if the
11875 XRender extension is not supported on the X11 display, or if the
11876 handle could not be created.