1 /****************************************************************************
3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
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
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.
40 ****************************************************************************/
42 #include "qapplication.h"
43 #include "qapplication_p.h"
46 #include "qdesktopwidget.h"
51 #include "qmetaobject.h"
56 #include "qstylefactory.h"
59 #include "qstyleoption.h"
60 #ifndef QT_NO_ACCESSIBILITY
61 # include "qaccessible.h"
64 # include "qt_windows.h"
67 # include "qt_mac_p.h"
68 # include "qt_cocoa_helpers_mac_p.h"
69 # include "qmainwindow.h"
72 # include "qwsdisplay_qws.h"
73 # include "qwsmanager_qws.h"
74 # include "qpaintengine.h" // for PorterDuff
75 # include "private/qwindowsurface_qws_p.h"
79 #include "qwhatsthis.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>
93 # include <private/qpaintengine_x11_p.h>
94 # include "qx11info_x11.h"
97 #include <private/qwindowsurface_p.h>
98 #include <private/qbackingstore_p.h>
100 # include <private/qpaintengine_mac_p.h>
102 #include <private/qpaintengine_raster_p.h>
104 #if defined(Q_OS_SYMBIAN)
105 #include "private/qt_s60_p.h"
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
126 #if !defined(Q_WS_QWS)
127 static bool qt_enable_backingstore
= true;
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
;
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()
146 return QApplicationPrivate::graphicsSystem() != 0;
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
)
163 if (p
->windowFlags() & Qt::BypassGraphicsProxyWidget
)
165 p
= p
->parentWidget();
171 # define QT_NO_PAINT_DEBUG
174 extern bool qt_sendSpontaneousEvent(QObject
*, QEvent
*); // qapplication.cpp
175 extern QDesktopWidget
*qt_desktopWidget
; // qapplication.cpp
177 QWidgetPrivate::QWidgetPrivate(int version
)
178 : QObjectPrivate(version
)
187 , extraPaintEngine(0)
190 , inheritedFontResolveMask(0)
191 , inheritedPaletteResolveMask(0)
196 , leftLayoutItemMargin(0)
197 , topLayoutItemMargin(0)
198 , rightLayoutItemMargin(0)
199 , bottomLayoutItemMargin(0)
201 , size_policy(QSizePolicy::Preferred
, QSizePolicy::Preferred
)
202 , fg_role(QPalette::NoRole
)
203 , bg_role(QPalette::NoRole
)
204 , dirtyOpaqueChildren(1)
209 , usesDoubleBufferedGLContext(0)
210 #if defined(Q_WS_X11)
212 #elif defined(Q_WS_WIN)
214 #elif defined(Q_WS_MAC)
215 , needWindowChange(0)
220 ,imHints(Qt::ImhNone
)
223 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
227 if (version
!= QObjectPrivateVersion
)
228 qFatal("Cannot mix incompatible Qt libraries");
231 memset(high_attributes
, 0, sizeof(high_attributes
));
232 #ifdef QWIDGET_EXTRA_DEBUG
233 static int count
= 0;
234 qDebug() << "widgets" << ++count
;
239 QWidgetPrivate::~QWidgetPrivate()
247 delete graphicsEffect
;
250 QWindowSurface
*QWidgetPrivate::createDefaultWindowSurface()
253 if (QApplicationPrivate::graphicsSystem())
254 return QApplicationPrivate::graphicsSystem()->createWindowSurface(q
);
255 return createDefaultWindowSurface_sys();
261 void QWidgetPrivate::scrollChildren(int dx
, int dy
)
264 if (q
->children().size() > 0) { // scroll children
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());
274 if (w
->testAttribute(Qt::WA_WState_Created
))
275 w
->d_func()->setWSGeometry();
277 w
->d_func()->setDirtyOpaqueRegion();
278 QMoveEvent
e(r
.topLeft(), oldp
);
279 QApplication::sendEvent(w
, &e
);
285 QInputContext
*QWidgetPrivate::inputContext() const
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()
307 if (!testAttribute(Qt::WA_InputMethodEnabled
))
310 return d
->inputContext();
314 This function sets the input context \a context
319 void QWidget::setInputContext(QInputContext
*context
)
322 if (!testAttribute(Qt::WA_InputMethodEnabled
))
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()
349 QInputContext
*qic
= this->inputContext();
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
381 This feature is only available in Qt for Embedded Linux.
383 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
385 void QWidget::setEditFocus(bool on
)
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())
397 if ((!on
&& !QWidgetPrivate::editingWidget
)
398 || (on
&& QWidgetPrivate::editingWidget
== f
)) {
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
);
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
418 \property QWidget::autoFillBackground
419 \brief whether the widget background is filled automatically
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
444 return d
->extra
&& d
->extra
->autoFillBackground
;
447 void QWidget::setAutoFillBackground(bool enabled
)
452 if (d
->extra
->autoFillBackground
== enabled
)
455 d
->extra
->autoFillBackground
= enabled
;
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:
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
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
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
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
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
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:
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.)
620 Widgets that accept keyboard input need to reimplement a few more event
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
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
634 \i focusOutEvent() is called when the widget loses keyboard focus.
637 You may be required to also reimplement some of the less common event
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
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
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
661 \i moveEvent() is called when the widget has been moved relative to
663 \i closeEvent() is called when the user closes the widget (or when
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()
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
681 \header \i Context \i Functions and Properties
683 \row \i Window functions \i
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(),
696 \row \i Window contents \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,
707 mapFromGlobal(), mapToGlobal(),
708 mapFromParent(), mapToParent(),
709 \l maximumSize, \l minimumSize, \l sizeIncrement,
710 \l baseSize, setFixedSize()
713 \l visible, isVisibleTo(),
714 \l enabled, isEnabledTo(),
721 \row \i Look and feel \i
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
745 mouseDoubleClickEvent(),
768 \row \i System functions \i
769 parentWidget(), window(), setParent(), winId(),
772 \row \i Interactive help \i
773 setToolTip(), setWhatsThis()
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
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:
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.
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
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.
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.
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:
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
901 \sa QEvent, QPainter, QGridLayout, QBoxLayout
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.
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
)
941 QWidgetBackingStore
*bs
= qt_widget_private(widget
)->maybeBackingStore();
945 return bs
->dirtyRegion(widget
);
948 /*****************************************************************************
949 QWidget member functions
950 *****************************************************************************/
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().
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
) {
978 d
->focus_next
->d_func()->focus_prev
= d
->focus_prev
;
980 d
->focus_prev
->d_func()->focus_next
= d
->focus_next
;
987 Constructs a widget which is a child of \a parent, with widget
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
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.
1012 QWidget::QWidget(QWidget
*parent
, Qt::WindowFlags f
)
1013 : QObject(*new QWidgetPrivate
, 0), QPaintDevice()
1016 d_func()->init(parent
, f
);
1018 QWidgetExceptionCleaner::cleanup(this, d_func());
1028 QWidget::QWidget(QWidget
*parent
, const char *name
, Qt::WindowFlags f
)
1029 : QObject(*new QWidgetPrivate
, 0), QPaintDevice()
1032 d_func()->init(parent
, f
);
1033 setObjectName(QString::fromAscii(name
));
1035 QWidgetExceptionCleaner::cleanup(this, d_func());
1043 QWidget::QWidget(QWidgetPrivate
&dd
, QWidget
* parent
, Qt::WindowFlags f
)
1044 : QObject(dd
, 0), QPaintDevice()
1050 QWidgetExceptionCleaner::cleanup(this, d_func());
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()) {
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.
1089 if (flags
& (Qt::WindowMinMaxButtonsHint
| Qt::WindowCloseButtonHint
| Qt::WindowContextHelpButtonHint
)) {
1090 flags
|= Qt::WindowSystemMenuHint
;
1092 if (flags
& (Qt::WindowMinMaxButtonsHint
| Qt::WindowCloseButtonHint
1093 | Qt::WindowSystemMenuHint
)) {
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
;
1106 ; // don't modify window flags if the user explicitely set them.
1107 else if (type
== Qt::Dialog
|| type
== Qt::Sheet
)
1109 flags
|= Qt::WindowTitleHint
| Qt::WindowSystemMenuHint
| Qt::WindowContextHelpButtonHint
| Qt::WindowCloseButtonHint
;
1111 flags
|= Qt::WindowTitleHint
| Qt::WindowSystemMenuHint
| Qt::WindowCloseButtonHint
;
1113 else if (type
== Qt::Tool
)
1114 flags
|= Qt::WindowTitleHint
| Qt::WindowSystemMenuHint
| Qt::WindowCloseButtonHint
;
1116 flags
|= Qt::WindowTitleHint
| Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint
;
1121 void QWidgetPrivate::init(QWidget
*parentWidget
, Qt::WindowFlags f
)
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
;
1138 #ifndef QT_NO_THREAD
1140 Q_ASSERT_X(q
->thread() == qApp
->thread(), "QWidget",
1141 "Widgets must be created in the GUI thread.");
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
;
1152 Q_UNUSED(desktopWidget
);
1155 data
.fstrut_dirty
= true;
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;
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
);
1176 data
.window_state_internal
= 0;
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
)
1191 else if (parentWidget
)
1192 q
->setParent(parentWidget
, data
.window_flags
);
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());
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
))
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()
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
)
1259 if (testAttribute(Qt::WA_WState_Created
) && window
== 0 && internalWinId())
1262 if (d
->data
.in_destructor
)
1265 Qt::WindowType type
= windowType();
1266 Qt::WindowFlags
&flags
= data
->window_flags
;
1268 if ((type
== Qt::Widget
|| type
== Qt::SubWindow
) && !parentWidget()) {
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());
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
);
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
);
1315 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1316 << "Alien?" << !testAttribute(Qt::WA_NativeWindow
);
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);
1344 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered
))
1345 setAttribute(Qt::WA_DropSiteRegistered
, true);
1348 extern void qt_eval_init_widget(QWidget
*w
);
1349 qt_eval_init_widget(this);
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.
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());
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);
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());
1401 // delete layout while we still are a valid widget
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;
1415 if (QApplicationPrivate::main_widget
== this) { // reset main widget
1416 QApplicationPrivate::main_widget
= 0;
1417 QApplication::quit();
1424 // swallow this problem because we are in a destructor
1427 d
->setDirtyOpaqueRegion();
1429 if (isWindow() && isVisible() && internalWinId()) {
1431 d
->close_helper(QWidgetPrivate::CloseNoEvent
);
1433 // if we're out of memory, at least hide the window.
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);
1448 if (QWidgetBackingStore
*bs
= d
->maybeBackingStore()) {
1449 bs
->removeDirtyWidget(this);
1450 if (testAttribute(Qt::WA_StaticContents
))
1451 bs
->removeStaticWidget(this);
1454 delete d
->needsFlush
;
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);
1471 destroy(); // platform-dependent cleanup
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
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
1495 bool userDesktopWidget
= qt_desktopWidget
!= 0 && qt_desktopWidget
!= q
&& q
->windowType() == Qt::Desktop
;
1496 if (mapper
&& data
.winid
&& !userDesktopWidget
) {
1497 mapper
->remove(data
.winid
);
1501 #if defined(Q_WS_X11)
1502 hd
= id
; // X11: hd == ident
1504 if (mapper
&& id
&& !userDesktopWidget
) {
1505 mapper
->insert(data
.winid
, q
);
1509 void QWidgetPrivate::createTLExtra()
1513 if (!extra
->topextra
) {
1514 QTLWExtra
* x
= extra
->topextra
= new QTLWExtra
;
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);
1526 x
->posFromMove
= false;
1527 x
->sizeAdjusted
= false;
1528 x
->inTopLevelResize
= false;
1529 x
->inRepaint
= false;
1532 #ifdef QWIDGET_EXTRA_DEBUG
1533 static int count
= 0;
1534 qDebug() << "tlextra" << ++count
;
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
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;
1567 #ifdef QWIDGET_EXTRA_DEBUG
1568 static int count
= 0;
1569 qDebug() << "extra" << ++count
;
1577 Deletes the widget extra data.
1580 void QWidgetPrivate::deleteExtra()
1582 if (extra
) { // if exists
1583 #ifndef QT_NO_CURSOR
1587 #ifndef QT_NO_STYLE_STYLESHEET
1588 // dereference the stylesheet style
1589 if (QStyleSheetStyle
*proxy
= qobject_cast
<QStyleSheetStyle
*>(extra
->style
))
1592 if (extra
->topextra
) {
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
;
1600 delete extra
->topextra
->windowSurface
;
1601 delete extra
->topextra
;
1604 // extra->xic destroyed in QWidget::destroy()
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
1618 const QWidget
*w
= q
;
1623 QWidgetPrivate
*pd
= w
->parentWidget()->d_func();
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())
1630 above
= (sibling
== w
);
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
)) {
1643 w
= w
->parentWidget();
1644 r
.translate(pd
->data
.crect
.topLeft());
1649 void QWidgetPrivate::syncBackingStore()
1651 if (paintOnScreen()) {
1654 } else if (QWidgetBackingStore
*bs
= maybeBackingStore()) {
1659 void QWidgetPrivate::syncBackingStore(const QRegion
®ion
)
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
)
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
);
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
);
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()
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
1727 Returns the widget's clipping rectangle.
1729 QRect
QWidgetPrivate::clipRect() const
1732 const QWidget
* w
= q
;
1733 if (!w
->isVisible())
1735 QRect r
= effectiveRectFor(q
->rect());
1741 && w
->parentWidget()) {
1744 w
= w
->parentWidget();
1745 r
&= QRect(ox
, oy
, w
->width(), w
->height());
1751 Returns the widget's clipping region (without siblings).
1753 QRegion
QWidgetPrivate::clipRegion() const
1756 if (!q
->isVisible())
1758 QRegion
r(q
->rect());
1759 const QWidget
* w
= q
;
1760 const QWidget
*ignoreUpTo
;
1766 && w
->parentWidget()) {
1770 w
= w
->parentWidget();
1771 r
&= QRegion(ox
, oy
, w
->width(), w
->height());
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
);
1790 void QWidgetPrivate::setDirtyOpaqueRegion()
1794 dirtyOpaqueChildren
= true;
1799 QWidget
*parent
= q
->parentWidget();
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
1813 QRegion r
= isOpaque
? q
->rect() : getOpaqueChildren();
1814 if (extra
&& extra
->hasMask
)
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())
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())
1848 const QRegion
&r
= getOpaqueChildren();
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
1858 static int disableSubtractOpaqueSiblings
= qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1859 if (disableSubtractOpaqueSiblings
|| q
->isWindow())
1862 QRect clipBoundingRect
;
1863 bool dirtyClipBoundingRect
= true;
1866 bool dirtyParentClip
= true;
1868 QPoint parentOffset
= data
.crect
.topLeft();
1870 const QWidget
*w
= q
;
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())
1883 const QRect siblingGeometry
= sibling
->d_func()->effectiveRectFor(sibling
->data
->crect
);
1884 if (!qRectIntersects(siblingGeometry
, widgetGeometry
))
1887 if (dirtyClipBoundingRect
) {
1888 clipBoundingRect
= sourceRegion
.boundingRect();
1889 dirtyClipBoundingRect
= false;
1892 if (!qRectIntersects(siblingGeometry
, clipBoundingRect
.translated(parentOffset
)))
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
;
1907 siblingDirty
&= sibling
->d_func()->extra
->mask
.translated(siblingPos
);
1908 if (siblingDirty
.isEmpty())
1911 if (sibling
->d_func()->isOpaque
|| alsoNonOpaque
) {
1913 siblingDirty
.translate(-parentOffset
);
1914 sourceRegion
-= siblingDirty
;
1916 sourceRegion
-= siblingGeometry
.translated(-parentOffset
);
1919 if (hasDirtySiblingsAbove
)
1920 *hasDirtySiblingsAbove
= true;
1921 if (sibling
->d_func()->children
.isEmpty())
1923 QRegion
opaqueSiblingChildren(sibling
->d_func()->getOpaqueChildren());
1924 opaqueSiblingChildren
.translate(-parentOffset
+ siblingPos
);
1925 sourceRegion
-= opaqueSiblingChildren
;
1927 if (sourceRegion
.isEmpty())
1930 dirtyClipBoundingRect
= true;
1931 dirtyParentClip
= true;
1934 w
= w
->parentWidget();
1935 parentOffset
+= pd
->data
.crect
.topLeft();
1936 dirtyParentClip
= true;
1940 void QWidgetPrivate::clipToEffectiveMask(QRegion
®ion
) const
1944 const QWidget
*w
= q
;
1947 if (graphicsEffect
) {
1948 w
= q
->parentWidget();
1949 offset
-= data
.crect
.topLeft();
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
;
1958 offset
-= wd
->data
.crect
.topLeft();
1959 w
= w
->parentWidget();
1963 bool QWidgetPrivate::paintOnScreen() const
1965 #if defined(Q_WS_QWS)
1967 #elif defined(QT_NO_BACKINGSTORE)
1971 if (q
->testAttribute(Qt::WA_PaintOnScreen
)
1972 || (!q
->isWindow() && q
->window()->testAttribute(Qt::WA_PaintOnScreen
))) {
1976 return !qt_enable_backingstore
;
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.
1993 if (q
->testAttribute(Qt::WA_X11OpenGLOverlay
)) {
1999 if (q
->testAttribute(Qt::WA_OpaquePaintEvent
) || q
->testAttribute(Qt::WA_PaintOnScreen
)) {
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()) {
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()) {
2024 void QWidgetPrivate::setOpaque(bool opaque
)
2026 if (isOpaque
== opaque
)
2030 macUpdateIsOpaque();
2033 x11UpdateIsOpaque();
2036 winUpdateIsOpaque();
2039 s60UpdateIsOpaque();
2043 void QWidgetPrivate::updateIsTranslucent()
2046 macUpdateIsOpaque();
2049 x11UpdateIsOpaque();
2052 winUpdateIsOpaque();
2055 s60UpdateIsOpaque();
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
2072 void QPixmap::fill( const QWidget
*widget
, const QPoint
&off
)
2076 widget
->d_func()->paintBackground(&p
, QRect(off
, size()));
2079 static inline void fillRegion(QPainter
*painter
, const QRegion
&rgn
, const QBrush
&brush
)
2083 if (brush
.style() == Qt::TexturePattern
) {
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
);
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());
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
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
);
2133 if (!(flags
& DontSetCompositionMode
) && painter
->paintEngine()->hasFeature(QPaintEngine::PorterDuff
))
2134 painter
->setCompositionMode(QPainter::CompositionMode_Source
); //copy alpha straight in
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
);
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
2158 This function is called when a widget is hidden or destroyed.
2159 It resets some application global pointers that should only refer active,
2164 extern QPointer
<QWidget
> qt_button_down
;
2166 extern QWidget
*qt_button_down
;
2169 void QWidgetPrivate::deactivateWidgetCleanup()
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
)
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
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
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
;
2236 void QWidgetPrivate::createWinId(WId winid
)
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()) {
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
)))) {
2258 // if the window has already been created, we
2259 // need to raise it to its proper stacking position
2274 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2278 void QWidget::createWinId()
2281 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
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
2298 \sa nativeParentWidget()
2300 WId
QWidget::effectiveWinId() const
2302 WId id
= internalWinId();
2303 if (id
|| !testAttribute(Qt::WA_WState_Created
))
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
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
2333 return d
->extra
->styleSheet
;
2336 void QWidget::setStyleSheet(const QString
& styleSheet
)
2341 QStyleSheetStyle
*proxy
= qobject_cast
<QStyleSheetStyle
*>(d
->extra
->style
);
2342 d
->extra
->styleSheet
= styleSheet
;
2343 if (styleSheet
.isEmpty()) { // stylesheet removed
2351 if (proxy
) { // style sheet update
2352 proxy
->repolish(this);
2356 if (testAttribute(Qt::WA_SetStyle
)) {
2357 d
->setStyle_helper(new QStyleSheetStyle(d
->extra
->style
), true);
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
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
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
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
)
2402 setAttribute(Qt::WA_SetStyle
, style
!= 0);
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)
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);
2415 d
->setStyle_helper(style
, false);
2418 void QWidgetPrivate::setStyle_helper(QStyle
*newStyle
, bool propagate
, bool
2425 QStyle
*oldStyle
= q
->style();
2426 #ifndef QT_NO_STYLE_STYLESHEET
2427 QStyle
*origStyle
= 0;
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.
2440 #ifndef QT_NO_STYLE_STYLESHEET
2441 origStyle
= extra
->style
;
2443 extra
->style
= newStyle
;
2447 if (q
->windowType() != Qt::Desktop
) {
2449 oldStyle
->unpolish(q
);
2452 macUpdateMetalAttribute();
2454 q
->style()->polish(q
);
2456 } else if (metalHack
) {
2457 macUpdateMetalAttribute();
2463 for (int i
= 0; i
< children
.size(); ++i
) {
2464 QWidget
*c
= qobject_cast
<QWidget
*>(children
.at(i
));
2466 c
->d_func()->inheritStyle();
2470 QEvent
e(QEvent::StyleChange
);
2471 QApplication::sendEvent(q
, &e
);
2473 q
->styleChange(*oldStyle
);
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
);
2484 #ifndef QT_NO_STYLE_STYLESHEET
2485 // dereference the old stylesheet style
2486 if (QStyleSheetStyle
*proxy
= qobject_cast
<QStyleSheetStyle
*>(origStyle
))
2491 // Inherits style from the current parent and propagates it as necessary
2492 void QWidgetPrivate::inheritStyle()
2494 #ifndef QT_NO_STYLE_STYLESHEET
2497 QStyleSheetStyle
*proxy
= extra
? qobject_cast
<QStyleSheetStyle
*>(extra
->style
) : 0;
2499 if (!q
->styleSheet().isEmpty()) {
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
))
2517 setStyle_helper(newStyle
, true);
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?
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
))
2532 setStyle_helper(origStyle
, true);
2533 #endif // QT_NO_STYLE_STYLESHEET
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
);
2551 \fn bool QWidget::isWindow() const
2553 Returns true if the widget is an independent window, otherwise
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
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
2620 This value is not updated properly during drag and drop
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(),
2647 void QWidget::showMinimized()
2649 bool isMin
= isMinimized();
2650 if (isMin
&& isVisible())
2656 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted
);
2660 setWindowState((windowState() & ~Qt::WindowActive
) | Qt::WindowMinimized
);
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
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
);
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
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()
2790 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted
);
2793 setWindowState((windowState() & ~(Qt::WindowMinimized
| Qt::WindowMaximized
))
2794 | Qt::WindowFullScreen
);
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()
2814 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted
);
2817 setWindowState((windowState() & ~(Qt::WindowMinimized
| Qt::WindowFullScreen
))
2818 | Qt::WindowMaximized
);
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()
2834 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted
);
2837 setWindowState(windowState() & ~(Qt::WindowMinimized
2838 | Qt::WindowMaximized
2839 | Qt::WindowFullScreen
));
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
)
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
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
)
2912 qWarning("QWidget::insertAction: Attempt to insert null action");
2917 if(d
->actions
.contains(action
))
2918 removeAction(action
);
2920 int pos
= d
->actions
.indexOf(before
);
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
)
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
2979 #endif // QT_NO_ACTION
2982 \fn bool QWidget::isEnabledToTLW() const
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
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
)
3011 setAttribute(Qt::WA_ForceDisabled
, !enable
);
3012 d
->setEnabled_helper(enable
);
3015 void QWidgetPrivate::setEnabled_helper(bool enable
)
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())
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
3044 extern void qt_x11_enforce_cursor(QWidget
* w
); // defined in qwidget_x11.cpp
3045 qt_x11_enforce_cursor(q
);
3048 #if defined(Q_WS_MAC)
3049 setEnabled_helper_sys(enable
);
3051 if (q
->testAttribute(Qt::WA_InputMethodEnabled
) && q
->hasFocus()) {
3052 QInputContext
*qic
= inputContext();
3054 qic
->setFocusWidget(q
);
3057 qic
->setFocusWidget(0);
3060 QEvent
e(QEvent::EnabledChange
);
3061 QApplication::sendEvent(q
, &e
);
3063 q
->enabledChange(!enable
); // compatibility
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.
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)
3103 \fn void QWidget::paletteChange(const QPalette &)
3110 \fn void QWidget::fontChange(const QFont &)
3117 \fn void QWidget::windowActivationChange(bool)
3124 \fn void QWidget::languageChange()
3130 \fn void QWidget::styleChange(QStyle& style)
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
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
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());
3176 \property QWidget::x
3178 \brief the x coordinate of the widget relative to its parent including
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
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
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
3228 By default, this property contains a position that refers to the
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
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
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.
3362 QRect
QWidget::normalGeometry() const
3365 if (!d
->extra
|| !d
->extra
->topextra
)
3368 if (!isMaximized() && !isFullScreen())
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
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())
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
3408 \sa childrenRect() geometry() mask()
3411 QRegion
QWidget::childrenRegion() const
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();
3422 r
|= mask
.translated(w
->pos());
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
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
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
3465 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3468 QSize
QWidget::maximumSize() const
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
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
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
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
3550 return (d
->extra
&& d
->extra
->topextra
)
3551 ? QSize(d
->extra
->topextra
->incw
, d
->extra
->topextra
->inch
)
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
3571 return (d
->extra
!= 0 && d
->extra
->topextra
!= 0)
3572 ? QSize(d
->extra
->topextra
->basew
, d
->extra
->topextra
->baseh
)
3576 bool QWidgetPrivate::setMinimumSize_helper(int &minw
, int &minh
)
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();
3593 int mw
= minw
, mh
= minh
;
3594 if (mw
== QWIDGETSIZE_MAX
)
3596 if (mh
== QWIDGETSIZE_MAX
)
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
,
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) "
3609 q
->objectName().toLocal8Bit().data(), q
->metaObject()->className(), minw
, minh
);
3610 minw
= mw
= qMax(minw
, 0);
3611 minh
= mh
= qMax(minh
, 0);
3614 if (extra
->minw
== mw
&& extra
->minh
== mh
)
3618 extra
->explicitMinSize
= (mw
? Qt::Horizontal
: 0) | (mh
? Qt::Vertical
: 0);
3625 This function corresponds to setMinimumSize(QSize(minw, minh)).
3626 Sets the minimum width to \a minw and the minimum height to \a
3630 void QWidget::setMinimumSize(int minw
, int minh
)
3633 if (!d
->setMinimumSize_helper(minw
, minh
))
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
3644 data
->window_state
= data
->window_state
| Qt::WindowMaximized
;
3646 #ifndef QT_NO_GRAPHICSVIEW
3648 if (d
->extra
->proxyWidget
)
3649 d
->extra
->proxyWidget
->setMinimumSize(minw
, minh
);
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
)
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
,
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) "
3669 q
->objectName().toLocal8Bit().data(), q
->metaObject()->className(), maxw
, maxh
);
3670 maxw
= qMax(maxw
, 0);
3671 maxh
= qMax(maxh
, 0);
3674 if (extra
->maxw
== maxw
&& extra
->maxh
== maxh
)
3678 extra
->explicitMaxSize
= (maxw
!= QWIDGETSIZE_MAX
? Qt::Horizontal
: 0) |
3679 (maxh
!= QWIDGETSIZE_MAX
? Qt::Vertical
: 0);
3686 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3687 maxh)). Sets the maximum width to \a maxw and the maximum height
3690 void QWidget::setMaximumSize(int maxw
, int maxh
)
3693 if (!d
->setMaximumSize_helper(maxw
, maxh
))
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
3706 if (d
->extra
->proxyWidget
)
3707 d
->extra
->proxyWidget
->setMaximumSize(maxw
, maxh
);
3711 d
->updateGeometry_helper(d
->extra
->minw
== d
->extra
->maxw
&& d
->extra
->minh
== d
->extra
->maxh
);
3717 Sets the x (width) size increment to \a w and the y (height) size
3720 void QWidget::setSizeIncrement(int w
, int h
)
3724 QTLWExtra
* x
= d
->topData();
3725 if (x
->incw
== w
&& x
->inch
== h
)
3730 d
->setConstraints_sys();
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
)
3743 QTLWExtra
* x
= d
->topData();
3744 if (x
->basew
== basew
&& x
->baseh
== baseh
)
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)
3777 Sets the width of the widget to \a w and the height to \a h.
3780 void QWidget::setFixedSize(int w
, int h
)
3784 // temporary fix for 4.3.x.
3785 // Should move the embedded spesific contraints in setMinimumSize_helper into QLayout
3788 bool minSizeSet
= d
->setMinimumSize_helper(tmpW
, tmpH
);
3790 bool minSizeSet
= d
->setMinimumSize_helper(w
, h
);
3792 bool maxSizeSet
= d
->setMaximumSize_helper(w
, h
);
3793 if (!minSizeSet
&& !maxSizeSet
)
3797 d
->setConstraints_sys();
3799 d
->updateGeometry_helper(true);
3801 if (w
!= QWIDGETSIZE_MAX
|| h
!= QWIDGETSIZE_MAX
)
3805 void QWidget::setMinimumWidth(int w
)
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
)
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
)
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
)
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
)
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
)
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
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();
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
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();
3931 Translates the widget coordinate \a pos to a coordinate in the
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
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
3972 QWidget
*QWidget::window() const
3974 QWidget
*w
= (QWidget
*)this;
3975 QWidget
*p
= w
->parentWidget();
3976 while (!w
->isWindow() && p
) {
3978 p
= p
->parentWidget();
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();
3999 /*! \fn QWidget *QWidget::topLevelWidget() const
4002 Use window() instead.
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
;
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
;
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
)
4065 if(m
== Qt::NoBackground
) {
4066 setAttribute(Qt::WA_NoSystemBackground
, true);
4069 setAttribute(Qt::WA_NoSystemBackground
, false);
4070 d
->fg_role
= QPalette::NoRole
;
4071 QPalette::ColorRole role
= d
->bg_role
;
4073 case Qt::FixedColor
:
4074 case Qt::FixedPixmap
:
4076 case Qt::PaletteForeground
:
4077 role
= QPalette::WindowText
;
4079 case Qt::PaletteButton
:
4080 role
= QPalette::Button
;
4082 case Qt::PaletteLight
:
4083 role
= QPalette::Light
;
4085 case Qt::PaletteMidlight
:
4086 role
= QPalette::Midlight
;
4088 case Qt::PaletteDark
:
4089 role
= QPalette::Dark
;
4091 case Qt::PaletteMid
:
4092 role
= QPalette::Mid
;
4094 case Qt::PaletteText
:
4095 role
= QPalette::Text
;
4097 case Qt::PaletteBrightText
:
4098 role
= QPalette::BrightText
;
4100 case Qt::PaletteBase
:
4101 role
= QPalette::Base
;
4103 case Qt::PaletteBackground
:
4104 role
= QPalette::Window
;
4106 case Qt::PaletteShadow
:
4107 role
= QPalette::Shadow
;
4109 case Qt::PaletteHighlight
:
4110 role
= QPalette::Highlight
;
4112 case Qt::PaletteHighlightedText
:
4113 role
= QPalette::HighlightedText
;
4115 case Qt::PaletteButtonText
:
4116 role
= QPalette::ButtonText
;
4118 case Qt::PaletteLink
:
4119 role
= QPalette::Link
;
4121 case Qt::PaletteLinkVisited
:
4122 role
= QPalette::LinkVisited
;
4124 case Qt::X11ParentRelative
:
4125 d
->fg_role
= role
= QPalette::NoRole
;
4129 setBackgroundRole(role
);
4133 The widget mapper is no longer part of the public API.
4135 QT3_SUPPORT QWidgetMapper
*QWidget::wmapper() { return QWidgetPrivate::mapper
; }
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;
4156 QPalette::ColorRole role
= w
->d_func()->bg_role
;
4157 if (role
!= QPalette::NoRole
)
4159 if (w
->isWindow() || w
->windowType() == Qt::SubWindow
)
4161 w
= w
->parentWidget();
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
)
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
4201 QPalette::ColorRole rl
= QPalette::ColorRole(d
->fg_role
);
4202 if (rl
!= QPalette::NoRole
)
4204 QPalette::ColorRole role
= QPalette::WindowText
;
4205 switch (backgroundRole()) {
4206 case QPalette::Button
:
4207 role
= QPalette::ButtonText
;
4209 case QPalette::Base
:
4210 role
= QPalette::Text
;
4212 case QPalette::Dark
:
4213 case QPalette::Shadow
:
4214 role
= QPalette::Light
;
4216 case QPalette::Highlight
:
4217 role
= QPalette::HighlightedText
;
4219 case QPalette::ToolTipBase
:
4220 role
= QPalette::ToolTipText
;
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
)
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
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
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))
4309 data
->pal
.setCurrentColorGroup(QPalette::Active
);
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
);
4317 data
->pal
.setCurrentColorGroup(QPalette::Inactive
);
4322 void QWidget::setPalette(const QPalette
&palette
)
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
);
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
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
);
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
;
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
)
4390 if (data
.pal
== palette
&& data
.pal
.resolve() == palette
.resolve())
4393 updateSystemBackground();
4394 propagatePaletteChange();
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
)
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
);
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
);
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
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
);
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);
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
4516 void QWidgetPrivate::resolveFont()
4518 QFont naturalFont
= naturalWidgetFont(inheritedFontResolveMask
);
4519 QFont resolvedFont
= data
.fnt
.resolve(naturalFont
);
4520 setFont_helper(resolvedFont
);
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
)
4535 #ifndef QT_NO_STYLE_STYLESHEET
4536 const QStyleSheetStyle
* cssStyle
;
4537 cssStyle
= extra
? qobject_cast
<const QStyleSheetStyle
*>(extra
->style
) : 0;
4541 QFont old
= data
.fnt
;
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());
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
));
4563 #ifndef QT_NO_STYLE_STYLESHEET
4564 } else if (w
->testAttribute(Qt::WA_StyleSheet
)) {
4565 // Style sheets follow a different font propagation scheme.
4567 cssStyle
->updateStyleSheetFont(w
);
4569 } else if ((!w
->isWindow() || w
->testAttribute(Qt::WA_WindowPropagation
))) {
4570 // Propagate font changes.
4571 QWidgetPrivate
*wd
= w
->d_func();
4572 wd
->inheritedFontResolveMask
= newMask
;
4578 #ifndef QT_NO_STYLE_STYLESHEET
4580 cssStyle
->updateStyleSheetFont(q
);
4584 QEvent
e(QEvent::FontChange
);
4585 QApplication::sendEvent(q
, &e
);
4591 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction
)
4595 if ( (direction
== Qt::RightToLeft
) == q
->testAttribute(Qt::WA_RightToLeft
))
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()
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
4628 \sa QApplication::layoutDirection
4630 void QWidget::setLayoutDirection(Qt::LayoutDirection direction
)
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()
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
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
4698 if (testAttribute(Qt::WA_SetCursor
))
4699 return (d
->extra
&& 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
)
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
))
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()
4732 delete d
->extra
->curs
;
4736 setAttribute(Qt::WA_SetCursor
, false);
4737 d
->unsetCursor_sys();
4739 QEvent
event(QEvent::CursorChange
);
4740 QApplication::sendEvent(this, &event
);
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.
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
)
4788 qWarning("QWidget::render: null pointer to paint device");
4792 const bool inRenderWithPainter
= d
->extra
&& d
->extra
->inRenderWithPainter
;
4793 QRegion paintRegion
= !inRenderWithPainter
? d
->prepareToRender(sourceRegion
, renderFlags
)
4795 if (paintRegion
.isEmpty())
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
);
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
);
4824 redirected
= QPainter::redirected(target
, &redirectionOffset
);
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
;
4847 flags
|= QWidgetPrivate::DontSubtractOpaqueChildren
;
4850 flags
|= QWidgetPrivate::DontSetCompositionMode
;
4853 if (target
->devType() == QInternal::Printer
) {
4855 d
->render_helper(&p
, targetOffset
, paintRegion
, renderFlags
);
4860 // Render via backingstore.
4861 d
->drawWidget(target
, paintRegion
, offset
, flags
, d
->sharedPainter());
4863 // Restore shared painter.
4864 if (oldSharedPainter
)
4865 d
->setSharedPainter(oldSharedPainter
);
4867 // Render via backingstore (no shared painter).
4868 d
->drawWidget(target
, paintRegion
, offset
, flags
, 0);
4875 Renders the widget into the \a painter's QPainter::device().
4877 Transformations and settings applied to the \a painter will be used
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
)
4889 qWarning("QWidget::render: Null pointer to painter");
4893 if (!painter
->isActive()) {
4894 qWarning("QWidget::render: Cannot render with an inactive painter");
4898 const qreal opacity
= painter
->opacity();
4899 if (qFuzzyIsNull(opacity
))
4900 return; // Fully transparent.
4903 const bool inRenderWithPainter
= d
->extra
&& d
->extra
->inRenderWithPainter
;
4904 const QRegion toBePainted
= !inRenderWithPainter
? d
->prepareToRender(sourceRegion
, renderFlags
)
4906 if (toBePainted
.isEmpty())
4911 d
->extra
->inRenderWithPainter
= true;
4914 d
->render_helper(painter
, targetOffset
, toBePainted
, renderFlags
);
4916 QPaintEngine
*engine
= painter
->paintEngine();
4918 QPaintEnginePrivate
*enginePriv
= engine
->d_func();
4919 Q_ASSERT(enginePriv
);
4920 QPaintDevice
*target
= engine
->paintDevice();
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;
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
);
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
);
4958 d
->extra
->inRenderWithPainter
= false;
4961 #if !defined(Q_OS_SYMBIAN)
4962 void QWidgetPrivate::setSoftKeys_sys(const QList
<QAction
*> &softkeys
)
4966 #endif // !defined(Q_OS_SYMBIAN)
4968 QGraphicsEffect
*QWidget::graphicsEffect() const
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
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.
4986 void QWidget::setGraphicsEffect(QGraphicsEffect
*effect
)
4989 if (d
->graphicsEffect
== effect
)
4992 if (d
->graphicsEffect
&& effect
) {
4993 delete d
->graphicsEffect
;
4994 d
->graphicsEffect
= 0;
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.
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();
5016 bool QWidgetPrivate::isAboutToShow() const
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
®ion
, QWidget::RenderFlags renderFlags
)
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
;
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
;
5088 void QWidgetPrivate::render_helper(QPainter
*painter
, const QPoint
&targetOffset
, const QRegion
&toBePainted
,
5089 QWidget::RenderFlags renderFlags
)
5092 Q_ASSERT(!toBePainted
.isEmpty());
5096 const QTransform originalTransform
= painter
->worldTransform();
5097 const bool useDeviceCoordinates
= originalTransform
.isScaling();
5098 if (!useDeviceCoordinates
) {
5100 // Render via a pixmap.
5101 const QRect rect
= toBePainted
.boundingRect();
5102 const QSize size
= rect
.size();
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
);
5117 painter
->setRenderHints(QPainter::SmoothPixmapTransform
, false);
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();
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
);
5153 void QWidgetPrivate::drawWidget(QPaintDevice
*pdev
, const QRegion
&rgn
, const QPoint
&offset
, int flags
,
5154 QPainter
*sharedPainter
, QWidgetBackingStore
*backingStore
)
5160 if (graphicsEffect
&& graphicsEffect
->isEnabled()) {
5161 QGraphicsEffectSource
*source
= graphicsEffect
->d_func()->source
;
5162 QWidgetEffectSourcePrivate
*sourced
= static_cast<QWidgetEffectSourcePrivate
*>
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
);
5171 p
.translate(offset
);
5172 context
.painter
= &p
;
5173 graphicsEffect
->draw(&p
, source
);
5174 paintEngine
->d_func()->systemClip
= QRegion();
5176 context
.painter
= sharedPainter
;
5177 sharedPainter
->save();
5178 sharedPainter
->translate(offset
);
5179 graphicsEffect
->draw(sharedPainter
, source
);
5180 sharedPainter
->restore();
5182 sourced
->context
= 0;
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
);
5212 QPaintEngine
*paintEngine
= pdev
->paintEngine();
5214 setRedirected(pdev
, -offset
);
5217 paintEngine
->d_func()->systemClip
= toBePainted
;
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
)) {
5226 paintBackground(&p
, toBePainted
, (asRoot
|| onScreen
) ? flags
| DrawAsRoot
: 0);
5230 paintEngine
->d_func()->systemClip
= toBePainted
.translated(offset
);
5232 if (!onScreen
&& !asRoot
&& !isOpaque
&& q
->testAttribute(Qt::WA_TintedBackground
)) {
5234 QColor tint
= q
->palette().window().color();
5235 tint
.setAlphaF(qreal(.6));
5236 p
.fillRect(toBePainted
.boundingRect(), tint
);
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());
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
);
5256 restoreRedirected();
5258 paintEngine
->d_func()->systemRect
= QRect();
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()) {
5271 #ifndef QT_NO_PAINT_DEBUG
5273 QWidgetBackingStore::unflushPaint(q
, toBePainted
);
5275 } else if (q
->isWindow()) {
5276 QPaintEngine
*engine
= pdev
->paintEngine();
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());
5284 p
.fillRect(q
->rect(), bg
);
5286 if (engine
->autoDestruct())
5292 if (recursive
&& !children
.isEmpty()) {
5293 paintSiblingsRecursive(pdev
, children
, children
.size() - 1, rgn
, offset
, flags
& ~DrawAsRoot
5294 #ifdef Q_BACKINGSTORE_SUBSURFACES
5295 , q
->windowSurface()
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
5306 , QPainter
*sharedPainter
, QWidgetBackingStore
*backingStore
)
5310 bool dirtyBoundingRect
= true;
5311 const bool exludeOpaqueChildren
= (flags
& DontDrawOpaqueChildren
);
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
)
5332 } while (index
>= 0);
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
;
5344 wr
-= hasMask
? wd
->extra
->mask
.translated(widgetPos
) : w
->data
->crect
;
5345 paintSiblingsRecursive(pdev
, siblings
, --index
, wr
, offset
, flags
5346 #ifdef Q_BACKINGSTORE_SUBSURFACES
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
);
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();
5368 // Device coordinates without context not yet supported.
5369 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
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
);
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");
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();
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
);
5423 offset
->rx() += -left
;
5428 offset
->ry() += -top
;
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
);
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
5457 QGraphicsProxyWidget
* QWidgetPrivate::nearestGraphicsProxyWidget(QWidget
*origin
)
5460 QWExtra
*extra
= origin
->d_func()->extra
;
5461 if (extra
&& extra
->proxyWidget
)
5462 return extra
->proxyWidget
;
5463 return nearestGraphicsProxyWidget(origin
->parentWidget());
5469 \property QWidget::locale
5470 \brief the widget's locale
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),
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
)
5486 if (locale
== loc
&& !forceUpdate
)
5491 if (!children
.isEmpty()) {
5492 for (int i
= 0; i
< children
.size(); ++i
) {
5493 QWidget
*w
= qobject_cast
<QWidget
*>(children
.at(i
));
5496 if (w
->testAttribute(Qt::WA_SetLocale
))
5498 if (w
->isWindow() && !w
->testAttribute(Qt::WA_WindowPropagation
))
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
)
5511 setAttribute(Qt::WA_SetLocale
);
5512 d
->setLocale_helper(locale
);
5515 QLocale
QWidget::locale() const
5522 void QWidgetPrivate::resolveLocale()
5526 if (!q
->testAttribute(Qt::WA_SetLocale
)) {
5527 setLocale_helper(q
->isWindow()
5529 : q
->parentWidget()->locale());
5533 void QWidget::unsetLocale()
5536 setAttribute(Qt::WA_SetLocale
, false);
5540 static QString
constructWindowTitleFromFilePath(const QString
&filePath
)
5542 QFileInfo
fi(filePath
);
5543 QString windowTitle
= fi
.fileName() + QLatin1String("[*]");
5545 QString appName
= QApplication::applicationName();
5546 if (!appName
.isEmpty())
5547 windowTitle
+= QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName
;
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
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
5568 \sa windowIcon, windowIconText, windowModified, windowFilePath
5570 QString
QWidget::windowTitle() const
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
);
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
5593 QString
qt_setWindowTitle_helperHelper(const QString
&title
, const QWidget
*widget
)
5598 extern QString
qt_eval_adapt_window_title(const QString
&title
);
5599 QString cap
= qt_eval_adapt_window_title(title
);
5601 QString cap
= title
;
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
;
5616 while (cap
.indexOf(placeHolder
, index
) == index
) {
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("*"));
5627 cap
.remove(lastIndex
, 3);
5630 index
= cap
.indexOf(placeHolder
, index
);
5633 cap
.replace(QLatin1String("[*][*]"), placeHolder
);
5638 void QWidgetPrivate::setWindowTitle_helper(const QString
&title
)
5641 if (!q
->testAttribute(Qt::WA_WState_Created
))
5643 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title
, q
));
5646 void QWidgetPrivate::setWindowIconText_helper(const QString
&title
)
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
)
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
)
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;
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
)
5717 setAttribute(Qt::WA_SetWindowIcon
, !icon
.isNull());
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
5745 return (d
->extra
&& d
->extra
->topextra
) ? d
->extra
->topextra
->iconText
: QString();
5749 \property QWidget::windowFilePath
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
5761 \o The file name of the specified path, obtained using QFileInfo::fileName().
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.
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
5791 return (d
->extra
&& d
->extra
->topextra
) ? d
->extra
->topextra
->filePath
: QString();
5794 void QWidget::setWindowFilePath(const QString
&filePath
)
5796 if (filePath
== windowFilePath())
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()) {
5810 setWindowTitle_helper(QFileInfo(filePath
).fileName());
5814 setWindowTitle_helper(q
->windowTitle());
5818 setWindowFilePath_sys(filePath
);
5823 Returns the window's role, or an empty string.
5825 \sa windowIcon, windowTitle
5828 QString
QWidget::windowRole() const
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
5838 void QWidget::setWindowRole(const QString
&role
)
5840 #if defined(Q_WS_X11)
5842 d
->topData()->role
= role
;
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.
5879 void QWidget::setFocusProxy(QWidget
* w
)
5882 if (!w
&& !d
->extra
)
5885 for (QWidget
* fp
= w
; fp
; fp
= fp
->focusProxy()) {
5887 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5893 d
->extra
->focus_proxy
= w
;
5898 Returns the focus proxy, or 0 if there is no focus proxy.
5903 QWidget
* QWidget::focusProxy() const
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
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
)
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
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
5956 \warning If you call setFocus() in a function which may itself be
5957 called from focusOutEvent() or focusInEvent(), you may get an
5960 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5961 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5962 grabMouse(), {Keyboard Focus}
5965 void QWidget::setFocus(Qt::FocusReason reason
)
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()
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();
5994 while (w
&& w
->isHidden()) {
5995 w
->d_func()->focus_child
= f
;
5996 w
= w
->isWindow() ? 0 : w
->parentWidget();
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;
6016 if (f
->isActiveWindow()) {
6017 QApplicationPrivate::setFocusWidget(f
, reason
);
6018 #ifndef QT_NO_ACCESSIBILITY
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
6024 QAccessible::updateAccessibility(f
, 0, QAccessible::Focus
);
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
);
6035 QApplication::sendEvent(that
->style(), &event
);
6038 // Send event to self
6039 QFocusEvent
event(QEvent::FocusIn
, reason
);
6040 QPointer
<QWidget
> that
= f
;
6041 QApplication::sendEvent(f
, &event
);
6043 QApplication::sendEvent(that
->style(), &event
);
6052 \fn void QWidget::setFocus()
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
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()
6078 if (w
->d_func()->focus_child
== this)
6079 w
->d_func()->focus_child
= 0;
6080 w
= w
->parentWidget();
6082 #ifndef QT_NO_GRAPHICSVIEW
6083 QWExtra
*topData
= d_func()->extra
;
6084 if (topData
&& topData
->proxyWidget
)
6085 topData
->proxyWidget
->clearFocus();
6089 // Update proxy state
6090 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason
);
6091 #if defined(Q_WS_WIN)
6092 if (!(windowType() == Qt::Popup
) && GetFocus() == internalWinId())
6097 #ifndef QT_NO_ACCESSIBILITY
6098 QAccessible::updateAccessibility(this, 0, QAccessible::Focus
);
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
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
)
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
);
6158 QWidget
*w
= QApplicationPrivate::focusNextPrevChild_helper(this, next
);
6159 if (!w
) return false;
6161 w
->setFocus(next
? Qt::TabFocusReason
: Qt::BacktabFocusReason
);
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()
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
)))
6222 #ifndef QT_NO_GRAPHICSVIEW
6223 if (QWExtra
*tlwExtra
= tlw
->d_func()->extra
) {
6224 if (isVisible() && tlwExtra
->proxyWidget
)
6225 return tlwExtra
->proxyWidget
->isActiveWindow();
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())
6235 extern bool qt_mac_insideKeyWindow(const QWidget
*); //qwidget_mac.cpp
6236 if (QApplication::testAttribute(Qt::AA_MacPluginApplication
) && qt_mac_insideKeyWindow(tlw
))
6239 if(style()->styleHint(QStyle::SH_Widget_ShareActivation
, 0, this)) {
6240 if(tlw
->windowType() == Qt::Tool
&&
6242 (!tlw
->parentWidget() || tlw
->parentWidget()->isActiveWindow()))
6244 QWidget
*w
= QApplication::activeWindow();
6245 while(w
&& tlw
->windowType() == Qt::Tool
&&
6246 !w
->isModal() && w
->parentWidget()) {
6247 w
= w
->parentWidget()->window();
6252 #if defined(Q_WS_WIN32)
6253 HWND active
= GetActiveWindow();
6254 if (!tlw
->testAttribute(Qt::WA_WState_Created
))
6256 return active
== tlw
->internalWinId() || ::IsChild(active
, tlw
->internalWinId());
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
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
)
6284 if (first
->window() != second
->window()) {
6285 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6289 QWidget
*fp
= first
->focusProxy();
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()) {
6300 if (fp
->focusPolicy() != Qt::NoFocus
)
6308 if (QWidget
*sp
= second
->focusProxy())
6311 // QWidget *fp = first->d_func()->focus_prev;
6312 QWidget
*fn
= first
->d_func()->focus_next
;
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
);
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
6343 This function is called from QWidget::reparent() *after* the widget
6344 has been reparented.
6349 void QWidgetPrivate::reparentFocusWidgets(QWidget
* oldtlw
)
6352 if (oldtlw
== q
->window())
6353 return; // nothing to do
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.
6371 bool currentIsNew
= q
->isAncestorOf(w
);
6374 //prev was old -- append to new list
6375 n
->d_func()->focus_next
= w
;
6376 w
->d_func()->focus_prev
= n
;
6381 //prev was new -- append to old list, if there is one
6383 o
->d_func()->focus_next
= w
;
6384 w
->d_func()->focus_prev
= o
;
6386 // "create" the old list
6392 w
= w
->d_func()->focus_next
;
6393 prevWasNew
= currentIsNew
;
6396 //repair the old list:
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
;
6412 n
->d_func()->focus_next
= topLevel
;
6414 //repair the new list
6415 n
->d_func()->focus_next
= q
;
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
)
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();
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
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)
6465 This corresponds to move(QPoint(\a x, \a y)).
6468 void QWidget::move(const QPoint
&p
)
6471 setAttribute(Qt::WA_Moved
);
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();
6480 data
->crect
.moveTopLeft(p
); // no frame yet
6481 setAttribute(Qt::WA_PendingMoveEvent
);
6485 /*! \fn void QWidget::resize(int w, int h)
6488 This corresponds to resize(QSize(\a w, \a h)).
6491 void QWidget::resize(const QSize
&s
)
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();
6499 data
->crect
.setSize(s
.boundedTo(maximumSize()).expandedTo(minimumSize()));
6500 setAttribute(Qt::WA_PendingResizeEvent
);
6504 void QWidget::setGeometry(const QRect
&r
)
6507 setAttribute(Qt::WA_Resized
);
6508 setAttribute(Qt::WA_Moved
);
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();
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
);
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
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
6552 << qint32(QApplication::desktop()->screenNumber(this))
6553 << quint8(windowState() & Qt::WindowMaximized
)
6554 << quint8(windowState() & Qt::WindowFullScreen
);
6561 Restores the geometry and state top-level widgets stored in the
6562 byte array \a geometry. Returns true on success; otherwise
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
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)
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
)
6594 const quint16 currentMajorVersion
= 1;
6595 quint16 majorVersion
= 0;
6596 quint16 minorVersion
= 0;
6598 stream
>> majorVersion
>> minorVersion
;
6600 if (majorVersion
!= currentMajorVersion
)
6602 // (Allow all minor versions.)
6604 QRect restoredFrameGeometry
;
6605 QRect restoredNormalGeometry
;
6606 qint32 restoredScreenNumber
;
6610 stream
>> restoredFrameGeometry
6611 >> restoredNormalGeometry
6612 >> restoredScreenNumber
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
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.
6642 restoredFrameGeometry
.setHeight(qMin(restoredFrameGeometry
.height(), availableGeometry
.height()));
6643 restoredNormalGeometry
.setHeight(qMin(restoredNormalGeometry
.height(), availableGeometry
.height() - frameHeight
));
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();
6666 ws
|= Qt::WindowMaximized
;
6668 ws
|= Qt::WindowFullScreen
;
6670 d_func()->topData()->normalGeometry
= restoredNormalGeometry
;
6675 offset
= d_func()->topData()->fullScreenOffset
;
6677 setWindowState(windowState() & ~(Qt::WindowMaximized
| Qt::WindowFullScreen
));
6678 move(restoredFrameGeometry
.topLeft() + offset
);
6679 resize(restoredNormalGeometry
.size());
6684 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
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
)
6703 if (left
== d
->leftmargin
&& top
== d
->topmargin
6704 && right
== d
->rightmargin
&& bottom
== d
->bottommargin
)
6706 d
->leftmargin
= left
;
6708 d
->rightmargin
= right
;
6709 d
->bottommargin
= bottom
;
6711 if (QLayout
*l
=d
->layout
)
6712 l
->update(); //force activate; will do updateGeometry
6716 // ### Qt 5: compat, remove
6719 QResizeEvent
e(data
->crect
.size(), data
->crect
.size());
6720 QApplication::sendEvent(this, &e
);
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
6738 *left
= d
->leftmargin
;
6740 *top
= d
->topmargin
;
6742 *right
= d
->rightmargin
;
6744 *bottom
= d
->bottommargin
;
6748 Returns the area inside the widget's margins.
6750 \sa setContentsMargins(), getContentsMargins()
6752 QRect
QWidget::contentsRect() const
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
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
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
;
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
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.
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.
6866 void QWidget::setUpdatesEnabled(bool enable
)
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()
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()
6891 // polish if necessary
6893 if (!q
->testAttribute(Qt::WA_WState_Created
))
6894 createRecursively();
6895 q
->ensurePolished();
6899 QApplication::sendPostedEvents(q
, QEvent::ChildInserted
);
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
6910 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive
, bool disableUpdates
)
6914 disableUpdates
= disableUpdates
&& q
->updatesEnabled();
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);
6931 q
->setAttribute(Qt::WA_UpdatesDisabled
, false);
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())
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();
6961 child
->setAttribute(Qt::WA_WState_Visible
);
6963 // Do the same for all my children.
6964 childPrivate
->activateChildLayoutsRecursively();
6966 // We're not cheating anymore.
6968 child
->setAttribute(Qt::WA_WState_Visible
, false);
6972 void QWidgetPrivate::show_helper()
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);
6986 if (q
->parentWidget() && sendChildEvents
)
6987 QApplication::sendPostedEvents(q
->parentWidget(),
6988 QEvent::ChildInserted
);
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
) {
6998 if (q
->parentWidget() && q
->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange
))
6999 q
->setAttribute(Qt::WA_KeyboardFocusChange
);
7001 while (QApplication::activePopupWidget()) {
7002 if (!QApplication::activePopupWidget()->close())
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
) {
7018 ancestorProxy
->d_func()->embedSubWindow(q
);
7023 Q_UNUSED(isEmbedded
);
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
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
);
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
);
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
);
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
);
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
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()
7085 void QWidgetPrivate::hide_helper()
7089 bool isEmbedded
= false;
7090 #if !defined QT_NO_GRAPHICSVIEW
7091 isEmbedded
= q
->isWindow() && nearestGraphicsProxyWidget(q
->parentWidget()) != 0;
7093 Q_UNUSED(isEmbedded
);
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
7111 q
->setAttribute(Qt::WA_Mapped
, false);
7114 bool wasVisible
= q
->testAttribute(Qt::WA_WState_Visible
);
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
7128 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
7129 qApp
->d_func()->sendSyntheticEnterLeave(q
);
7132 QWidget
*fw
= QApplication::focusWidget();
7133 while (fw
&& !fw
->isWindow()) {
7135 q
->focusNextPrevChild(true);
7138 fw
= fw
->parentWidget();
7142 if (QWidgetBackingStore
*bs
= maybeBackingStore())
7143 bs
->removeDirtyWidget(q
);
7145 #ifndef QT_NO_ACCESSIBILITY
7147 QAccessible::updateAccessibility(q
, 0, QAccessible::ObjectHide
);
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:
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.
7175 void QWidget::setVisible(bool visible
)
7177 if (visible
) { // show
7178 if (testAttribute(Qt::WA_WState_ExplicitShowHide
) && !testAttribute(Qt::WA_WState_Hidden
))
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
))) {
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);
7204 bool wasResized
= testAttribute(Qt::WA_Resized
);
7205 Qt::WindowStates initialWindowState
= windowState();
7207 // polish if necessary
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);
7221 QApplication::sendPostedEvents(this, QEvent::ChildInserted
);
7223 // activate our layout before we and our children become visible
7225 d
->layout
->activate();
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())
7233 parent
= parent
->parentWidget();
7235 if (parent
&& !d
->getOpaqueRegion().isEmpty())
7236 parent
->d_func()->setDirtyOpaqueRegion();
7239 // adjust size if necessary
7241 && (isWindow() || !parentWidget()->d_func()->layout
)) {
7244 if (windowState() != initialWindowState
)
7245 setWindowState(initialWindowState
);
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
);
7260 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
7261 qApp
->d_func()->sendSyntheticEnterLeave(this);
7265 QEvent
showToParentEvent(QEvent::ShowToParent
);
7266 QApplication::sendEvent(this, &showToParentEvent
);
7268 if (testAttribute(Qt::WA_WState_ExplicitShowHide
) && testAttribute(Qt::WA_WState_Hidden
))
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
);
7280 if (QApplicationPrivate::hidden_focus_widget
== this)
7281 QApplicationPrivate::hidden_focus_widget
= 0;
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
))
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()
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
));
7334 || widget
->isWindow()
7335 || widget
->testAttribute(Qt::WA_WState_Hidden
))
7338 widget
->setAttribute(Qt::WA_Mapped
);
7339 widget
->d_func()->showChildren(true);
7341 QApplication::sendSpontaneousEvent(widget
, &e
);
7343 if (widget
->testAttribute(Qt::WA_WState_ExplicitShowHide
))
7344 widget
->d_func()->show_recursive();
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
))
7359 widget
->setAttribute(Qt::WA_Mapped
, false);
7361 widget
->setAttribute(Qt::WA_WState_Visible
, false);
7362 widget
->d_func()->hideChildren(spontaneous
);
7365 QApplication::sendSpontaneousEvent(widget
, &e
);
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
);
7378 #ifndef QT_NO_ACCESSIBILITY
7380 QAccessible::updateAccessibility(widget
, 0, QAccessible::ObjectHide
);
7385 bool QWidgetPrivate::close_helper(CloseMode mode
)
7387 if (data
.is_closing
)
7391 data
.is_closing
= 1;
7393 QPointer
<QWidget
> that
= q
;
7394 QPointer
<QWidget
> parentWidget
= q
->parentWidget();
7397 bool isMain
= (QApplicationPrivate::main_widget
== q
);
7399 bool quitOnClose
= q
->testAttribute(Qt::WA_QuitOnClose
);
7400 if (mode
!= CloseNoEvent
) {
7402 if (mode
== CloseWithSpontaneousEvent
)
7403 QApplication::sendSpontaneousEvent(q
, &e
);
7405 QApplication::sendEvent(q
, &e
);
7406 if (!that
.isNull() && !e
.isAccepted()) {
7407 data
.is_closing
= 0;
7412 if (!that
.isNull() && !q
->isHidden())
7417 QApplication::quit();
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
));
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;
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);
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
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
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
7541 const QWidget
* w
= this;
7542 while (!w
->isHidden()
7544 && w
->parentWidget()
7545 && w
->parentWidget() != ancestor
)
7546 w
= w
->parentWidget();
7547 return !w
->isHidden();
7552 Use visibleRegion() instead.
7554 QRect
QWidget::visibleRect() const
7556 return d_func()->clipRect();
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
7574 QRect clipRect
= d
->clipRect();
7575 if (clipRect
.isEmpty())
7577 QRegion
r(clipRect
);
7578 d
->subtractOpaqueChildren(r
, clipRect
);
7579 d
->subtractOpaqueSiblings(r
);
7581 const QWSWindowSurface
*surface
= static_cast<const QWSWindowSurface
*>(windowSurface());
7583 const QPoint offset
= mapTo(surface
->window(), QPoint());
7584 r
&= surface
->clipRegion().translated(-offset
);
7591 QSize
QWidgetPrivate::adjustedSize() const
7595 QSize s
= q
->sizeHint();
7597 if (q
->isWindow()) {
7598 Qt::Orientations exp
;
7600 if (layout
->hasHeightForWidth())
7601 s
.setHeight(layout
->totalHeightForWidth(s
.width()));
7602 exp
= layout
->expandingDirections();
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());
7616 QRect screen
= QApplication::desktop()->screenGeometry(q
->pos());
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()));
7622 s
.setWidth(qMin(s
.width(), screen
.width()*2/3));
7623 s
.setHeight(qMin(s
.height(), screen
.height()*2/3));
7625 if (QTLWExtra
*extra
= maybeTopData())
7626 extra
->sizeAdjusted
= true;
7630 QRect r
= q
->childrenRect(); // get children rectangle
7633 s
= r
.size() + QSize(2 * r
.x(), 2 * r
.y());
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
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()
7659 QSize s
= d
->adjustedSize();
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
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
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
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
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
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
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
7735 if (child
->isWindow())
7737 child
= child
->parentWidget();
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
);
7749 dwStyle
|= WS_DISABLED
;
7751 dwStyle
&= ~WS_DISABLED
;
7752 SetWindowLong(w
->winId(), GWL_STYLE
, dwStyle
);
7753 // we might need to repaint in some situations (eg. menu)
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
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
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
)
7795 // ignore mouse events when disabled
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
7817 switch (event
->type()) {
7818 case QEvent::MouseMove
:
7819 mouseMoveEvent((QMouseEvent
*)event
);
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.
7828 resetInputContext();
7830 mousePressEvent((QMouseEvent
*)event
);
7833 case QEvent::MouseButtonRelease
:
7834 mouseReleaseEvent((QMouseEvent
*)event
);
7837 case QEvent::MouseButtonDblClick
:
7838 mouseDoubleClickEvent((QMouseEvent
*)event
);
7840 #ifndef QT_NO_WHEELEVENT
7842 wheelEvent((QWheelEvent
*)event
);
7845 #ifndef QT_NO_TABLETEVENT
7846 case QEvent::TabletMove
:
7847 case QEvent::TabletPress
:
7848 case QEvent::TabletRelease
:
7849 tabletEvent((QTabletEvent
*)event
);
7857 case QEvent::KeyPress
: {
7858 QKeyEvent
*k
= (QKeyEvent
*)event
;
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);
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);
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);
7894 case QEvent::KeyRelease
:
7895 keyReleaseEvent((QKeyEvent
*)event
);
7897 case QEvent::ShortcutOverride
:
7900 case QEvent::InputMethod
:
7901 inputMethodEvent((QInputMethodEvent
*) event
);
7904 case QEvent::PolishRequest
:
7908 case QEvent::Polish
: {
7909 style()->polish(this);
7910 setAttribute(Qt::WA_WState_Polished
);
7911 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7913 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7914 d
->resolvePalette();
7916 if(d
->sendChildEvents
)
7917 QApplication::sendPostedEvents(this, QEvent::ChildInserted
);
7922 case QEvent::ApplicationWindowIconChange
:
7923 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon
)) {
7924 d
->setWindowIcon_sys();
7925 d
->setWindowIcon_helper();
7928 case QEvent::FocusIn
:
7929 d
->setSoftKeys_sys(softKeys());
7930 focusInEvent((QFocusEvent
*)event
);
7933 case QEvent::FocusOut
:
7934 focusOutEvent((QFocusEvent
*)event
);
7938 #ifndef QT_NO_STATUSTIP
7939 if (d
->statusTip
.size()) {
7940 QStatusTipEvent
tip(d
->statusTip
);
7941 QApplication::sendEvent(const_cast<QWidget
*>(this), &tip
);
7948 #ifndef QT_NO_STATUSTIP
7949 if (d
->statusTip
.size()) {
7951 QStatusTipEvent
tip(empty
);
7952 QApplication::sendEvent(const_cast<QWidget
*>(this), &tip
);
7958 case QEvent::HoverEnter
:
7959 case QEvent::HoverLeave
:
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
);
7971 moveEvent((QMoveEvent
*)event
);
7974 case QEvent::Resize
:
7975 resizeEvent((QResizeEvent
*)event
);
7979 closeEvent((QCloseEvent
*)event
);
7982 #ifndef QT_NO_CONTEXTMENU
7983 case QEvent::ContextMenu
:
7984 switch (data
->context_menu_policy
) {
7985 case Qt::PreventContextMenu
:
7987 case Qt::DefaultContextMenu
:
7988 contextMenuEvent(static_cast<QContextMenuEvent
*>(event
));
7990 case Qt::CustomContextMenu
:
7991 emit
customContextMenuRequested(static_cast<QContextMenuEvent
*>(event
)->pos());
7994 case Qt::ActionsContextMenu
:
7995 if (d
->actions
.count()) {
7996 QMenu::exec(d
->actions
, static_cast<QContextMenuEvent
*>(event
)->globalPos(),
8007 #endif // QT_NO_CONTEXTMENU
8009 #ifndef QT_NO_DRAGANDDROP
8011 dropEvent((QDropEvent
*) event
);
8014 case QEvent::DragEnter
:
8015 dragEnterEvent((QDragEnterEvent
*) event
);
8018 case QEvent::DragMove
:
8019 dragMoveEvent((QDragMoveEvent
*) event
);
8022 case QEvent::DragLeave
:
8023 dragLeaveEvent((QDragLeaveEvent
*) event
);
8028 showEvent((QShowEvent
*) event
);
8032 hideEvent((QHideEvent
*) event
);
8035 case QEvent::ShowWindowRequest
:
8040 case QEvent::ApplicationFontChange
:
8043 case QEvent::ApplicationPaletteChange
:
8044 if (!(windowType() == Qt::Desktop
))
8045 d
->resolvePalette();
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
:
8066 case QEvent::WindowActivate
:
8067 case QEvent::WindowDeactivate
: {
8069 windowActivationChange(event
->type() != QEvent::WindowActivate
);
8071 if (isVisible() && !palette().isEqual(QPalette::Active
, QPalette::Inactive
))
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());
8085 case QEvent::LanguageChange
:
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
);
8100 case QEvent::ApplicationLayoutDirectionChange
:
8101 d
->resolveLayoutDirection();
8104 case QEvent::LayoutDirectionChange
:
8106 d
->layout
->invalidate();
8110 case QEvent::UpdateRequest
:
8111 d
->syncBackingStore();
8113 case QEvent::UpdateLater
:
8114 update(static_cast<QUpdateLaterEvent
*>(event
)->region());
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
8129 QApplication::sendEvent(o
, event
);
8132 #if defined(Q_WS_WIN)
8133 setDisabledStyle(this, (event
->type() == QEvent::WindowBlocked
));
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);
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);
8152 case QEvent::QueryWhatsThis
:
8153 if (d
->whatsThis
.isEmpty())
8157 #ifndef QT_NO_ACCESSIBILITY
8158 case QEvent::AccessibilityDescription
:
8159 case QEvent::AccessibilityHelp
: {
8160 QAccessibleEvent
*ev
= static_cast<QAccessibleEvent
*>(event
);
8163 switch (ev
->type()) {
8164 #ifndef QT_NO_TOOLTIP
8165 case QEvent::AccessibilityDescription
:
8166 ev
->setValue(d
->toolTip
);
8169 #ifndef QT_NO_WHATSTHIS
8170 case QEvent::AccessibilityHelp
:
8171 ev
->setValue(d
->whatsThis
);
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;
8186 #ifndef QT_NO_ACTION
8187 case QEvent::ActionAdded
:
8188 case QEvent::ActionRemoved
:
8189 case QEvent::ActionChanged
:
8190 actionEvent((QActionEvent
*)event
);
8194 case QEvent::KeyboardLayoutChange
:
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
);
8208 case QEvent::MacGLWindowChange
:
8209 d
->needWindowChange
= false;
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())
8221 // fake a mouse event!
8222 QEvent::Type eventType
= QEvent::None
;
8223 switch (touchEvent
->type()) {
8224 case QEvent::TouchBegin
:
8225 eventType
= QEvent::MouseButtonPress
;
8227 case QEvent::TouchUpdate
:
8228 eventType
= QEvent::MouseMove
;
8230 case QEvent::TouchEnd
:
8231 eventType
= QEvent::MouseButtonRelease
;
8237 if (eventType
== QEvent::None
)
8240 QMouseEvent
mouseEvent(eventType
,
8241 touchPoint
.pos().toPoint(),
8242 touchPoint
.screenPos().toPoint(),
8245 touchEvent
->modifiers());
8246 (void) QApplication::sendEvent(this, &mouseEvent
);
8249 case QEvent::SymbianDeferredFocusChanged
: {
8251 d
->handleSymbianDeferredFocusChanged();
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();
8262 const char axis
= propName
.at(12);
8264 d
->extra
->customDpiX
= value
;
8265 else if (axis
== 'Y')
8266 d
->extra
->customDpiY
= value
;
8267 d
->updateFont(d
->data
.fnt
);
8273 return QObject::event(event
);
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
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
:
8299 #ifndef QT_NO_ACCESSIBILITY
8300 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged
);
8304 case QEvent::FontChange
:
8305 case QEvent::StyleChange
: {
8310 d
->layout
->invalidate();
8313 d
->data
.fstrut_dirty
= true;
8318 case QEvent::PaletteChange
:
8323 case QEvent::MacSizeChange
:
8326 case QEvent::ToolTipChange
:
8327 case QEvent::MouseTrackingChange
:
8328 qt_mac_update_mouseTracking(this);
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
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
)
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
8381 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8382 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8385 void QWidget::mousePressEvent(QMouseEvent
*event
)
8388 if ((windowType() == Qt::Popup
)) {
8391 while ((w
= QApplication::activePopupWidget()) && w
!= this){
8393 if (QApplication::activePopupWidget() == w
) // widget does not want to dissappear
8394 w
->hide(); // hide at least
8396 if (!rect().contains(event
->pos())){
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
)
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(),
8448 void QWidget::wheelEvent(QWheelEvent
*event
)
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(),
8469 void QWidget::tabletEvent(QTabletEvent
*event
)
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
) {
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
)
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()) {
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())
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
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
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:
8627 \o repaint() or update() was invoked,
8628 \o the widget was obscured and has now been uncovered, or
8629 \o many other reasons.
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
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(),
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
*)
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()}
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
)
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
)
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
8784 The default implementation calls event->ignore(), which rejects the
8785 Input Method event. See the \l QInputMethodEvent documentation for more
8788 \sa event(), QInputMethodEvent
8790 void QWidget::inputMethodEvent(QInputMethodEvent
*event
)
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
8808 case Qt::ImMicroFocus
:
8809 return QRect(width()/2, 0, 1, height());
8812 case Qt::ImAnchorPosition
:
8814 return inputMethodQuery(Qt::ImCursorPosition
);
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.
8839 \sa inputMethodQuery(), QInputContext
8841 Qt::InputMethodHints
QWidget::inputMethodHints() const
8847 void QWidget::setInputMethodHints(Qt::InputMethodHints 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();
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
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
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
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
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
8987 \note Events are only delivered to this event handler if the widget is
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
)
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
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
)
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
9067 \note Events are only delivered to this event handler if the widget is
9070 \warning This function is not portable.
9072 \sa QApplication::x11EventFilter(), QWidget::winId()
9074 bool QWidget::x11Event(XEvent
*)
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
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
*)
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)
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()).
9129 void QWidget::ensurePolished() const
9133 const QMetaObject
*m
= metaObject();
9134 if (m
== d
->polished
)
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())
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
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.
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
)
9212 qWarning("QWidget::setLayout: Cannot set layout to 0");
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());
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();
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());
9239 l
->d_func()->topLevel
= true;
9241 if (oldParent
!= this) {
9243 l
->d_func()->reparentChildWidgets(this);
9247 if (isWindow() && d
->maybeTopData())
9248 d
->topData()->sizeAdjusted
= false;
9252 \fn QLayout *QWidget::takeLayout()
9254 Remove the layout from the widget.
9258 QLayout
*QWidget::takeLayout()
9261 QLayout
*l
= layout();
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
9292 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9294 QSizePolicy
QWidget::sizePolicy() const
9297 return d
->size_policy
;
9300 void QWidget::setSizePolicy(QSizePolicy policy
)
9303 setAttribute(Qt::WA_WState_OwnSizePolicy
);
9304 if (policy
== d
->size_policy
)
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
);
9317 if (isWindow() && d
->maybeTopData())
9318 d
->topData()->sizeAdjusted
= false;
9322 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
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
);
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.
9358 Returns the visible child widget at point \a p in the widget's own
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
9371 bool includeFrame
= q
->isWindow() && qobject_cast
<const QMainWindow
*>(q
)
9372 && static_cast<const QMainWindow
*>(q
)->unifiedTitleAndToolBarOnMac();
9379 !q
->rect().contains(p
))
9382 for (int i
= children
.size(); i
> 0 ;) {
9384 QWidget
*w
= qobject_cast
<QWidget
*>(children
.at(i
));
9385 if (w
&& !w
->isWindow() && !w
->isHidden()
9386 && (w
->geometry().contains(p
)
9388 || (includeFrame
&& w
->geometry().contains(qt_mac_nativeMapFromParent(w
, p
)))
9391 if (ignoreChildrenInDestructor
&& w
->data
->in_destructor
)
9393 if (w
->testAttribute(Qt::WA_TransparentForMouseEvents
))
9395 QPoint childPoint
= w
->mapFromParent(p
);
9397 if (includeFrame
&& !w
->geometry().contains(p
))
9398 childPoint
= qt_mac_nativeMapFromParent(w
, p
);
9400 if (QWidget
*t
= w
->d_func()->childAt_helper(childPoint
, ignoreChildrenInDestructor
))
9402 // if WMouseNoMask is set the widget mask is ignored, if
9403 // the widget has no mask then the WMouseNoMask flag has no
9405 if (w
->testAttribute(Qt::WA_MouseNoMask
) || w
->mask().contains(childPoint
)
9406 || w
->mask().isEmpty())
9413 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate
)
9417 widgetItem
->invalidateSizeCache();
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()
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
)
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
9478 if (!((data
->window_flags
^ flags
) & Qt::Window
)
9479 && (visible
|| testAttribute(Qt::WA_Moved
))) {
9482 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9483 d
->adjustQuitOnCloseAttribute();
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
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.
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
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
9527 If the "new" parent widget is the old parent widget, this function
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())
9544 setParent((QWidget
*)parent
, windowFlags() & ~Qt::WindowType_Mask
);
9550 This function also takes widget flags, \a f as an argument.
9553 void QWidget::setParent(QWidget
*parent
, Qt::WindowFlags f
)
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
);
9575 if (!testAttribute(Qt::WA_WState_Hidden
)) {
9577 setAttribute(Qt::WA_WState_ExplicitShowHide
, false);
9580 QEvent
e(QEvent::ParentAboutToChange
);
9581 QApplication::sendEvent(this, &e
);
9584 if (newParent
&& isAncestorOf(focusWidget()))
9585 focusWidget()->clearFocus();
9587 d
->setParent_sys(parent
, f
);
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();
9597 oldBs
->subSurfaces
.removeAll(windowSurface
);
9600 QWidgetBackingStore
*newBs
= parent
->d_func()->maybeBackingStore();
9602 newBs
->subSurfaces
.append(windowSurface
);
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
))
9621 d
->reparentFocusWidgets(oldtlw
);
9622 setAttribute(Qt::WA_Resized
, resized
);
9623 if (!testAttribute(Qt::WA_StyleSheet
)
9624 && (!parent
|| !parent
->testAttribute(Qt::WA_StyleSheet
))) {
9626 d
->resolvePalette();
9628 d
->resolveLayoutDirection();
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
9636 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9637 || (f
& Qt::MSWindowsOwnDC
)
9640 // propagate enabled updates enabled state to non-windows
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);
9649 // send and post remaining QObject events
9650 if (parent
&& d
->sendChildEvents
) {
9651 QChildEvent
e(QEvent::ChildAdded
, this);
9652 QApplication::sendEvent(parent
, &e
);
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);
9663 //### already hidden above ---> must probably do something smart on the 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);
9669 // q->setAttribute(Qt::WA_WState_Hidden);
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
);
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);
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
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())
9729 if (dx
== 0 && dy
== 0)
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));
9745 d
->setDirtyOpaqueRegion();
9746 d
->scroll_sys(dx
, dy
);
9752 This version only scrolls \a r and does not move the children of
9755 If \a r is empty or invalid, the result is undefined.
9759 void QWidget::scroll(int dx
, int dy
, const QRect
&r
)
9762 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9764 if (dx
== 0 && dy
== 0)
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()));
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
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()
9806 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
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())
9818 w
= data
->crect
.width() - x
;
9820 h
= data
->crect
.height() - y
;
9822 repaint(QRect(x
, y
, w
, h
));
9827 This version repaints a rectangle \a rect inside the widget.
9829 void QWidget::repaint(const QRect
&rect
)
9833 if (testAttribute(Qt::WA_WState_ConfigPending
)) {
9838 if (!isVisible() || !updatesEnabled() || rect
.isEmpty())
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;
9849 d
->repaint_sys(rect
);
9856 This version repaints a region \a rgn inside the widget.
9858 void QWidget::repaint(const QRegion
&rgn
)
9862 if (testAttribute(Qt::WA_WState_ConfigPending
)) {
9867 if (!isVisible() || !updatesEnabled() || rgn
.isEmpty())
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;
9878 d
->repaint_sys(rgn
);
9883 Updates the widget unless updates are disabled or the widget is
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
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()
9905 /*! \fn void QWidget::update(int x, int y, int w, int h)
9908 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9915 This version updates a rectangle \a rect inside the widget.
9917 void QWidget::update(const QRect
&rect
)
9919 if (!isVisible() || !updatesEnabled() || rect
.isEmpty())
9922 if (testAttribute(Qt::WA_WState_InPaintEvent
)) {
9923 QApplication::postEvent(this, new QUpdateLaterEvent(rect
));
9927 if (hasBackingStoreSupport()) {
9928 QTLWExtra
*tlwExtra
= window()->d_func()->maybeTopData();
9929 if (tlwExtra
&& !tlwExtra
->inTopLevelResize
&& tlwExtra
->backingStore
)
9930 tlwExtra
->backingStore
->markDirty(rect
, this);
9932 d_func()->repaint_sys(rect
);
9939 This version repaints a region \a rgn inside the widget.
9941 void QWidget::update(const QRegion
&rgn
)
9943 if (!isVisible() || !updatesEnabled() || rgn
.isEmpty())
9946 if (testAttribute(Qt::WA_WState_InPaintEvent
)) {
9947 QApplication::postEvent(this, new QUpdateLaterEvent(rgn
));
9951 if (hasBackingStoreSupport()) {
9952 QTLWExtra
*tlwExtra
= window()->d_func()->maybeTopData();
9953 if (tlwExtra
&& !tlwExtra
->inTopLevelResize
&& tlwExtra
->backingStore
)
9954 tlwExtra
->backingStore
->markDirty(rgn
, this);
9956 d_func()->repaint_sys(rgn
);
9962 Clear the rectangle at point (\a x, \a y) of width \a w and height
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
))
9972 w
= data
->crect
.width() - x
;
9974 h
= data
->crect
.height() - y
;
9975 if (w
!= 0 && h
!= 0) {
9977 p
.eraseRect(QRect(x
, y
, w
, h
));
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
))
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
))
10004 QPainter
paint(this);
10005 paint
.drawText(x
, y
, str
);
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
)
10023 void QWidget::setIcon(const QPixmap
&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
)
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");
10058 if (attribute
== Qt::WA_PaintOnScreen
&& on
) {
10059 // see qwidget_win.cpp, ::paintEngine for details
10061 if (d
->noPaintOnScreen
)
10066 if (attribute
< int(8*sizeof(uint
))) {
10068 data
->widget_attributes
|= (1<<attribute
);
10070 data
->widget_attributes
&= ~(1<<attribute
);
10072 const int x
= attribute
- 8*sizeof(uint
);
10073 const int int_off
= x
/ (8*sizeof(uint
));
10075 d
->high_attributes
[int_off
] |= (1<<(x
-(int_off
*8*sizeof(uint
))));
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
);
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
);
10103 case Qt::WA_NoChildEventsForParent
:
10104 d
->sendChildEvents
= !on
;
10106 case Qt::WA_NoChildEventsFromChildren
:
10107 d
->receiveChildEvents
= !on
;
10109 case Qt::WA_MacBrushedMetal
:
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();
10116 case Qt::WA_MacShowFocusRect
:
10123 qt_mac_update_mouseTracking(this);
10126 case Qt::WA_MacAlwaysShowToolWindow
:
10128 d
->macUpdateHideOnSuspend();
10131 case Qt::WA_MacNormalSize
:
10132 case Qt::WA_MacSmallSize
:
10133 case Qt::WA_MacMiniSize
:
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
)
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();
10150 case Qt::WA_ShowModal
:
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();
10164 while (w
&& !w
->testAttribute(Qt::WA_GroupLeader
)) {
10165 w
= w
->parentWidget();
10169 data
->window_modality
= (w
&& w
->testAttribute(Qt::WA_GroupLeader
))
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()
10182 case Qt::WA_MouseTracking
: {
10183 QEvent
e(QEvent::MouseTrackingChange
);
10184 QApplication::sendEvent(this, &e
);
10186 case Qt::WA_NativeWindow
: {
10187 QInputContext
*ic
= 0;
10188 if (on
&& !internalWinId() && testAttribute(Qt::WA_InputMethodEnabled
) && hasFocus()) {
10189 ic
= d
->inputContext();
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
))
10197 if (ic
&& isEnabled())
10198 ic
->setFocusWidget(this);
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.
10208 setAttribute(Qt::WA_NativeWindow
);
10209 d
->enforceNativeChildren();
10213 case Qt::WA_OpaquePaintEvent
:
10214 d
->updateIsOpaque();
10216 case Qt::WA_NoSystemBackground
:
10217 d
->updateIsOpaque();
10219 case Qt::WA_UpdatesDisabled
:
10220 d
->updateSystemBackground();
10222 case Qt::WA_TransparentForMouseEvents
:
10224 d
->macUpdateIgnoreMouseEvents();
10227 case Qt::WA_InputMethodEnabled
: {
10228 QInputContext
*ic
= d
->ic
;
10229 if (!ic
&& (!on
|| hasFocus()))
10230 ic
= d
->inputContext();
10232 if (on
&& hasFocus() && ic
->focusWidget() != this && isEnabled()) {
10233 ic
->setFocusWidget(this);
10234 } else if (!on
&& ic
->focusWidget() == this) {
10236 ic
->setFocusWidget(0);
10241 case Qt::WA_WindowPropagation
:
10242 d
->resolvePalette();
10244 d
->resolveLocale();
10247 case Qt::WA_NoX11EventCompression
:
10250 d
->extra
->compress_events
= on
;
10252 case Qt::WA_X11OpenGLOverlay
:
10253 d
->updateIsOpaque();
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.
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());
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();
10294 case Qt::WA_StaticContents
:
10295 if (QWidgetBackingStore
*bs
= d
->maybeBackingStore()) {
10297 bs
->addStaticWidget(this);
10299 bs
->removeStaticWidget(this);
10302 case Qt::WA_TranslucentBackground
:
10304 setAttribute(Qt::WA_NoSystemBackground
);
10305 d
->updateIsTranslucent();
10309 case Qt::WA_AcceptTouchEvents
:
10310 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10312 d
->registerTouchWindow();
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.
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
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
)
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
);
10380 if (!testAttribute(Qt::WA_WState_Created
))
10384 #ifndef QT_NO_GRAPHICSVIEW
10385 if (QGraphicsProxyWidget
*proxy
= graphicsProxyWidget()) {
10386 // Avoid invalidating the cache if set.
10387 if (proxy
->cacheMode() == QGraphicsItem::NoCache
)
10389 else if (QGraphicsScene
*scene
= proxy
->scene())
10390 scene
->update(proxy
->sceneBoundingRect());
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
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
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
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
)
10430 setAttribute(Qt::WA_WindowModified
, mod
);
10433 if (!windowTitle().contains(QLatin1String("[*]")) && mod
)
10434 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10436 d
->setWindowTitle_helper(windowTitle());
10437 d
->setWindowIconText_helper(windowIconText());
10439 d
->setWindowModified_sys(mod
);
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
)
10470 QEvent
event(QEvent::ToolTipChange
);
10471 QApplication::sendEvent(this, &event
);
10474 QString
QWidget::toolTip() const
10476 Q_D(const QWidget
);
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
)
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
)
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
)
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
)
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
10596 \sa releaseShortcut() setShortcutEnabled()
10598 int QWidget::grabShortcut(const QKeySequence
&key
, Qt::ShortcutContext context
)
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
10620 \sa grabShortcut() setShortcutEnabled()
10622 void QWidget::releaseShortcut(int 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
)
10645 qApp
->d_func()->shortcutMap
.setShortcutEnabled(enable
, id
, this, 0);
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
)
10660 qApp
->d_func()->shortcutMap
.setShortcutAutoRepeat(enable
, id
, this, 0);
10662 #endif // QT_NO_SHORTCUT
10664 Updates the widget's micro focus.
10668 void QWidget::updateMicroFocus()
10670 #if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN))
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();
10679 #ifndef QT_NO_ACCESSIBILITY
10680 // ##### is this correct
10681 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged
);
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
);
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
10714 if (hdc
!= d
->hd
&& !ReleaseDC(winId(), hdc
))
10715 qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
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
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
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()
10751 QWidget
*p
= parentWidget();
10752 const int parentChildCount
= p
->d_func()->children
.size();
10753 if (parentChildCount
< 2)
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
))
10762 else if (from
== parentChildCount
- 1)
10765 QRegion
region(rect());
10766 d
->subtractOpaqueSiblings(region
);
10767 d
->invalidateBuffer(region
);
10769 if (testAttribute(Qt::WA_WState_Created
))
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()
10789 QWidget
*p
= parentWidget();
10790 const int parentChildCount
= p
->d_func()->children
.size();
10791 if (parentChildCount
< 2)
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.
10797 p
->d_func()->children
.move(from
, 0);
10798 if (!testAttribute(Qt::WA_WState_Created
) && p
->testAttribute(Qt::WA_WState_Created
))
10800 else if (from
== 0)
10803 if (testAttribute(Qt::WA_WState_Created
))
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
)
10821 QWidget
*p
= parentWidget();
10822 if (!w
|| isWindow() || p
!= w
->parentWidget() || this == w
)
10825 int from
= p
->d_func()->children
.indexOf(this);
10826 int to
= p
->d_func()->children
.indexOf(w
);
10827 Q_ASSERT(from
>= 0);
10831 // Do nothing if the widget is already in correct stacking order _and_ created.
10833 p
->d_func()->children
.move(from
, to
);
10834 if (!testAttribute(Qt::WA_WState_Created
) && p
->testAttribute(Qt::WA_WState_Created
))
10836 else if (from
== to
)
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
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.
10947 widget->setEraseColor(color);
10950 palette.setColor(widget->backgroundRole(), color);
10951 widget->setPalette(palette);
10956 \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
10958 Use the palette instead.
10961 widget->setErasePixmap(pixmap);
10964 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
10965 widget->setPalette(palette);
10970 \fn void QWidget::setPaletteForegroundColor(const QColor &color)
10972 Use the palette directly.
10975 widget->setPaletteForegroundColor(color);
10978 palette.setColor(widget->foregroundRole(), color);
10979 widget->setPalette(palette);
10984 \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
10986 Use the palette directly.
10989 widget->setPaletteBackgroundColor(color);
10992 palette.setColor(widget->backgroundRole(), color);
10993 widget->setPalette(palette);
10998 \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
11000 Use the palette directly.
11003 widget->setPaletteBackgroundPixmap(pixmap);
11006 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11007 widget->setPalette(palette);
11012 \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
11014 Use the palette instead.
11017 widget->setBackgroundPixmap(pixmap);
11020 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11021 widget->setPalette(palette);
11026 \fn void QWidget::setBackgroundColor(const QColor &color)
11028 Use the palette instead.
11031 widget->setBackgroundColor(color);
11034 palette.setColor(widget->backgroundRole(), color);
11035 widget->setPalette(palette);
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)
11076 \fn BackgroundOrigin QWidget::backgroundOrigin() const
11080 Always returns \c WindowOrigin.
11084 \fn QPoint QWidget::backgroundOffset() const
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
11195 Use isWindow() instead.
11199 \fn bool QWidget::isRightToLeft() const
11204 \fn bool QWidget::isLeftToRight() const
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.
11262 return widget->childAt(x, y, true);
11264 QWidget *child = widget->childAt(x, y, true);
11267 if (widget->rect().contains(x, y))
11273 \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
11276 Use the \l sizePolicy property and heightForWidth() function instead.
11280 \fn bool QWidget::isUpdatesEnabled() const
11283 Use the \l updatesEnabled property instead.
11287 \macro QWIDGETSIZE_MAX
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
11308 // ### Fix properly for 4.3
11311 && q
->testAttribute(Qt::WA_WState_Created
))
11312 const_cast<QWidgetPrivate
*>(this)->updateFrameStrut();
11314 return maybeTopData() ? maybeTopData()->frameStrut
: QRect();
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
11337 QTLWExtra
*topData
= d
->topData();
11338 if (topData
->windowSurface
== surface
)
11341 QWindowSurface
*oldSurface
= topData
->windowSurface
;
11342 delete topData
->windowSurface
;
11343 topData
->windowSurface
= surface
;
11345 QWidgetBackingStore
*bs
= d
->maybeBackingStore();
11349 if (isTopLevel()) {
11350 if (bs
->windowSurface
!= oldSurface
&& bs
->windowSurface
!= surface
)
11351 delete bs
->windowSurface
;
11352 bs
->windowSurface
= surface
;
11354 #ifdef Q_BACKINGSTORE_SUBSURFACES
11356 bs
->subSurfaces
.append(surface
);
11358 bs
->subSurfaces
.removeOne(oldSurface
);
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();
11384 QTLWExtra
*extra
= w
->d_func()->maybeTopData();
11385 if (extra
&& extra
->windowSurface
)
11386 return extra
->windowSurface
;
11387 if (w
->isTopLevel())
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
11400 *left
= (int)leftLayoutItemMargin
;
11402 *top
= (int)topLayoutItemMargin
;
11404 *right
= (int)rightLayoutItemMargin
;
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
)
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
)
11428 QStyleOption myOpt
;
11431 myOpt
.rect
.setRect(0, 0, 32768, 32768); // arbitrary
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());
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()
11453 if (!q
->parentWidget()) {
11454 Qt::WindowType type
= q
->windowType();
11455 if (type
== Qt::Widget
|| type
== Qt::SubWindow
)
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
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
);
11489 return d
->extra
->proxyWidget
;
11497 \typedef QWidgetList
11500 Synonym for QList<QWidget *>.
11505 #include "moc_qwidget.cpp"
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
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
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
11581 \sa releaseMouse() grabKeyboard() releaseKeyboard() grabKeyboard()
11586 \fn void QWidget::grabMouse(const QCursor &cursor)
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,
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
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()
11689 \a m is the metric to get.
11693 \fn void QWidget::setMask(const QRegion ®ion)
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
11706 void QWidget::setMask(const QRegion
&newMask
)
11711 if (newMask
== d
->extra
->mask
)
11714 #ifndef QT_NO_BACKINGSTORE
11715 const QRegion
oldMask(d
->extra
->mask
);
11718 d
->extra
->mask
= newMask
;
11719 d
->extra
->hasMask
= !newMask
.isEmpty();
11721 #ifndef QT_MAC_USE_COCOA
11722 if (!testAttribute(Qt::WA_WState_Created
))
11726 d
->setMask_sys(newMask
);
11728 #ifndef QT_NO_BACKINGSTORE
11732 if (!d
->extra
->hasMask
) {
11733 // Mask was cleared; update newly exposed area.
11734 QRegion
expose(rect());
11736 if (!expose
.isEmpty()) {
11737 d
->setDirtyOpaqueRegion();
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
);
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
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
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().
11797 void QWidget::clearMask()
11799 setMask(QRegion());
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();
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
11830 A QWidget can have 0 or more softkeys
11832 \sa softKeys(), setSoftKeys()
11834 void QWidget::setSoftKey(QAction
*softKey
)
11837 qDeleteAll(d
->softKeys
);
11838 d
->softKeys
.clear();
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
)
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
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.