Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindow.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qwindow.h"
6
7#include <qpa/qplatformwindow.h>
8#include <qpa/qplatformintegration.h>
9#ifndef QT_NO_CONTEXTMENU
10#include <qpa/qplatformtheme.h>
11#endif
12#include "qsurfaceformat.h"
13#ifndef QT_NO_OPENGL
14#include <qpa/qplatformopenglcontext.h>
15#include "qopenglcontext.h"
17#endif
18#include "qscreen.h"
19
20#include "qwindow_p.h"
22#if QT_CONFIG(accessibility)
23# include "qaccessible.h"
24# include <private/qaccessiblecache_p.h>
25#endif
27#if QT_CONFIG(draganddrop)
28#include "qshapedpixmapdndwindow_p.h"
29#endif // QT_CONFIG(draganddrop)
30
31#include <private/qevent_p.h>
32#include <private/qeventpoint_p.h>
33#include <private/qguiapplication_p.h>
34
35#include <QtCore/QTimer>
36#include <QtCore/QDebug>
37
38#include <QStyleHints>
39#include <qpa/qplatformcursor.h>
40#include <qpa/qplatformwindow_p.h>
41
43
44/*!
45 \class QWindow
46 \inmodule QtGui
47 \since 5.0
48 \brief The QWindow class represents a window in the underlying windowing system.
49
50 A window that is supplied a parent becomes a native child window of
51 their parent window.
52
53 An application will typically use QWidget or QQuickView for its UI, and not
54 QWindow directly. Still, it is possible to render directly to a QWindow
55 with QBackingStore or QOpenGLContext, when wanting to keep dependencies to
56 a minimum or when wanting to use OpenGL directly. The
57 \l{Raster Window Example} and \l{OpenGL Window Example}
58 are useful reference examples for how to render to a QWindow using
59 either approach.
60
61 \section1 Resource Management
62
63 Windows can potentially use a lot of memory. A usual measurement is
64 width times height times color depth. A window might also include multiple
65 buffers to support double and triple buffering, as well as depth and stencil
66 buffers. To release a window's memory resources, call the destroy() function.
67
68 \section1 Content Orientation
69
70 QWindow has reportContentOrientationChange() that can be used to specify
71 the layout of the window contents in relation to the screen. The content
72 orientation is simply a hint to the windowing system about which
73 orientation the window contents are in. It's useful when you wish to keep
74 the same window size, but rotate the contents instead, especially when
75 doing rotation animations between different orientations. The windowing
76 system might use this value to determine the layout of system popups or
77 dialogs.
78
79 \section1 Visibility and Windowing System Exposure
80
81 By default, the window is not visible, and you must call setVisible(true),
82 or show() or similar to make it visible. To make a window hidden again,
83 call setVisible(false) or hide(). The visible property describes the state
84 the application wants the window to be in. Depending on the underlying
85 system, a visible window might still not be shown on the screen. It could,
86 for instance, be covered by other opaque windows or moved outside the
87 physical area of the screen. On windowing systems that have exposure
88 notifications, the isExposed() accessor describes whether the window should
89 be treated as directly visible on screen. The exposeEvent() function is
90 called whenever an area of the window is invalidated, for example due to the
91 exposure in the windowing system changing. On windowing systems that do not
92 make this information visible to the application, isExposed() will simply
93 return the same value as isVisible().
94
95 QWindow::Visibility queried through visibility() is a convenience API
96 combining the functions of visible() and windowStates().
97
98 \section1 Rendering
99
100 There are two Qt APIs that can be used to render content into a window,
101 QBackingStore for rendering with a QPainter and flushing the contents
102 to a window with type QSurface::RasterSurface, and QOpenGLContext for
103 rendering with OpenGL to a window with type QSurface::OpenGLSurface.
104
105 The application can start rendering as soon as isExposed() returns \c true,
106 and can keep rendering until it isExposed() returns \c false. To find out when
107 isExposed() changes, reimplement exposeEvent(). The window will always get
108 a resize event before the first expose event.
109
110 \section1 Initial Geometry
111
112 If the window's width and height are left uninitialized, the window will
113 get a reasonable default geometry from the platform window. If the position
114 is left uninitialized, then the platform window will allow the windowing
115 system to position the window. For example on X11, the window manager
116 usually does some kind of smart positioning to try to avoid having new
117 windows completely obscure existing windows. However setGeometry()
118 initializes both the position and the size, so if you want a fixed size but
119 an automatic position, you should call resize() or setWidth() and
120 setHeight() instead.
121*/
122
123/*!
124 Creates a window as a top level on the \a targetScreen.
125
126 The window is not shown until setVisible(true), show(), or similar is called.
127
128 \sa setScreen()
129*/
130QWindow::QWindow(QScreen *targetScreen)
131 : QObject(*new QWindowPrivate(), nullptr)
132 , QSurface(QSurface::Window)
133{
134 Q_D(QWindow);
135 d->init(nullptr, targetScreen);
136}
137
138/*!
139 Creates a window as a child of the given \a parent window.
140
141 The window will be embedded inside the parent window, its coordinates
142 relative to the parent.
143
144 The screen is inherited from the parent.
145
146 \sa setParent()
147*/
148QWindow::QWindow(QWindow *parent)
149 : QWindow(*new QWindowPrivate(), parent)
150{
151}
152
153/*!
154 Creates a window as a child of the given \a parent window with the \a dd
155 private implementation.
156
157 The window will be embedded inside the parent window, its coordinates
158 relative to the parent.
159
160 The screen is inherited from the parent.
161
162 \internal
163 \sa setParent()
164*/
165QWindow::QWindow(QWindowPrivate &dd, QWindow *parent)
166 : QObject(dd, nullptr)
167 , QSurface(QSurface::Window)
168{
169 Q_D(QWindow);
170 d->init(parent);
171}
172
173/*!
174 Destroys the window.
175*/
176QWindow::~QWindow()
177{
178 Q_D(QWindow);
179
180#if QT_CONFIG(accessibility)
181 if (QGuiApplicationPrivate::is_app_running && !QGuiApplicationPrivate::is_app_closing && QAccessible::isActive())
182 QAccessibleCache::instance()->sendObjectDestroyedEvent(this);
183#endif
184
185 // Delete child windows up front, instead of waiting for ~QObject,
186 // in case the destruction of the child references its parent as
187 // a (no longer valid) QWindow.
188 qDeleteAll(findChildren<QWindow *>(Qt::FindDirectChildrenOnly));
189
190 d->destroy();
191 // Decouple from parent before window goes under
192 setParent(nullptr);
193 QGuiApplicationPrivate::window_list.removeAll(this);
194 QGuiApplicationPrivate::popup_list.removeAll(this);
195 if (!QGuiApplicationPrivate::is_app_closing)
196 QGuiApplicationPrivate::instance()->modalWindowList.removeOne(this);
197
198 // thse are normally cleared in destroy(), but the window may in
199 // some cases end up becoming the focus window again, or receive an enter
200 // event. Clear it again here as a workaround. See QTBUG-75326.
201 if (QGuiApplicationPrivate::focus_window == this)
202 QGuiApplicationPrivate::focus_window = nullptr;
203 if (QGuiApplicationPrivate::currentMouseWindow == this)
204 QGuiApplicationPrivate::currentMouseWindow = nullptr;
205 if (QGuiApplicationPrivate::currentMousePressWindow == this)
206 QGuiApplicationPrivate::currentMousePressWindow = nullptr;
207
208 d->isWindow = false;
209}
210
211QWindowPrivate::QWindowPrivate(decltype(QObjectPrivateVersion) version)
212 : QObjectPrivate(version)
213{}
214
215QWindowPrivate::~QWindowPrivate()
216 = default;
217
218void QWindowPrivate::init(QWindow *parent, QScreen *targetScreen)
219{
220 Q_Q(QWindow);
221
222 q->QObject::setParent(parent);
223
224 isWindow = true;
225 parentWindow = static_cast<QWindow *>(q->QObject::parent());
226
227 QScreen *connectScreen = targetScreen ? targetScreen : QGuiApplication::primaryScreen();
228
229 if (!parentWindow)
230 connectToScreen(connectScreen);
231
232 // If your application aborts here, you are probably creating a QWindow
233 // before the screen list is populated.
234 if (Q_UNLIKELY(!parentWindow && !topLevelScreen)) {
235 qFatal("Cannot create window: no screens available");
236 }
237 QGuiApplicationPrivate::window_list.prepend(q);
238
239 requestedFormat = QSurfaceFormat::defaultFormat();
240 devicePixelRatio = connectScreen->devicePixelRatio();
241
242 QObject::connect(q, &QWindow::screenChanged, q, [q, this](QScreen *){
243 // We may have changed scaling; trigger resize event if needed,
244 // except on Windows, where we send resize events during WM_DPICHANGED
245 // event handling. FIXME: unify DPI change handling across all platforms.
246#ifndef Q_OS_WIN
247 if (const auto *handle = q->handle()) {
248 QWindowSystemInterfacePrivate::GeometryChangeEvent gce(q,
249 QHighDpi::fromNativeWindowGeometry(handle->QPlatformWindow::geometry(), q),
250 QHighDpi::fromNativePixels(handle->geometry(), q));
251 QGuiApplicationPrivate::processGeometryChangeEvent(&gce);
252 }
253#else
254 Q_UNUSED(q);
255#endif
256 updateDevicePixelRatio();
257 });
258
259 if (parentWindow) {
260 QChildWindowEvent childAddedEvent(QEvent::ChildWindowAdded, q);
261 QCoreApplication::sendEvent(parentWindow, &childAddedEvent);
262 }
263}
264
265/*!
266 \enum QWindow::Visibility
267 \since 5.1
268
269 This enum describes what part of the screen the window occupies or should
270 occupy.
271
272 \value Windowed The window occupies part of the screen, but not necessarily
273 the entire screen. This state will occur only on windowing systems which
274 support showing multiple windows simultaneously. In this state it is
275 possible for the user to move and resize the window manually, if
276 WindowFlags permit it and if it is supported by the windowing system.
277
278 \value Minimized The window is reduced to an entry or icon on the task bar,
279 dock, task list or desktop, depending on how the windowing system handles
280 minimized windows.
281
282 \value Maximized The window occupies one entire screen, and the titlebar is
283 still visible. On most windowing systems this is the state achieved by
284 clicking the maximize button on the toolbar.
285
286 \value FullScreen The window occupies one entire screen, is not resizable,
287 and there is no titlebar. On some platforms which do not support showing
288 multiple simultaneous windows, this can be the usual visibility when the
289 window is not hidden.
290
291 \value AutomaticVisibility This means to give the window a default visible
292 state, which might be fullscreen or windowed depending on the platform.
293 It can be given as a parameter to setVisibility but will never be
294 read back from the visibility accessor.
295
296 \value Hidden The window is not visible in any way, however it may remember
297 a latent visibility which can be restored by setting AutomaticVisibility.
298*/
299
300/*!
301 \property QWindow::visibility
302 \brief the screen-occupation state of the window
303 \since 5.1
304
305 Visibility is whether the window should appear in the windowing system as
306 normal, minimized, maximized, fullscreen or hidden.
307
308 To set the visibility to AutomaticVisibility means to give the window
309 a default visible state, which might be fullscreen or windowed depending on
310 the platform.
311 When reading the visibility property you will always get the actual state,
312 never AutomaticVisibility.
313
314 The default value is Hidden.
315*/
316QWindow::Visibility QWindow::visibility() const
317{
318 Q_D(const QWindow);
319 return d->visibility;
320}
321
322void QWindow::setVisibility(Visibility v)
323{
324 switch (v) {
325 case Hidden:
326 hide();
327 break;
328 case AutomaticVisibility:
329 show();
330 break;
331 case Windowed:
332 showNormal();
333 break;
334 case Minimized:
335 showMinimized();
336 break;
337 case Maximized:
338 showMaximized();
339 break;
340 case FullScreen:
341 showFullScreen();
342 break;
343 default:
344 Q_ASSERT(false);
345 }
346}
347
348/*
349 Subclasses may override this function to run custom setVisible
350 logic. Subclasses that do so must call the base class implementation
351 at some point to make the native window visible, and must not
352 call QWindow::setVisble() since that will recurse back here.
353*/
354void QWindowPrivate::setVisible(bool visible)
355{
356 Q_Q(QWindow);
357
358 if (this->visible != visible) {
359 this->visible = visible;
360 emit q->visibleChanged(visible);
361 updateVisibility();
362 } else if (platformWindow) {
363 // Visibility hasn't changed, and the platform window is in sync
364 return;
365 }
366
367 if (!platformWindow) {
368 // If we have a parent window, but the parent hasn't been created yet, we
369 // can defer creation until the parent is created or we're re-parented.
370 if (parentWindow && !parentWindow->handle())
371 return;
372
373 // We only need to create the window if it's being shown
374 if (visible) {
375 // FIXME: At this point we've already updated the visible state of
376 // the QWindow, so if the platform layer reads the window state during
377 // creation, and reflects that in the native window, it will end up
378 // with a visible window. This may in turn result in resize or expose
379 // events from the platform before we have sent the show event below.
380 q->create();
381 }
382 }
383
384 if (visible) {
385 // remove posted quit events when showing a new window
386 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
387
388 if (q->type() == Qt::Window) {
389 QGuiApplicationPrivate *app_priv = QGuiApplicationPrivate::instance();
390 QString &firstWindowTitle = app_priv->firstWindowTitle;
391 if (!firstWindowTitle.isEmpty()) {
392 q->setTitle(firstWindowTitle);
393 firstWindowTitle = QString();
394 }
395 if (!app_priv->forcedWindowIcon.isNull())
396 q->setIcon(app_priv->forcedWindowIcon);
397
398 // Handling of the -qwindowgeometry, -geometry command line arguments
399 static bool geometryApplied = false;
400 if (!geometryApplied) {
401 geometryApplied = true;
402 QGuiApplicationPrivate::applyWindowGeometrySpecificationTo(q);
403 }
404 }
405
406 QShowEvent showEvent;
407 QGuiApplication::sendEvent(q, &showEvent);
408 }
409
410 if (q->isModal()) {
411 if (visible)
412 QGuiApplicationPrivate::showModalWindow(q);
413 else
414 QGuiApplicationPrivate::hideModalWindow(q);
415 // QShapedPixmapWindow is used on some platforms for showing a drag pixmap, so don't block
416 // input to this window as it is performing a drag - QTBUG-63846
417 } else if (visible && QGuiApplication::modalWindow()
418#if QT_CONFIG(draganddrop)
419 && !qobject_cast<QShapedPixmapWindow *>(q)
420#endif // QT_CONFIG(draganddrop)
421 ) {
422 QGuiApplicationPrivate::updateBlockedStatus(q);
423 }
424
425 if (q->type() == Qt::Popup) {
426 if (visible)
427 QGuiApplicationPrivate::activatePopup(q);
428 else
429 QGuiApplicationPrivate::closePopup(q);
430 }
431
432#ifndef QT_NO_CURSOR
433 if (visible && (hasCursor || QGuiApplication::overrideCursor()))
434 applyCursor();
435#endif
436
437 if (platformWindow)
438 platformWindow->setVisible(visible);
439
440 if (!visible) {
441 QHideEvent hideEvent;
442 QGuiApplication::sendEvent(q, &hideEvent);
443 }
444}
445
446void QWindowPrivate::updateVisibility()
447{
448 Q_Q(QWindow);
449
450 QWindow::Visibility old = visibility;
451
452 if (!visible)
453 visibility = QWindow::Hidden;
454 else if (windowState & Qt::WindowMinimized)
455 visibility = QWindow::Minimized;
456 else if (windowState & Qt::WindowFullScreen)
457 visibility = QWindow::FullScreen;
458 else if (windowState & Qt::WindowMaximized)
459 visibility = QWindow::Maximized;
460 else
461 visibility = QWindow::Windowed;
462
463 if (visibility != old)
464 emit q->visibilityChanged(visibility);
465}
466
467void QWindowPrivate::updateSiblingPosition(SiblingPosition position)
468{
469 Q_Q(QWindow);
470
471 if (!q->parent())
472 return;
473
474 QObjectList &siblings = q->parent()->d_ptr->children;
475
476 const qsizetype siblingCount = siblings.size() - 1;
477 if (siblingCount == 0)
478 return;
479
480 const qsizetype currentPosition = siblings.indexOf(q);
481 Q_ASSERT(currentPosition >= 0);
482
483 const qsizetype targetPosition = position == PositionTop ? siblingCount : 0;
484
485 if (currentPosition == targetPosition)
486 return;
487
488 siblings.move(currentPosition, targetPosition);
489}
490
491bool QWindowPrivate::windowRecreationRequired(QScreen *newScreen) const
492{
493 Q_Q(const QWindow);
494 const QScreen *oldScreen = q->screen();
495 return oldScreen != newScreen && (platformWindow || !oldScreen)
496 && !(oldScreen && oldScreen->virtualSiblings().contains(newScreen));
497}
498
499void QWindowPrivate::disconnectFromScreen()
500{
501 if (topLevelScreen)
502 topLevelScreen = nullptr;
503}
504
505void QWindowPrivate::connectToScreen(QScreen *screen)
506{
507 disconnectFromScreen();
508 topLevelScreen = screen;
509}
510
511void QWindowPrivate::emitScreenChangedRecursion(QScreen *newScreen)
512{
513 Q_Q(QWindow);
514 emit q->screenChanged(newScreen);
515 for (QObject *child : q->children()) {
516 if (child->isWindowType())
517 static_cast<QWindow *>(child)->d_func()->emitScreenChangedRecursion(newScreen);
518 }
519}
520
521void QWindowPrivate::setTopLevelScreen(QScreen *newScreen, bool recreate)
522{
523 Q_Q(QWindow);
524
525 if (parentWindow) {
526 qWarning() << q << '(' << newScreen << "): Attempt to set a screen on a child window.";
527 return;
528 }
529 if (newScreen != topLevelScreen) {
530 const bool shouldRecreate = recreate && windowRecreationRequired(newScreen);
531 const bool shouldShow = visibilityOnDestroy && !topLevelScreen;
532 if (shouldRecreate && platformWindow)
533 q->destroy();
534 connectToScreen(newScreen);
535 if (shouldShow)
536 q->setVisible(true);
537 else if (newScreen && shouldRecreate)
538 create(true);
539 emitScreenChangedRecursion(newScreen);
540 }
541}
542
543static constexpr auto kForeignWindowId = "_q_foreignWinId";
544
545void QWindowPrivate::create(bool recursive)
546{
547 Q_Q(QWindow);
548 if (platformWindow)
549 return;
550
551 // avoid losing update requests when re-creating
552 const bool needsUpdate = updateRequestPending;
553 // the platformWindow, if there was one, is now gone, so make this flag reflect reality now
554 updateRequestPending = false;
555
556 if (q->parent())
557 q->parent()->create();
558
559 if (platformWindow) {
560 // Creating the parent window will end up creating any child window
561 // that was already visible, via setVisible. If this applies to us,
562 // we will already have a platform window at this point.
563 return;
564 }
565
566 // QPlatformWindow will poll geometry() during construction below. Set the
567 // screen here so that high-dpi scaling will use the correct scale factor.
568 if (q->isTopLevel()) {
569 if (QScreen *screen = screenForGeometry(geometry))
570 setTopLevelScreen(screen, false);
571 }
572
573 const WId nativeHandle = q->property(kForeignWindowId).value<WId>();
574
575 QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration();
576 platformWindow = nativeHandle ? platformIntegration->createForeignWindow(q, nativeHandle)
577 : platformIntegration->createPlatformWindow(q);
578 Q_ASSERT(platformWindow);
579
580 if (!platformWindow) {
581 qWarning() << "Failed to create platform window for" << q << "with flags" << q->flags();
582 return;
583 }
584
585 platformWindow->initialize();
586
587 QObjectList childObjects = q->children();
588 for (int i = 0; i < childObjects.size(); i ++) {
589 QObject *object = childObjects.at(i);
590 if (!object->isWindowType())
591 continue;
592
593 QWindow *childWindow = static_cast<QWindow *>(object);
594 if (recursive)
595 childWindow->d_func()->create(recursive);
596
597 // The child may have had deferred creation due to this window not being created
598 // at the time setVisible was called, so we re-apply the visible state, which
599 // may result in creating the child, and emitting the appropriate signals.
600 if (childWindow->isVisible())
601 childWindow->setVisible(true);
602
603 if (QPlatformWindow *childPlatformWindow = childWindow->d_func()->platformWindow)
604 childPlatformWindow->setParent(this->platformWindow);
605 }
606
607 QPlatformSurfaceEvent e(QPlatformSurfaceEvent::SurfaceCreated);
608 QGuiApplication::sendEvent(q, &e);
609
610 updateDevicePixelRatio();
611
612 if (needsUpdate)
613 q->requestUpdate();
614}
615
616void QWindowPrivate::clearFocusObject()
617{
618}
619
620// Allows for manipulating the suggested geometry before a resize/move
621// event in derived classes for platforms that support it, for example to
622// implement heightForWidth().
623QRectF QWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
624{
625 Q_UNUSED(rect);
626 return QRectF();
627}
628
629void QWindowPrivate::setMinOrMaxSize(QSize *oldSizeMember, const QSize &size,
630 qxp::function_ref<void()> funcWidthChanged,
631 qxp::function_ref<void()> funcHeightChanged)
632{
633 Q_Q(QWindow);
634 Q_ASSERT(oldSizeMember);
635 const QSize adjustedSize =
636 size.expandedTo(QSize(0, 0)).boundedTo(QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX));
637 if (*oldSizeMember == adjustedSize)
638 return;
639 const bool widthChanged = adjustedSize.width() != oldSizeMember->width();
640 const bool heightChanged = adjustedSize.height() != oldSizeMember->height();
641 *oldSizeMember = adjustedSize;
642
643 if (platformWindow && q->isTopLevel())
644 platformWindow->propagateSizeHints();
645
646 if (widthChanged)
647 funcWidthChanged();
648 if (heightChanged)
649 funcHeightChanged();
650
651 // resize window if current size is outside of min and max limits
652 if (minimumSize.width() <= maximumSize.width()
653 || minimumSize.height() <= maximumSize.height()) {
654 const QSize currentSize = q->size();
655 const QSize boundedSize = currentSize.expandedTo(minimumSize).boundedTo(maximumSize);
656 q->resize(boundedSize);
657 }
658}
659
660/*!
661 Sets the \a surfaceType of the window.
662
663 Specifies whether the window is meant for raster rendering with
664 QBackingStore, or OpenGL rendering with QOpenGLContext.
665
666 The surfaceType will be used when the native surface is created
667 in the create() function. Calling this function after the native
668 surface has been created requires calling destroy() and create()
669 to release the old native surface and create a new one.
670
671 \sa QBackingStore, QOpenGLContext, create(), destroy()
672*/
673void QWindow::setSurfaceType(SurfaceType surfaceType)
674{
675 Q_D(QWindow);
676 d->surfaceType = surfaceType;
677}
678
679/*!
680 Returns the surface type of the window.
681
682 \sa setSurfaceType()
683*/
684QWindow::SurfaceType QWindow::surfaceType() const
685{
686 Q_D(const QWindow);
687 return d->surfaceType;
688}
689
690/*!
691 \property QWindow::visible
692 \brief whether the window is visible or not
693
694 This property controls the visibility of the window in the windowing system.
695
696 By default, the window is not visible, you must call setVisible(true), or
697 show() or similar to make it visible.
698
699 \note Hiding a window does not remove the window from the windowing system,
700 it only hides it. On windowing systems that give full screen applications a
701 dedicated desktop (such as macOS), hiding a full screen window will not remove
702 that desktop, but leave it blank. Another window from the same application
703 might be shown full screen, and will fill that desktop. Use QWindow::close to
704 completely remove a window from the windowing system.
705
706 \sa show()
707*/
708void QWindow::setVisible(bool visible)
709{
710 Q_D(QWindow);
711
712 d->setVisible(visible);
713}
714
715bool QWindow::isVisible() const
716{
717 Q_D(const QWindow);
718
719 return d->visible;
720}
721
722/*!
723 Allocates the platform resources associated with the window.
724
725 It is at this point that the surface format set using setFormat() gets resolved
726 into an actual native surface. However, the window remains hidden until setVisible() is called.
727
728 Note that it is not usually necessary to call this function directly, as it will be implicitly
729 called by show(), setVisible(), winId(), and other functions that require access to the platform
730 resources.
731
732 Call destroy() to free the platform resources if necessary.
733
734 \sa destroy()
735*/
736void QWindow::create()
737{
738 Q_D(QWindow);
739 d->create(false);
740}
741
742/*!
743 Returns the window's platform id.
744
745 \note This function will cause the platform window to be created if it is not already.
746 Returns 0, if the platform window creation failed.
747
748 For platforms where this id might be useful, the value returned
749 will uniquely represent the window inside the corresponding screen.
750
751 \sa screen()
752*/
753WId QWindow::winId() const
754{
755 Q_D(const QWindow);
756
757 if (!d->platformWindow)
758 const_cast<QWindow *>(this)->create();
759
760 if (!d->platformWindow)
761 return 0;
762
763 return d->platformWindow->winId();
764}
765
766 /*!
767 Returns the parent window, if any.
768
769 If \a mode is IncludeTransients, then the transient parent is returned
770 if there is no parent.
771
772 A window without a parent is known as a top level window.
773
774 \since 5.9
775*/
776QWindow *QWindow::parent(AncestorMode mode) const
777{
778 Q_D(const QWindow);
779 return d->parentWindow ? d->parentWindow : (mode == IncludeTransients ? transientParent() : nullptr);
780}
781
782/*!
783 Sets the \a parent Window. This will lead to the windowing system managing
784 the clip of the window, so it will be clipped to the \a parent window.
785
786 Setting \a parent to be \nullptr will make the window become a top level
787 window.
788
789 If \a parent is a window created by fromWinId(), then the current window
790 will be embedded inside \a parent, if the platform supports it.
791*/
792void QWindow::setParent(QWindow *parent)
793{
794 Q_D(QWindow);
795 if (d->parentWindow == parent
796 // Allow explicit reparenting to top level for embedded windows
797 && !(d->platformWindow && d->platformWindow->isEmbedded())) {
798 return;
799 }
800
801 QScreen *oldScreen = screen();
802 QScreen *newScreen = parent ? parent->screen() : oldScreen;
803 if (d->windowRecreationRequired(newScreen)) {
804 qWarning() << this << '(' << parent << "): Cannot change screens (" << oldScreen << newScreen << ')';
805 return;
806 }
807
808 QEvent parentAboutToChangeEvent(QEvent::ParentWindowAboutToChange);
809 QCoreApplication::sendEvent(this, &parentAboutToChangeEvent);
810
811 const auto previousParent = d->parentWindow;
812 QObject::setParent(parent);
813 d->parentWindow = parent;
814
815 if (parent)
816 d->disconnectFromScreen();
817 else
818 d->connectToScreen(newScreen);
819
820 // If we were set visible, but not created because we were a child, and we're now
821 // re-parented into a created parent, or to being a top level, we need re-apply the
822 // visibility state, which will also create.
823 if (isVisible() && (!parent || parent->handle()))
824 setVisible(true);
825
826 if (d->platformWindow) {
827 if (parent)
828 parent->create();
829
830 d->platformWindow->setParent(parent ? parent->d_func()->platformWindow : nullptr);
831 }
832
833 QGuiApplicationPrivate::updateBlockedStatus(this);
834
835 if (previousParent) {
836 QChildWindowEvent childRemovedEvent(QEvent::ChildWindowRemoved, this);
837 QCoreApplication::sendEvent(previousParent, &childRemovedEvent);
838 }
839
840 if (parent) {
841 QChildWindowEvent childAddedEvent(QEvent::ChildWindowAdded, this);
842 QCoreApplication::sendEvent(parent, &childAddedEvent);
843 }
844
845 QEvent parentChangedEvent(QEvent::ParentWindowChange);
846 QCoreApplication::sendEvent(this, &parentChangedEvent);
847
848#if QT_CONFIG(accessibility)
849 if (!d->accessibleParent
850 && QGuiApplicationPrivate::is_app_running && !QGuiApplicationPrivate::is_app_closing) {
851 QAccessibleEvent qaEvent(this, QAccessible::ParentChanged);
852 QAccessible::updateAccessibility(&qaEvent);
853 }
854#endif
855
856 // The QPA layer should detect screen changes for child windows, and emit
857 // QWSI::handleWindowScreenChanged, but due to the ordering above where the
858 // parentWindow member is updated before calling setParent on the platform
859 // window we'll end up treating those callbacks from the QPA layer as noops
860 // in processWindowScreenChangedEvent since the screen is already up to date.
861 // To work around this we emit an explicit update here.
862 if (parent && screen() != oldScreen)
863 d->emitScreenChangedRecursion(screen());
864}
865
866/*!
867 Returns whether the window is top level, i.e. has no parent window.
868*/
869bool QWindow::isTopLevel() const
870{
871 Q_D(const QWindow);
872 return d->parentWindow == nullptr;
873}
874
875/*!
876 Returns whether the window is modal.
877
878 A modal window prevents other windows from getting any input.
879
880 \sa QWindow::modality
881*/
882bool QWindow::isModal() const
883{
884 Q_D(const QWindow);
885 return d->modality != Qt::NonModal;
886}
887
888/*! \property QWindow::modality
889 \brief the modality of the window
890
891 A modal window prevents other windows from receiving input events. Qt
892 supports two types of modality: Qt::WindowModal and Qt::ApplicationModal.
893
894 By default, this property is Qt::NonModal
895
896 \sa Qt::WindowModality
897*/
898
899Qt::WindowModality QWindow::modality() const
900{
901 Q_D(const QWindow);
902 return d->modality;
903}
904
905void QWindow::setModality(Qt::WindowModality modality)
906{
907 Q_D(QWindow);
908 if (d->modality == modality)
909 return;
910 d->modality = modality;
911 emit modalityChanged(modality);
912}
913
914/*! \fn void QWindow::modalityChanged(Qt::WindowModality modality)
915
916 This signal is emitted when the Qwindow::modality property changes to \a modality.
917*/
918
919/*!
920 Sets the window's surface \a format.
921
922 The format determines properties such as color depth, alpha, depth and
923 stencil buffer size, etc. For example, to give a window a transparent
924 background (provided that the window system supports compositing, and
925 provided that other content in the window does not make it opaque again):
926
927 \code
928 QSurfaceFormat format;
929 format.setAlphaBufferSize(8);
930 window.setFormat(format);
931 \endcode
932
933 The surface format will be resolved in the create() function. Calling
934 this function after create() has been called will not re-resolve the
935 surface format of the native surface.
936
937 When the format is not explicitly set via this function, the format returned
938 by QSurfaceFormat::defaultFormat() will be used. This means that when having
939 multiple windows, individual calls to this function can be replaced by one
940 single call to QSurfaceFormat::setDefaultFormat() before creating the first
941 window.
942
943 \sa create(), destroy(), QSurfaceFormat::setDefaultFormat()
944*/
945void QWindow::setFormat(const QSurfaceFormat &format)
946{
947 Q_D(QWindow);
948 d->requestedFormat = format;
949}
950
951/*!
952 Returns the requested surface format of this window.
953
954 If the requested format was not supported by the platform implementation,
955 the requestedFormat will differ from the actual window format.
956
957 This is the value set with setFormat().
958
959 \sa setFormat(), format()
960 */
961QSurfaceFormat QWindow::requestedFormat() const
962{
963 Q_D(const QWindow);
964 return d->requestedFormat;
965}
966
967/*!
968 Returns the actual format of this window.
969
970 After the window has been created, this function will return the actual surface format
971 of the window. It might differ from the requested format if the requested format could
972 not be fulfilled by the platform. It might also be a superset, for example certain
973 buffer sizes may be larger than requested.
974
975 \note Depending on the platform, certain values in this surface format may still
976 contain the requested values, that is, the values that have been passed to
977 setFormat(). Typical examples are the OpenGL version, profile and options. These may
978 not get updated during create() since these are context specific and a single window
979 may be used together with multiple contexts over its lifetime. Use the
980 QOpenGLContext's format() instead to query such values.
981
982 \sa create(), requestedFormat(), QOpenGLContext::format()
983*/
984QSurfaceFormat QWindow::format() const
985{
986 Q_D(const QWindow);
987 if (d->platformWindow)
988 return d->platformWindow->format();
989 return d->requestedFormat;
990}
991
992/*!
993 \property QWindow::flags
994 \brief the window flags of the window
995
996 The window flags control the window's appearance in the windowing system,
997 whether it's a dialog, popup, or a regular window, and whether it should
998 have a title bar, etc.
999
1000 The actual window flags might differ from the flags set with setFlags()
1001 if the requested flags could not be fulfilled.
1002
1003 \sa setFlag()
1004*/
1005void QWindow::setFlags(Qt::WindowFlags flags)
1006{
1007 Q_D(QWindow);
1008 if (d->windowFlags == flags)
1009 return;
1010
1011 if (d->platformWindow)
1012 d->platformWindow->setWindowFlags(flags);
1013
1014 d->windowFlags = flags;
1015
1016 emit flagsChanged(this->flags());
1017}
1018
1019Qt::WindowFlags QWindow::flags() const
1020{
1021 Q_D(const QWindow);
1022 Qt::WindowFlags flags = d->windowFlags;
1023
1024 if (d->platformWindow && d->platformWindow->isForeignWindow())
1025 flags |= Qt::ForeignWindow;
1026
1027 return flags;
1028}
1029
1030/*!
1031 \since 5.9
1032
1033 Sets the window flag \a flag on this window if \a on is true;
1034 otherwise clears the flag.
1035
1036 \sa setFlags(), flags(), type()
1037*/
1038void QWindow::setFlag(Qt::WindowType flag, bool on)
1039{
1040 Q_D(QWindow);
1041 if (on)
1042 setFlags(d->windowFlags | flag);
1043 else
1044 setFlags(d->windowFlags & ~flag);
1045}
1046
1047/*!
1048 Returns the type of the window.
1049
1050 This returns the part of the window flags that represents
1051 whether the window is a dialog, tooltip, popup, regular window, etc.
1052
1053 \sa flags(), setFlags()
1054*/
1055Qt::WindowType QWindow::type() const
1056{
1057 return static_cast<Qt::WindowType>(int(flags() & Qt::WindowType_Mask));
1058}
1059
1060/*!
1061 \property QWindow::title
1062 \brief the window's title in the windowing system
1063
1064 The window title might appear in the title area of the window decorations,
1065 depending on the windowing system and the window flags. It might also
1066 be used by the windowing system to identify the window in other contexts,
1067 such as in the task switcher.
1068
1069 \sa flags()
1070*/
1071void QWindow::setTitle(const QString &title)
1072{
1073 Q_D(QWindow);
1074 bool changed = false;
1075 if (d->windowTitle != title) {
1076 d->windowTitle = title;
1077 changed = true;
1078 }
1079 if (d->platformWindow)
1080 d->platformWindow->setWindowTitle(title);
1081 if (changed)
1082 emit windowTitleChanged(title);
1083}
1084
1085QString QWindow::title() const
1086{
1087 Q_D(const QWindow);
1088 return d->windowTitle;
1089}
1090
1091/*!
1092 \brief set the file name this window is representing.
1093
1094 The windowing system might use \a filePath to display the
1095 path of the document this window is representing in the tile bar.
1096
1097*/
1098void QWindow::setFilePath(const QString &filePath)
1099{
1100 Q_D(QWindow);
1101 d->windowFilePath = filePath;
1102 if (d->platformWindow)
1103 d->platformWindow->setWindowFilePath(filePath);
1104}
1105
1106/*!
1107 \brief the file name this window is representing.
1108
1109 \sa setFilePath()
1110*/
1111QString QWindow::filePath() const
1112{
1113 Q_D(const QWindow);
1114 return d->windowFilePath;
1115}
1116
1117/*!
1118 \brief Sets the window's \a icon in the windowing system
1119
1120 The window icon might be used by the windowing system for example to
1121 decorate the window, and/or in the task switcher.
1122
1123 \note On \macos, the window title bar icon is meant for windows representing
1124 documents, and will only show up if a file path is also set.
1125
1126 \sa setFilePath()
1127*/
1128void QWindow::setIcon(const QIcon &icon)
1129{
1130 Q_D(QWindow);
1131 d->windowIcon = icon;
1132 if (d->platformWindow)
1133 d->platformWindow->setWindowIcon(icon);
1134 QEvent e(QEvent::WindowIconChange);
1135 QCoreApplication::sendEvent(this, &e);
1136}
1137
1138/*!
1139 \brief Returns the window's icon in the windowing system
1140
1141 \sa setIcon()
1142*/
1143QIcon QWindow::icon() const
1144{
1145 Q_D(const QWindow);
1146 if (d->windowIcon.isNull())
1147 return QGuiApplication::windowIcon();
1148 return d->windowIcon;
1149}
1150
1151/*!
1152 Raise the window in the windowing system.
1153
1154 Requests that the window be raised to appear above other windows.
1155*/
1156void QWindow::raise()
1157{
1158 Q_D(QWindow);
1159
1160 d->updateSiblingPosition(QWindowPrivate::PositionTop);
1161
1162 if (d->platformWindow)
1163 d->platformWindow->raise();
1164}
1165
1166/*!
1167 Lower the window in the windowing system.
1168
1169 Requests that the window be lowered to appear below other windows.
1170*/
1171void QWindow::lower()
1172{
1173 Q_D(QWindow);
1174
1175 d->updateSiblingPosition(QWindowPrivate::PositionBottom);
1176
1177 if (d->platformWindow)
1178 d->platformWindow->lower();
1179}
1180
1181/*!
1182 \brief Start a system-specific resize operation
1183 \since 5.15
1184
1185 Calling this will start an interactive resize operation on the window by platforms
1186 that support it. The actual behavior may vary depending on the platform. Usually,
1187 it will make the window resize so that its edge follows the mouse cursor.
1188
1189 On platforms that support it, this method of resizing windows is preferred over
1190 \c setGeometry, because it allows a more native look and feel of resizing windows, e.g.
1191 letting the window manager snap this window against other windows, or special resizing
1192 behavior with animations when dragged to the edge of the screen.
1193
1194 \a edges should either be a single edge, or two adjacent edges (a corner). Other values
1195 are not allowed.
1196
1197 Returns true if the operation was supported by the system.
1198*/
1199bool QWindow::startSystemResize(Qt::Edges edges)
1200{
1201 Q_D(QWindow);
1202 if (Q_UNLIKELY(!isVisible() || !d->platformWindow || d->maximumSize == d->minimumSize))
1203 return false;
1204
1205 const bool isSingleEdge = edges == Qt::TopEdge || edges == Qt::RightEdge || edges == Qt::BottomEdge || edges == Qt::LeftEdge;
1206 const bool isCorner =
1207 edges == (Qt::TopEdge | Qt::LeftEdge) ||
1208 edges == (Qt::TopEdge | Qt::RightEdge) ||
1209 edges == (Qt::BottomEdge | Qt::RightEdge) ||
1210 edges == (Qt::BottomEdge | Qt::LeftEdge);
1211
1212 if (Q_UNLIKELY(!isSingleEdge && !isCorner)) {
1213 qWarning() << "Invalid edges" << edges << "passed to QWindow::startSystemResize, ignoring.";
1214 return false;
1215 }
1216
1217 return d->platformWindow->startSystemResize(edges);
1218}
1219
1220/*!
1221 \brief Start a system-specific move operation
1222 \since 5.15
1223
1224 Calling this will start an interactive move operation on the window by platforms
1225 that support it. The actual behavior may vary depending on the platform. Usually,
1226 it will make the window follow the mouse cursor until a mouse button is released.
1227
1228 On platforms that support it, this method of moving windows is preferred over
1229 \c setPosition, because it allows a more native look-and-feel of moving windows, e.g.
1230 letting the window manager snap this window against other windows, or special tiling
1231 or resizing behavior with animations when dragged to the edge of the screen.
1232 Furthermore, on some platforms such as Wayland, \c setPosition is not supported, so
1233 this is the only way the application can influence its position.
1234
1235 Returns true if the operation was supported by the system.
1236*/
1237bool QWindow::startSystemMove()
1238{
1239 Q_D(QWindow);
1240 if (Q_UNLIKELY(!isVisible() || !d->platformWindow))
1241 return false;
1242
1243 return d->platformWindow->startSystemMove();
1244}
1245
1246/*!
1247 \property QWindow::opacity
1248 \brief The opacity of the window in the windowing system.
1249 \since 5.1
1250
1251 If the windowing system supports window opacity, this can be used to fade the
1252 window in and out, or to make it semitransparent.
1253
1254 A value of 1.0 or above is treated as fully opaque, whereas a value of 0.0 or below
1255 is treated as fully transparent. Values inbetween represent varying levels of
1256 translucency between the two extremes.
1257
1258 The default value is 1.0.
1259*/
1260void QWindow::setOpacity(qreal level)
1261{
1262 Q_D(QWindow);
1263 if (level == d->opacity)
1264 return;
1265 d->opacity = level;
1266 if (d->platformWindow) {
1267 d->platformWindow->setOpacity(level);
1268 emit opacityChanged(level);
1269 }
1270}
1271
1272qreal QWindow::opacity() const
1273{
1274 Q_D(const QWindow);
1275 return d->opacity;
1276}
1277
1278/*!
1279 Sets the mask of the window.
1280
1281 The mask is a hint to the windowing system that the application does not
1282 want to receive mouse or touch input outside the given \a region.
1283
1284 The window manager may or may not choose to display any areas of the window
1285 not included in the mask, thus it is the application's responsibility to
1286 clear to transparent the areas that are not part of the mask.
1287*/
1288void QWindow::setMask(const QRegion &region)
1289{
1290 Q_D(QWindow);
1291 if (d->platformWindow)
1292 d->platformWindow->setMask(QHighDpi::toNativeLocalRegion(region, this));
1293 d->mask = region;
1294}
1295
1296/*!
1297 Returns the mask set on the window.
1298
1299 The mask is a hint to the windowing system that the application does not
1300 want to receive mouse or touch input outside the given region.
1301*/
1302QRegion QWindow::mask() const
1303{
1304 Q_D(const QWindow);
1305 return d->mask;
1306}
1307
1308/*!
1309 Requests the window to be activated, i.e. receive keyboard focus.
1310
1311 \sa isActive(), QGuiApplication::focusWindow()
1312*/
1313void QWindow::requestActivate()
1314{
1315 Q_D(QWindow);
1316 if (flags() & Qt::WindowDoesNotAcceptFocus) {
1317 qWarning() << "requestActivate() called for " << this << " which has Qt::WindowDoesNotAcceptFocus set.";
1318 return;
1319 }
1320 if (d->platformWindow)
1321 d->platformWindow->requestActivateWindow();
1322}
1323
1324/*!
1325 Returns if this window is exposed in the windowing system.
1326
1327 When the window is not exposed, it is shown by the application
1328 but it is still not showing in the windowing system, so the application
1329 should minimize animations and other graphical activities.
1330
1331 An exposeEvent() is sent every time this value changes.
1332
1333 \sa exposeEvent()
1334*/
1335bool QWindow::isExposed() const
1336{
1337 Q_D(const QWindow);
1338 return d->exposed;
1339}
1340
1341/*!
1342 \property QWindow::active
1343 \brief the active status of the window
1344 \since 5.1
1345
1346 \sa requestActivate()
1347*/
1348
1349/*!
1350 Returns \c true if the window is active.
1351
1352 This is the case for the window that has input focus as well as windows
1353 that are in the same parent / transient parent chain as the focus window.
1354
1355 Typically active windows should appear active from a style perspective.
1356
1357 To get the window that currently has focus, use QGuiApplication::focusWindow().
1358
1359 \sa requestActivate()
1360*/
1361bool QWindow::isActive() const
1362{
1363 Q_D(const QWindow);
1364 if (!d->platformWindow)
1365 return false;
1366
1367 QWindow *focus = QGuiApplication::focusWindow();
1368
1369 // Means the whole application lost the focus
1370 if (!focus)
1371 return false;
1372
1373 if (focus == this)
1374 return true;
1375
1376 if (QWindow *p = parent(IncludeTransients))
1377 return p->isActive();
1378 else
1379 return isAncestorOf(focus);
1380}
1381
1382/*!
1383 \property QWindow::contentOrientation
1384 \brief the orientation of the window's contents
1385
1386 This is a hint to the window manager in case it needs to display
1387 additional content like popups, dialogs, status bars, or similar
1388 in relation to the window.
1389
1390 The recommended orientation is QScreen::orientation() but
1391 an application doesn't have to support all possible orientations,
1392 and thus can opt to ignore the current screen orientation.
1393
1394 The difference between the window and the content orientation
1395 determines how much to rotate the content by. QScreen::angleBetween(),
1396 QScreen::transformBetween(), and QScreen::mapBetween() can be used
1397 to compute the necessary transform.
1398
1399 The default value is Qt::PrimaryOrientation
1400*/
1401void QWindow::reportContentOrientationChange(Qt::ScreenOrientation orientation)
1402{
1403 Q_D(QWindow);
1404 if (d->contentOrientation == orientation)
1405 return;
1406 if (d->platformWindow)
1407 d->platformWindow->handleContentOrientationChange(orientation);
1408 d->contentOrientation = orientation;
1409 emit contentOrientationChanged(orientation);
1410}
1411
1412Qt::ScreenOrientation QWindow::contentOrientation() const
1413{
1414 Q_D(const QWindow);
1415 return d->contentOrientation;
1416}
1417
1418/*!
1419 Returns the ratio between physical pixels and device-independent pixels
1420 for the window. This value is dependent on the screen the window is on,
1421 and may change when the window is moved.
1422
1423 The QWindow instance receives an event of type
1424 QEvent::DevicePixelRatioChange when the device pixel ratio changes.
1425
1426 Common values are 1.0 on normal displays and 2.0 on Apple "retina" displays.
1427
1428 \note For windows not backed by a platform window, meaning that create() was not
1429 called, the function will fall back to the associated QScreen's device pixel ratio.
1430
1431 \sa QScreen::devicePixelRatio(), QEvent::DevicePixelRatioChange
1432*/
1433qreal QWindow::devicePixelRatio() const
1434{
1435 Q_D(const QWindow);
1436 return d->devicePixelRatio;
1437}
1438
1439/*
1440 Updates the cached devicePixelRatio value by polling for a new value.
1441 Sends QEvent::DevicePixelRatioChange to the window if the DPR has changed.
1442 Returns true if the DPR was changed.
1443*/
1444bool QWindowPrivate::updateDevicePixelRatio()
1445{
1446 Q_Q(QWindow);
1447
1448 const qreal newDevicePixelRatio = [this, q]{
1449 if (platformWindow)
1450 return platformWindow->devicePixelRatio() * QHighDpiScaling::factor(q);
1451
1452 // If there is no platform window use the associated screen's devicePixelRatio,
1453 // which typically is the primary screen and will be correct for single-display
1454 // systems (a very common case).
1455 if (auto *screen = q->screen())
1456 return screen->devicePixelRatio();
1457
1458 // In some cases we are running without any QScreens, so fall back to QGuiApp
1459 return qGuiApp->devicePixelRatio();
1460 }();
1461
1462 if (newDevicePixelRatio == devicePixelRatio)
1463 return false;
1464
1465 devicePixelRatio = newDevicePixelRatio;
1466 QEvent dprChangeEvent(QEvent::DevicePixelRatioChange);
1467 QGuiApplication::sendEvent(q, &dprChangeEvent);
1468 return true;
1469}
1470
1471Qt::WindowState QWindowPrivate::effectiveState(Qt::WindowStates state)
1472{
1473 if (state & Qt::WindowMinimized)
1474 return Qt::WindowMinimized;
1475 else if (state & Qt::WindowFullScreen)
1476 return Qt::WindowFullScreen;
1477 else if (state & Qt::WindowMaximized)
1478 return Qt::WindowMaximized;
1479 return Qt::WindowNoState;
1480}
1481
1482/*!
1483 \brief set the screen-occupation state of the window
1484
1485 The window \a state represents whether the window appears in the
1486 windowing system as maximized, minimized, fullscreen, or normal.
1487
1488 The enum value Qt::WindowActive is not an accepted parameter.
1489
1490 \sa showNormal(), showFullScreen(), showMinimized(), showMaximized(), setWindowStates()
1491*/
1492void QWindow::setWindowState(Qt::WindowState state)
1493{
1494 setWindowStates(state);
1495}
1496
1497/*!
1498 \brief set the screen-occupation state of the window
1499 \since 5.10
1500
1501 The window \a state represents whether the window appears in the
1502 windowing system as maximized, minimized and/or fullscreen.
1503
1504 The window can be in a combination of several states. For example, if
1505 the window is both minimized and maximized, the window will appear
1506 minimized, but clicking on the task bar entry will restore it to the
1507 maximized state.
1508
1509 The enum value Qt::WindowActive should not be set.
1510
1511 \sa showNormal(), showFullScreen(), showMinimized(), showMaximized()
1512 */
1513void QWindow::setWindowStates(Qt::WindowStates state)
1514{
1515 Q_D(QWindow);
1516 if (state & Qt::WindowActive) {
1517 qWarning("QWindow::setWindowStates does not accept Qt::WindowActive");
1518 state &= ~Qt::WindowActive;
1519 }
1520
1521 if (d->platformWindow)
1522 d->platformWindow->setWindowState(state);
1523
1524 auto originalEffectiveState = QWindowPrivate::effectiveState(d->windowState);
1525 d->windowState = state;
1526 auto newEffectiveState = QWindowPrivate::effectiveState(d->windowState);
1527 if (newEffectiveState != originalEffectiveState)
1528 emit windowStateChanged(newEffectiveState);
1529
1530 d->updateVisibility();
1531}
1532
1533/*!
1534 \brief the screen-occupation state of the window
1535
1536 \sa setWindowState(), windowStates()
1537*/
1538Qt::WindowState QWindow::windowState() const
1539{
1540 Q_D(const QWindow);
1541 return QWindowPrivate::effectiveState(d->windowState);
1542}
1543
1544/*!
1545 \brief the screen-occupation state of the window
1546 \since 5.10
1547
1548 The window can be in a combination of several states. For example, if
1549 the window is both minimized and maximized, the window will appear
1550 minimized, but clicking on the task bar entry will restore it to
1551 the maximized state.
1552
1553 \sa setWindowStates()
1554*/
1555Qt::WindowStates QWindow::windowStates() const
1556{
1557 Q_D(const QWindow);
1558 return d->windowState;
1559}
1560
1561/*!
1562 \fn QWindow::windowStateChanged(Qt::WindowState windowState)
1563
1564 This signal is emitted when the \a windowState changes, either
1565 by being set explicitly with setWindowStates(), or automatically when
1566 the user clicks one of the titlebar buttons or by other means.
1567*/
1568
1569/*!
1570 \property QWindow::transientParent
1571 \brief the window for which this window is a transient pop-up
1572 \since 5.13
1573
1574 This is a hint to the window manager that this window is a dialog or pop-up
1575 on behalf of the transient parent.
1576
1577 In order to cause the window to be centered above its transient \a parent by
1578 default, depending on the window manager, it may also be necessary to call
1579 setFlags() with a suitable \l Qt::WindowType (such as \c Qt::Dialog).
1580
1581 \sa parent()
1582*/
1583void QWindow::setTransientParent(QWindow *parent)
1584{
1585 Q_D(QWindow);
1586 if (parent && !parent->isTopLevel()) {
1587 qWarning() << parent << "must be a top level window.";
1588 return;
1589 }
1590 if (parent == this) {
1591 qWarning() << "transient parent" << parent << "cannot be same as window";
1592 return;
1593 }
1594
1595 d->transientParent = parent;
1596
1597 QGuiApplicationPrivate::updateBlockedStatus(this);
1598 emit transientParentChanged(parent);
1599}
1600
1601QWindow *QWindow::transientParent() const
1602{
1603 Q_D(const QWindow);
1604 return d->transientParent.data();
1605}
1606
1607/*
1608 The setter for the QWindow::transientParent property.
1609 The only reason this exists is to set the transientParentPropertySet flag
1610 so that Qt Quick knows whether it was set programmatically (because of
1611 Window declaration context) or because the user set the property.
1612*/
1613void QWindowPrivate::setTransientParent(QWindow *parent)
1614{
1615 Q_Q(QWindow);
1616 q->setTransientParent(parent);
1617 transientParentPropertySet = true;
1618}
1619
1620/*!
1621 \enum QWindow::AncestorMode
1622
1623 This enum is used to control whether or not transient parents
1624 should be considered ancestors.
1625
1626 \value ExcludeTransients Transient parents are not considered ancestors.
1627 \value IncludeTransients Transient parents are considered ancestors.
1628*/
1629
1630/*!
1631 Returns \c true if the window is an ancestor of the given \a child. If \a mode
1632 is IncludeTransients, then transient parents are also considered ancestors.
1633*/
1634bool QWindow::isAncestorOf(const QWindow *child, AncestorMode mode) const
1635{
1636 if (child->parent() == this || (mode == IncludeTransients && child->transientParent() == this))
1637 return true;
1638
1639 if (QWindow *parent = child->parent(mode)) {
1640 if (isAncestorOf(parent, mode))
1641 return true;
1642 } else if (handle() && child->handle()) {
1643 if (handle()->isAncestorOf(child->handle()))
1644 return true;
1645 }
1646
1647 return false;
1648}
1649
1650/*!
1651 Returns the minimum size of the window.
1652
1653 \sa setMinimumSize()
1654*/
1655QSize QWindow::minimumSize() const
1656{
1657 Q_D(const QWindow);
1658 return d->minimumSize;
1659}
1660
1661/*!
1662 Returns the maximum size of the window.
1663
1664 \sa setMaximumSize()
1665*/
1666QSize QWindow::maximumSize() const
1667{
1668 Q_D(const QWindow);
1669 return d->maximumSize;
1670}
1671
1672/*!
1673 Returns the base size of the window.
1674
1675 \sa setBaseSize()
1676*/
1677QSize QWindow::baseSize() const
1678{
1679 Q_D(const QWindow);
1680 return d->baseSize;
1681}
1682
1683/*!
1684 Returns the size increment of the window.
1685
1686 \sa setSizeIncrement()
1687*/
1688QSize QWindow::sizeIncrement() const
1689{
1690 Q_D(const QWindow);
1691 return d->sizeIncrement;
1692}
1693
1694/*!
1695 Sets the minimum size of the window.
1696
1697 This is a hint to the window manager to prevent resizing below the specified \a size.
1698
1699 \sa setMaximumSize(), minimumSize()
1700*/
1701void QWindow::setMinimumSize(const QSize &size)
1702{
1703 Q_D(QWindow);
1704 d->setMinOrMaxSize(
1705 &d->minimumSize, size, [this, d]() { emit minimumWidthChanged(d->minimumSize.width()); },
1706 [this, d]() { emit minimumHeightChanged(d->minimumSize.height()); });
1707}
1708
1709/*!
1710 \property QWindow::x
1711 \brief the x position of the window's geometry
1712*/
1713void QWindow::setX(int arg)
1714{
1715 Q_D(QWindow);
1716 if (x() != arg)
1717 setGeometry(QRect(arg, y(), width(), height()));
1718 else
1719 d->positionAutomatic = false;
1720}
1721
1722/*!
1723 \property QWindow::y
1724 \brief the y position of the window's geometry
1725*/
1726void QWindow::setY(int arg)
1727{
1728 Q_D(QWindow);
1729 if (y() != arg)
1730 setGeometry(QRect(x(), arg, width(), height()));
1731 else
1732 d->positionAutomatic = false;
1733}
1734
1735/*!
1736 \property QWindow::width
1737 \brief the width of the window's geometry
1738*/
1739void QWindow::setWidth(int w)
1740{
1741 resize(w, height());
1742}
1743
1744/*!
1745 \property QWindow::height
1746 \brief the height of the window's geometry
1747*/
1748void QWindow::setHeight(int h)
1749{
1750 resize(width(), h);
1751}
1752
1753/*!
1754 \property QWindow::minimumWidth
1755 \brief the minimum width of the window's geometry
1756*/
1757void QWindow::setMinimumWidth(int w)
1758{
1759 setMinimumSize(QSize(w, minimumHeight()));
1760}
1761
1762/*!
1763 \property QWindow::minimumHeight
1764 \brief the minimum height of the window's geometry
1765*/
1766void QWindow::setMinimumHeight(int h)
1767{
1768 setMinimumSize(QSize(minimumWidth(), h));
1769}
1770
1771/*!
1772 Sets the maximum size of the window.
1773
1774 This is a hint to the window manager to prevent resizing above the specified \a size.
1775
1776 \sa setMinimumSize(), maximumSize()
1777*/
1778void QWindow::setMaximumSize(const QSize &size)
1779{
1780 Q_D(QWindow);
1781 d->setMinOrMaxSize(
1782 &d->maximumSize, size, [this, d]() { emit maximumWidthChanged(d->maximumSize.width()); },
1783 [this, d]() { emit maximumHeightChanged(d->maximumSize.height()); });
1784}
1785
1786/*!
1787 \property QWindow::maximumWidth
1788 \brief the maximum width of the window's geometry
1789*/
1790void QWindow::setMaximumWidth(int w)
1791{
1792 setMaximumSize(QSize(w, maximumHeight()));
1793}
1794
1795/*!
1796 \property QWindow::maximumHeight
1797 \brief the maximum height of the window's geometry
1798*/
1799void QWindow::setMaximumHeight(int h)
1800{
1801 setMaximumSize(QSize(maximumWidth(), h));
1802}
1803
1804/*!
1805 Sets the base \a size of the window.
1806
1807 The base size is used to calculate a proper window size if the
1808 window defines sizeIncrement().
1809
1810 \sa setMinimumSize(), setMaximumSize(), setSizeIncrement(), baseSize()
1811*/
1812void QWindow::setBaseSize(const QSize &size)
1813{
1814 Q_D(QWindow);
1815 if (d->baseSize == size)
1816 return;
1817 d->baseSize = size;
1818 if (d->platformWindow && isTopLevel())
1819 d->platformWindow->propagateSizeHints();
1820}
1821
1822/*!
1823 Sets the size increment (\a size) of the window.
1824
1825 When the user resizes the window, the size will move in steps of
1826 sizeIncrement().width() pixels horizontally and
1827 sizeIncrement().height() pixels vertically, with baseSize() as the
1828 basis.
1829
1830 By default, this property contains a size with zero width and height.
1831
1832 The windowing system might not support size increments.
1833
1834 \sa setBaseSize(), setMinimumSize(), setMaximumSize()
1835*/
1836void QWindow::setSizeIncrement(const QSize &size)
1837{
1838 Q_D(QWindow);
1839 if (d->sizeIncrement == size)
1840 return;
1841 d->sizeIncrement = size;
1842 if (d->platformWindow && isTopLevel())
1843 d->platformWindow->propagateSizeHints();
1844}
1845
1846/*!
1847 Sets the geometry of the window, excluding its window frame, to a
1848 rectangle constructed from \a posx, \a posy, \a w and \a h.
1849
1850 The geometry is in relation to the virtualGeometry() of its screen.
1851
1852 \sa geometry()
1853*/
1854void QWindow::setGeometry(int posx, int posy, int w, int h)
1855{
1856 setGeometry(QRect(posx, posy, w, h));
1857}
1858
1859/*!
1860 \brief Sets the geometry of the window, excluding its window frame, to \a rect.
1861
1862 The geometry is in relation to the virtualGeometry() of its screen.
1863
1864 \sa geometry()
1865*/
1866void QWindow::setGeometry(const QRect &rect)
1867{
1868 Q_D(QWindow);
1869 d->positionAutomatic = false;
1870 const QRect oldRect = geometry();
1871 if (rect == oldRect)
1872 return;
1873
1874 d->positionPolicy = QWindowPrivate::WindowFrameExclusive;
1875 if (d->platformWindow) {
1876 if (isTopLevel()) {
1877 QScreen *newScreen = d->screenForGeometry(rect);
1878 d->platformWindow->setGeometry(QHighDpi::toNativeGlobalPosition(rect, newScreen));
1879 } else {
1880 d->platformWindow->setGeometry(QHighDpi::toNativeWindowGeometry(rect, this));
1881 }
1882 } else {
1883 d->geometry = rect;
1884
1885 if (rect.x() != oldRect.x())
1886 emit xChanged(rect.x());
1887 if (rect.y() != oldRect.y())
1888 emit yChanged(rect.y());
1889 if (rect.width() != oldRect.width())
1890 emit widthChanged(rect.width());
1891 if (rect.height() != oldRect.height())
1892 emit heightChanged(rect.height());
1893 }
1894}
1895
1896/*
1897 This is equivalent to QPlatformWindow::screenForGeometry, but in platform
1898 independent coordinates. The duplication is unfortunate, but there is a
1899 chicken and egg problem here: we cannot convert to native coordinates
1900 before we know which screen we are on.
1901*/
1902QScreen *QWindowPrivate::screenForGeometry(const QRect &newGeometry) const
1903{
1904 Q_Q(const QWindow);
1905 QScreen *currentScreen = q->screen();
1906 QScreen *fallback = currentScreen;
1907 QPoint center = newGeometry.center();
1908 if (!q->parent() && currentScreen && !currentScreen->geometry().contains(center)) {
1909 const auto screens = currentScreen->virtualSiblings();
1910 for (QScreen* screen : screens) {
1911 if (screen->geometry().contains(center))
1912 return screen;
1913 if (screen->geometry().intersects(newGeometry))
1914 fallback = screen;
1915 }
1916 }
1917 return fallback;
1918}
1919
1920
1921/*!
1922 Returns the geometry of the window, excluding its window frame.
1923
1924 The geometry is in relation to the virtualGeometry() of its screen.
1925
1926 \sa frameMargins(), frameGeometry()
1927*/
1928QRect QWindow::geometry() const
1929{
1930 Q_D(const QWindow);
1931 if (d->platformWindow) {
1932 const auto nativeGeometry = d->platformWindow->geometry();
1933 return QHighDpi::fromNativeWindowGeometry(nativeGeometry, this);
1934 }
1935 return d->geometry;
1936}
1937
1938/*!
1939 Returns the window frame margins surrounding the window.
1940
1941 \sa geometry(), frameGeometry()
1942*/
1943QMargins QWindow::frameMargins() const
1944{
1945 Q_D(const QWindow);
1946 if (d->platformWindow)
1947 return QHighDpi::fromNativePixels(d->platformWindow->frameMargins(), this);
1948 return QMargins();
1949}
1950
1951/*!
1952 Returns the geometry of the window, including its window frame.
1953
1954 The geometry is in relation to the virtualGeometry() of its screen.
1955
1956 \sa geometry(), frameMargins()
1957*/
1958QRect QWindow::frameGeometry() const
1959{
1960 Q_D(const QWindow);
1961 if (d->platformWindow) {
1962 QMargins m = frameMargins();
1963 return QHighDpi::fromNativeWindowGeometry(d->platformWindow->geometry(), this).adjusted(-m.left(), -m.top(), m.right(), m.bottom());
1964 }
1965 return d->geometry;
1966}
1967
1968/*!
1969 Returns the top left position of the window, including its window frame.
1970
1971 This returns the same value as frameGeometry().topLeft().
1972
1973 \sa geometry(), frameGeometry()
1974*/
1975QPoint QWindow::framePosition() const
1976{
1977 Q_D(const QWindow);
1978 if (d->platformWindow) {
1979 QMargins margins = frameMargins();
1980 return QHighDpi::fromNativeWindowGeometry(d->platformWindow->geometry().topLeft(), this) - QPoint(margins.left(), margins.top());
1981 }
1982 return d->geometry.topLeft();
1983}
1984
1985/*!
1986 Sets the upper left position of the window (\a point) including its window frame.
1987
1988 The position is in relation to the virtualGeometry() of its screen.
1989
1990 \sa setGeometry(), frameGeometry()
1991*/
1992void QWindow::setFramePosition(const QPoint &point)
1993{
1994 Q_D(QWindow);
1995 d->positionPolicy = QWindowPrivate::WindowFrameInclusive;
1996 d->positionAutomatic = false;
1997 if (d->platformWindow) {
1998 d->platformWindow->setGeometry(QHighDpi::toNativeWindowGeometry(QRect(point, size()), this));
1999 } else {
2000 d->geometry.moveTopLeft(point);
2001 }
2002}
2003
2004/*!
2005 \fn void QWindow::setFramePosition(int x, int y)
2006 \brief Sets the upper left position of the window, including its window frame, to \a x, \a y
2007
2008 The position is in relation to the virtualGeometry() of its screen.
2009
2010 \since 6.12
2011 \sa setGeometry(), frameGeometry()
2012*/
2013
2014/*!
2015 Returns the safe area margins of the window.
2016
2017 The safe area represents the part of the window where content
2018 can be safely placed without risk of being obscured by, or
2019 conflicting with, other UI elements, such as system UIs.
2020
2021 The margins are relative to the internal geometry of the
2022 window, i.e QRect(0, 0, width(), height()).
2023
2024 \code
2025 void PaintDeviceWindow::paintEvent(QPaintEvent *)
2026 {
2027 QPainter painter(this);
2028 QRect rect(0, 0, width(), height());
2029 painter.fillRect(rect, QGradient::SunnyMorning);
2030 painter.fillRect(rect - safeAreaMargins(), QGradient::DustyGrass);
2031 }
2032 \endcode
2033
2034 \since 6.9
2035 \sa geometry(), safeAreaMarginsChanged()
2036*/
2037QMargins QWindow::safeAreaMargins() const
2038{
2039 Q_D(const QWindow);
2040 if (d->platformWindow)
2041 return QHighDpi::fromNativePixels(d->platformWindow->safeAreaMargins(), this);
2042 return {};
2043}
2044
2045/*!
2046 \fn void QWindow::safeAreaMarginsChanged(QMargins margins)
2047 \since 6.9
2048
2049 This signal is emitted when the safe area margins changed to \a margins.
2050
2051 \sa safeAreaMargins()
2052*/
2053
2054/*!
2055 \brief set the position of the window on the desktop to \a pt
2056
2057 The position is in relation to the virtualGeometry() of its screen.
2058
2059 For interactively moving windows, see startSystemMove(). For interactively
2060 resizing windows, see startSystemResize().
2061
2062 \note Not all windowing systems support setting or querying top level window positions.
2063 On such a system, programmatically moving windows may not have any effect, and artificial
2064 values may be returned for the current positions, such as \c QPoint(0, 0).
2065
2066 \sa position(), startSystemMove()
2067*/
2068void QWindow::setPosition(const QPoint &pt)
2069{
2070 setGeometry(QRect(pt, size()));
2071}
2072
2073/*!
2074 \brief set the position of the window on the desktop to \a posx, \a posy
2075
2076 The position is in relation to the virtualGeometry() of its screen.
2077
2078 \sa position()
2079*/
2080void QWindow::setPosition(int posx, int posy)
2081{
2082 setPosition(QPoint(posx, posy));
2083}
2084
2085/*!
2086 \fn QPoint QWindow::position() const
2087 \brief Returns the position of the window on the desktop excluding any window frame
2088
2089 \note Not all windowing systems support setting or querying top level window positions.
2090 On such a system, programmatically moving windows may not have any effect, and artificial
2091 values may be returned for the current positions, such as \c QPoint(0, 0).
2092
2093 \sa setPosition()
2094*/
2095
2096/*!
2097 \fn QSize QWindow::size() const
2098 \brief Returns the size of the window excluding any window frame
2099
2100 \sa resize()
2101*/
2102
2103/*!
2104 set the size of the window, excluding any window frame, to a QSize
2105 constructed from width \a w and height \a h
2106
2107 For interactively resizing windows, see startSystemResize().
2108
2109 \sa size(), geometry()
2110*/
2111void QWindow::resize(int w, int h)
2112{
2113 resize(QSize(w, h));
2114}
2115
2116/*!
2117 \brief set the size of the window, excluding any window frame, to \a newSize
2118
2119 \sa size(), geometry()
2120*/
2121void QWindow::resize(const QSize &newSize)
2122{
2123 Q_D(QWindow);
2124
2125 const QSize oldSize = size();
2126 if (newSize == oldSize)
2127 return;
2128
2129 d->positionPolicy = QWindowPrivate::WindowFrameExclusive;
2130 if (d->platformWindow) {
2131 d->platformWindow->setGeometry(
2132 QHighDpi::toNativeWindowGeometry(QRect(position(), newSize), this));
2133 } else {
2134 d->geometry.setSize(newSize);
2135 if (newSize.width() != oldSize.width())
2136 emit widthChanged(newSize.width());
2137 if (newSize.height() != oldSize.height())
2138 emit heightChanged(newSize.height());
2139 }
2140}
2141
2142/*!
2143 Releases the native platform resources associated with this window.
2144
2145 \sa create()
2146*/
2147void QWindow::destroy()
2148{
2149 Q_D(QWindow);
2150 if (!d->platformWindow)
2151 return;
2152
2153 if (d->platformWindow->isForeignWindow())
2154 return;
2155
2156 d->destroy();
2157}
2158
2159void QWindowPrivate::destroy()
2160{
2161 if (!platformWindow)
2162 return;
2163
2164 Q_Q(QWindow);
2165 QObjectList childrenWindows = q->children();
2166 for (int i = 0; i < childrenWindows.size(); i++) {
2167 QObject *object = childrenWindows.at(i);
2168 if (object->isWindowType()) {
2169 QWindow *w = static_cast<QWindow*>(object);
2170 qt_window_private(w)->destroy();
2171 }
2172 }
2173
2174 bool wasVisible = q->isVisible();
2175 visibilityOnDestroy = wasVisible && platformWindow;
2176
2177 q->setVisible(false);
2178
2179 // Let subclasses act, typically by doing graphics resource cleaup, when
2180 // the window, to which graphics resource may be tied, is going away.
2181 //
2182 // NB! This is dysfunctional when destroy() is invoked from the dtor since
2183 // a reimplemented event() will not get called in the subclasses at that
2184 // stage. However, the typical QWindow cleanup involves either close() or
2185 // going through QWindowContainer, both of which will do an explicit, early
2186 // destroy(), which is good here.
2187
2188 QPlatformSurfaceEvent e(QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed);
2189 QGuiApplication::sendEvent(q, &e);
2190
2191 // Unset platformWindow before deleting, so that the destructor of the
2192 // platform window does not recurse back into the platform window via
2193 // this window during destruction (e.g. as a result of platform events).
2194 delete std::exchange(platformWindow, nullptr);
2195
2196 if (QGuiApplicationPrivate::focus_window == q)
2197 QGuiApplicationPrivate::focus_window = q->parent();
2198 if (QGuiApplicationPrivate::currentMouseWindow == q)
2199 QGuiApplicationPrivate::currentMouseWindow = q->parent();
2200 if (QGuiApplicationPrivate::currentMousePressWindow == q)
2201 QGuiApplicationPrivate::currentMousePressWindow = q->parent();
2202
2203 for (int i = 0; i < QGuiApplicationPrivate::tabletDevicePoints.size(); ++i)
2204 if (QGuiApplicationPrivate::tabletDevicePoints.at(i).target == q)
2205 QGuiApplicationPrivate::tabletDevicePoints[i].target = q->parent();
2206
2207 resizeEventPending = true;
2208 receivedExpose = false;
2209 exposed = false;
2210
2211 // Position set via setFramePosition will have propagated back to
2212 // our geometry member as client geometry, so when creating the
2213 // window again we need to ensure the policy matches that.
2214 positionPolicy = QWindowPrivate::WindowFrameExclusive;
2215}
2216
2217/*!
2218 Returns the platform window corresponding to the window.
2219
2220 \internal
2221*/
2222QPlatformWindow *QWindow::handle() const
2223{
2224 Q_D(const QWindow);
2225 return d->platformWindow;
2226}
2227
2228/*!
2229 Returns the platform surface corresponding to the window.
2230
2231 \internal
2232*/
2233QPlatformSurface *QWindow::surfaceHandle() const
2234{
2235 Q_D(const QWindow);
2236 return d->platformWindow;
2237}
2238
2239/*!
2240 Sets whether keyboard grab should be enabled or not (\a grab).
2241
2242 If the return value is true, the window receives all key events until
2243 setKeyboardGrabEnabled(false) is called; other windows get no key events at
2244 all. Mouse events are not affected. Use setMouseGrabEnabled() if you want
2245 to grab that.
2246
2247 \sa setMouseGrabEnabled()
2248*/
2249bool QWindow::setKeyboardGrabEnabled(bool grab)
2250{
2251 Q_D(QWindow);
2252 if (d->platformWindow)
2253 return d->platformWindow->setKeyboardGrabEnabled(grab);
2254 return false;
2255}
2256
2257/*!
2258 Sets whether mouse grab should be enabled or not (\a grab).
2259
2260 If the return value is true, the window receives all mouse events until setMouseGrabEnabled(false) is
2261 called; other windows get no mouse events at all. Keyboard events are not affected.
2262 Use setKeyboardGrabEnabled() if you want to grab that.
2263
2264 \sa setKeyboardGrabEnabled()
2265*/
2266bool QWindow::setMouseGrabEnabled(bool grab)
2267{
2268 Q_D(QWindow);
2269 if (d->platformWindow)
2270 return d->platformWindow->setMouseGrabEnabled(grab);
2271 return false;
2272}
2273
2274/*!
2275 Returns the screen on which the window is shown, or null if there is none.
2276
2277 For child windows, this returns the screen of the corresponding top level window.
2278
2279 \sa setScreen(), QScreen::virtualSiblings()
2280*/
2281QScreen *QWindow::screen() const
2282{
2283 Q_D(const QWindow);
2284 return d->parentWindow ? d->parentWindow->screen() : d->topLevelScreen.data();
2285}
2286
2287/*!
2288 Sets the screen on which the window should be shown.
2289
2290 If the window has been created, it will be recreated on the \a newScreen.
2291
2292 \note If the screen is part of a virtual desktop of multiple screens,
2293 the window will not move automatically to \a newScreen. To place the
2294 window relative to the screen, use the screen's topLeft() position.
2295
2296 This function only works for top level windows.
2297
2298 \sa screen(), QScreen::virtualSiblings()
2299*/
2300void QWindow::setScreen(QScreen *newScreen)
2301{
2302 Q_D(QWindow);
2303 if (!newScreen)
2304 newScreen = QGuiApplication::primaryScreen();
2305 d->setTopLevelScreen(newScreen, newScreen != nullptr);
2306}
2307
2308/*!
2309 \fn QWindow::screenChanged(QScreen *screen)
2310
2311 This signal is emitted when a window's \a screen changes, either
2312 by being set explicitly with setScreen(), or automatically when
2313 the window's screen is removed.
2314*/
2315
2316/*!
2317 Returns the accessibility interface for the object that the window represents
2318 \internal
2319 \sa QAccessible
2320 */
2321QAccessibleInterface *QWindow::accessibleRoot() const
2322{
2323 return nullptr;
2324}
2325
2326#if QT_CONFIG(accessibility)
2327/*!
2328 \internal
2329
2330 Sets the accessible parent of the window to \a parent.
2331
2332 A window container represents the window it hosts as a child in its
2333 accessibility interface, so the window has to point back to the container
2334 as well.
2335*/
2336void QWindowPrivate::setAccessibleParent(QObject *parent)
2337{
2338 Q_Q(QWindow);
2339
2340 if (accessibleParent == parent)
2341 return;
2342
2343 accessibleParent = parent;
2344
2345 if (QGuiApplicationPrivate::is_app_running && !QGuiApplicationPrivate::is_app_closing) {
2346 QAccessibleEvent event(q, QAccessible::ParentChanged);
2347 QAccessible::updateAccessibility(&event);
2348 }
2349}
2350#endif
2351
2352/*!
2353 \fn QWindow::focusObjectChanged(QObject *object)
2354
2355 This signal is emitted when the final receiver of events tied to focus
2356 is changed to \a object.
2357
2358 \sa focusObject()
2359*/
2360
2361/*!
2362 Returns the QObject that will be the final receiver of events tied focus, such
2363 as key events.
2364*/
2365QObject *QWindow::focusObject() const
2366{
2367 return const_cast<QWindow *>(this);
2368}
2369
2370/*!
2371 Shows the window.
2372
2373 For child windows, this is equivalent to calling showNormal().
2374 Otherwise, it is equivalent to calling showFullScreen(), showMaximized(), or showNormal(),
2375 depending on the platform's default behavior for the window type and flags.
2376
2377 \sa showFullScreen(), showMaximized(), showNormal(), hide(), QStyleHints::showIsFullScreen(), flags()
2378*/
2379void QWindow::show()
2380{
2381 if (parent()) {
2382 showNormal();
2383 } else {
2384 const auto *platformIntegration = QGuiApplicationPrivate::platformIntegration();
2385 Qt::WindowState defaultState = platformIntegration->defaultWindowState(d_func()->windowFlags);
2386 if (defaultState == Qt::WindowFullScreen)
2387 showFullScreen();
2388 else if (defaultState == Qt::WindowMaximized)
2389 showMaximized();
2390 else
2391 showNormal();
2392 }
2393}
2394
2395/*!
2396 Hides the window.
2397
2398 Equivalent to calling setVisible(false).
2399
2400 \sa show(), setVisible()
2401*/
2402void QWindow::hide()
2403{
2404 setVisible(false);
2405}
2406
2407/*!
2408 Shows the window as minimized.
2409
2410 Equivalent to calling setWindowStates(Qt::WindowMinimized) and then
2411 setVisible(true).
2412
2413 \sa setWindowStates(), setVisible()
2414*/
2415void QWindow::showMinimized()
2416{
2417 setWindowStates(Qt::WindowMinimized);
2418 setVisible(true);
2419}
2420
2421/*!
2422 Shows the window as maximized.
2423
2424 Equivalent to calling setWindowStates(Qt::WindowMaximized) and then
2425 setVisible(true).
2426
2427 \sa setWindowStates(), setVisible()
2428*/
2429void QWindow::showMaximized()
2430{
2431 setWindowStates(Qt::WindowMaximized);
2432 setVisible(true);
2433}
2434
2435/*!
2436 Shows the window as fullscreen.
2437
2438 Equivalent to calling setWindowStates(Qt::WindowFullScreen) and then
2439 setVisible(true).
2440
2441 See the \l{QWidget::showFullScreen()} documentation for platform-specific
2442 considerations and limitations.
2443
2444 \sa setWindowStates(), setVisible()
2445*/
2446void QWindow::showFullScreen()
2447{
2448 setWindowStates(Qt::WindowFullScreen);
2449 setVisible(true);
2450#if !defined Q_OS_QNX // On QNX this window will be activated anyway from libscreen
2451 // activating it here before libscreen activates it causes problems
2452 requestActivate();
2453#endif
2454}
2455
2456/*!
2457 Shows the window as normal, i.e. neither maximized, minimized, nor fullscreen.
2458
2459 Equivalent to calling setWindowStates(Qt::WindowNoState) and then
2460 setVisible(true).
2461
2462 \sa setWindowStates(), setVisible()
2463*/
2464void QWindow::showNormal()
2465{
2466 setWindowStates(Qt::WindowNoState);
2467 setVisible(true);
2468}
2469
2470/*!
2471 Close the window.
2472
2473 This closes the window, effectively calling destroy(), and potentially
2474 quitting the application. Returns \c true on success, false if it has a parent
2475 window (in which case the top level window should be closed instead).
2476
2477 \sa destroy(), QGuiApplication::quitOnLastWindowClosed(), closeEvent()
2478*/
2479bool QWindow::close()
2480{
2481 Q_D(QWindow);
2482 if (d->inClose)
2483 return true;
2484
2485 // Do not close non top level windows
2486 if (!isTopLevel())
2487 return false;
2488
2489 if (!d->platformWindow) {
2490 // dock widgets can transition back and forth to being popups;
2491 // avoid getting stuck
2492 if (QGuiApplicationPrivate::activePopupWindow() == this)
2493 QGuiApplicationPrivate::closePopup(this);
2494 return true;
2495 }
2496
2497 // The window might be deleted during close,
2498 // as a result of delivering the close event.
2499 QPointer guard(this);
2500 d->inClose = true;
2501 bool success = d->platformWindow->close();
2502 if (guard)
2503 d->inClose = false;
2504
2505 return success;
2506}
2507
2508bool QWindowPrivate::participatesInLastWindowClosed() const
2509{
2510 Q_Q(const QWindow);
2511
2512 if (!q->isTopLevel())
2513 return false;
2514
2515 // Tool-tip widgets do not normally have Qt::WA_QuitOnClose,
2516 // but since we do not have a similar flag for non-widget
2517 // windows we need an explicit exclusion here as well.
2518 if (q->type() == Qt::ToolTip)
2519 return false;
2520
2521 // A window with a transient parent is not a primary window,
2522 // it's a secondary window.
2523 if (q->transientParent())
2524 return false;
2525
2526 return true;
2527}
2528
2529bool QWindowPrivate::treatAsVisible() const
2530{
2531 Q_Q(const QWindow);
2532 return q->isVisible();
2533}
2534
2535/*! \internal
2536 Returns the popup window that has consumed \a event, if any.
2537 \a activePopupOnPress is the window that we have observed previously handling the press.
2538*/
2539const QWindow *QWindowPrivate::forwardToPopup(QEvent *event, const QWindow */*activePopupOnPress*/)
2540{
2541 Q_Q(const QWindow);
2542 qCDebug(lcPopup) << "checking for popup alternative to" << q << "for" << event
2543 << "active popup?" << QGuiApplicationPrivate::activePopupWindow();
2544 QWindow *ret = nullptr;
2545 if (QWindow *popupWindow = QGuiApplicationPrivate::activePopupWindow()) {
2546 if (q == popupWindow)
2547 return nullptr; // avoid infinite recursion: we're already handling it
2548 if (event->isPointerEvent()) {
2549 // detach eventPoints before modifying them
2550 QScopedPointer<QPointerEvent> pointerEvent(static_cast<QPointerEvent *>(event)->clone());
2551 for (int i = 0; i < pointerEvent->pointCount(); ++i) {
2552 QEventPoint &eventPoint = pointerEvent->point(i);
2553 const QPoint globalPos = eventPoint.globalPosition().toPoint();
2554 const QPointF mapped = popupWindow->mapFromGlobal(globalPos);
2555 QMutableEventPoint::setPosition(eventPoint, mapped);
2556 QMutableEventPoint::setScenePosition(eventPoint, mapped);
2557 }
2558
2559 /* Popups are expected to be able to directly handle the
2560 drag-release sequence after pressing to open, as well as
2561 any other mouse events that occur within the popup's bounds. */
2562 if (QCoreApplication::sendSpontaneousEvent(popupWindow, pointerEvent.get())) {
2563 event->setAccepted(pointerEvent->isAccepted());
2564 if (pointerEvent->isAccepted())
2565 ret = popupWindow;
2566 }
2567 qCDebug(lcPopup) << q << "forwarded" << event->type() << "to popup" << popupWindow
2568 << "handled?" << (ret != nullptr)
2569 << "accepted?" << event->isAccepted();
2570 return ret;
2571 } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
2572 if (QCoreApplication::sendSpontaneousEvent(popupWindow, event))
2573 ret = popupWindow;
2574 qCDebug(lcPopup) << q << "forwarded" << event->type() << "to popup" << popupWindow
2575 << "handled?" << (ret != nullptr)
2576 << "accepted?" << event->isAccepted();
2577 return ret;
2578 }
2579 }
2580 return ret;
2581}
2582
2583/*!
2584 The expose event (\a ev) is sent by the window system when a window moves
2585 between the un-exposed and exposed states.
2586
2587 An exposed window is potentially visible to the user. If the window is moved
2588 off screen, is made totally obscured by another window, is minimized, or
2589 similar, this function might be called and the value of isExposed() might
2590 change to false. You may use this event to limit expensive operations such
2591 as animations to only run when the window is exposed.
2592
2593 This event should not be used to paint. To handle painting implement
2594 paintEvent() instead.
2595
2596 A resize event will always be sent before the expose event the first time
2597 a window is shown.
2598
2599 \sa paintEvent(), isExposed()
2600*/
2601void QWindow::exposeEvent(QExposeEvent *ev)
2602{
2603 ev->ignore();
2604}
2605
2606/*!
2607 The paint event (\a ev) is sent by the window system whenever an area of
2608 the window needs a repaint, for example when initially showing the window,
2609 or due to parts of the window being uncovered by moving another window.
2610
2611 The application is expected to render into the window in response to the
2612 paint event, regardless of the exposed state of the window. For example,
2613 a paint event may be sent before the window is exposed, to prepare it for
2614 showing to the user.
2615
2616 \since 6.0
2617
2618 \sa exposeEvent()
2619*/
2620void QWindow::paintEvent(QPaintEvent *ev)
2621{
2622 ev->ignore();
2623}
2624
2625/*!
2626 Override this to handle window move events (\a ev).
2627*/
2628void QWindow::moveEvent(QMoveEvent *ev)
2629{
2630 ev->ignore();
2631}
2632
2633/*!
2634 Override this to handle resize events (\a ev).
2635
2636 The resize event is called whenever the window is resized in the windowing system,
2637 either directly through the windowing system acknowledging a setGeometry() or resize() request,
2638 or indirectly through the user resizing the window manually.
2639*/
2640void QWindow::resizeEvent(QResizeEvent *ev)
2641{
2642 ev->ignore();
2643}
2644
2645/*!
2646 Override this to handle show events (\a ev).
2647
2648 The function is called when the window has requested becoming visible.
2649
2650 If the window is successfully shown by the windowing system, this will
2651 be followed by a resize and an expose event.
2652*/
2653void QWindow::showEvent(QShowEvent *ev)
2654{
2655 ev->ignore();
2656}
2657
2658/*!
2659 Override this to handle hide events (\a ev).
2660
2661 The function is called when the window has requested being hidden in the
2662 windowing system.
2663*/
2664void QWindow::hideEvent(QHideEvent *ev)
2665{
2666 ev->ignore();
2667}
2668
2669/*!
2670 Override this to handle close events (\a ev).
2671
2672 The function is called when the window is requested to close. Call \l{QEvent::ignore()}
2673 on the event if you want to prevent the window from being closed.
2674
2675 \sa close()
2676*/
2677void QWindow::closeEvent(QCloseEvent *ev)
2678{
2679 Q_UNUSED(ev);
2680}
2681
2682/*!
2683 Override this to handle any event (\a ev) sent to the window.
2684 Return \c true if the event was recognized and processed.
2685
2686 Remember to call the base class version if you wish for mouse events,
2687 key events, resize events, etc to be dispatched as usual.
2688*/
2689bool QWindow::event(QEvent *ev)
2690{
2691 Q_D(QWindow);
2692 switch (ev->type()) {
2693 case QEvent::MouseMove:
2694 mouseMoveEvent(static_cast<QMouseEvent*>(ev));
2695 break;
2696
2697 case QEvent::MouseButtonPress: {
2698 auto *me = static_cast<QMouseEvent*>(ev);
2699 mousePressEvent(me);
2700 if (!ev->isAccepted())
2701 d->maybeSynthesizeContextMenuEvent(me);
2702 break;
2703 }
2704
2705 case QEvent::MouseButtonRelease: {
2706 auto *me = static_cast<QMouseEvent*>(ev);
2707 mouseReleaseEvent(me);
2708 if (!ev->isAccepted())
2709 d->maybeSynthesizeContextMenuEvent(me);
2710 break;
2711 }
2712
2713 case QEvent::MouseButtonDblClick:
2714 mouseDoubleClickEvent(static_cast<QMouseEvent*>(ev));
2715 break;
2716
2717 case QEvent::TouchBegin:
2718 case QEvent::TouchUpdate:
2719 case QEvent::TouchEnd:
2720 case QEvent::TouchCancel:
2721 touchEvent(static_cast<QTouchEvent *>(ev));
2722 break;
2723
2724 case QEvent::Move:
2725 moveEvent(static_cast<QMoveEvent*>(ev));
2726 break;
2727
2728 case QEvent::Resize:
2729 resizeEvent(static_cast<QResizeEvent*>(ev));
2730 break;
2731
2732 case QEvent::KeyPress:
2733 keyPressEvent(static_cast<QKeyEvent *>(ev));
2734 break;
2735
2736 case QEvent::KeyRelease:
2737 keyReleaseEvent(static_cast<QKeyEvent *>(ev));
2738 break;
2739
2740 case QEvent::FocusIn: {
2741 focusInEvent(static_cast<QFocusEvent *>(ev));
2742#if QT_CONFIG(accessibility)
2743 QAccessible::State state;
2744 state.active = true;
2745 QAccessibleStateChangeEvent event(this, state);
2746 QAccessible::updateAccessibility(&event);
2747#endif
2748 break; }
2749
2750 case QEvent::FocusOut: {
2751 focusOutEvent(static_cast<QFocusEvent *>(ev));
2752#if QT_CONFIG(accessibility)
2753 QAccessible::State state;
2754 state.active = true;
2755 QAccessibleStateChangeEvent event(this, state);
2756 QAccessible::updateAccessibility(&event);
2757#endif
2758 break; }
2759
2760#if QT_CONFIG(wheelevent)
2761 case QEvent::Wheel:
2762 wheelEvent(static_cast<QWheelEvent*>(ev));
2763 break;
2764#endif
2765
2766 case QEvent::Close: {
2767
2768 const bool wasVisible = d->treatAsVisible();
2769 const bool participatesInLastWindowClosed = d->participatesInLastWindowClosed();
2770
2771 // The window might be deleted in the close event handler
2772 QPointer<QWindow> deletionGuard(this);
2773 closeEvent(static_cast<QCloseEvent*>(ev));
2774
2775 if (ev->isAccepted()) {
2776 if (deletionGuard)
2777 destroy();
2778 if (wasVisible && participatesInLastWindowClosed)
2779 QGuiApplicationPrivate::instance()->maybeLastWindowClosed();
2780 }
2781
2782 break;
2783 }
2784
2785 case QEvent::Expose:
2786 exposeEvent(static_cast<QExposeEvent *>(ev));
2787 break;
2788
2789 case QEvent::Paint:
2790 paintEvent(static_cast<QPaintEvent *>(ev));
2791 break;
2792
2793 case QEvent::Show:
2794 showEvent(static_cast<QShowEvent *>(ev));
2795 break;
2796
2797 case QEvent::Hide:
2798 hideEvent(static_cast<QHideEvent *>(ev));
2799 break;
2800
2801 case QEvent::ApplicationWindowIconChange:
2802 setIcon(icon());
2803 break;
2804
2805#if QT_CONFIG(tabletevent)
2806 case QEvent::TabletPress:
2807 case QEvent::TabletMove:
2808 case QEvent::TabletRelease:
2809 tabletEvent(static_cast<QTabletEvent *>(ev));
2810 break;
2811#endif
2812
2813 case QEvent::PlatformSurface: {
2814 if ((static_cast<QPlatformSurfaceEvent *>(ev))->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) {
2815#ifndef QT_NO_OPENGL
2816 QOpenGLContext *context = QOpenGLContext::currentContext();
2817 if (context && context->surface() == static_cast<QSurface *>(this))
2818 context->doneCurrent();
2819#endif
2820 }
2821 break;
2822 }
2823
2824 default:
2825 return QObject::event(ev);
2826 }
2827
2828 return true;
2829}
2830
2831/*! \internal
2832 Synthesize and send a QContextMenuEvent if the given \a event is a suitable
2833 mouse event (a right-button press or release, depending on
2834 QStyleHints::contextMenuTrigger()). On most platforms, it's done on mouse
2835 press; on Windows, it's done on release, because of the potential to
2836 support right-button clicks and drags to select or lasso items, and then
2837 still getting a context menu at the end of that gesture. (That is in
2838 conflict with supporting the press-drag-release gesture to select menu
2839 items on the context menus themselves. Context menus can be implemented
2840 that way by handling the separate press, move and release events.)
2841
2842 Any time the \a event was already handled in some way, it *should* be
2843 accepted, but mere acceptance of the mouse event cannot be taken to
2844 indicate that it's not necessary to synthesize a QContextMenuEvent here,
2845 because the Windows use case requires doing one thing (selecting items)
2846 with the mouse events, and then doing something completely different with
2847 the QContextMenuEvent. In other words, QContextMenuEvent is very different
2848 from other kinds of optional followup events synthesized from unhandled
2849 events (like the way we synthesize a QMouseEvent only if a QTabletEvent was
2850 not handled). Furthermore, there's enough legacy widget code that doesn't
2851 call ignore() on unhandled mouse events. So it's uncertain whether this can
2852 change in Qt 7.
2853
2854 The QContextMenuEvent occurs at the scenePosition(). The position()
2855 was likely already "localized" during the previous delivery.
2856
2857 The synthesis from a mouse button event could be done in the platform
2858 plugin, but so far on Windows it's not done: WM_CONTEXTMENU is not
2859 generated by the OS, because we never call the default window procedure
2860 that would do that in response to unhandled WM_RBUTTONUP. If we
2861 eventually want to do that, we would have to avoid doing it here,
2862 on platforms where the platform plugin is responsible for it.
2863
2864 QGuiApplicationPrivate::processContextMenuEvent also allows
2865 keyboard-triggered context menu events that the QPA plugin might generate.
2866 On Windows, the keyboard may have a menu key. On macOS, control-return
2867 is the usual shortcut; on Gnome, it's shift-F10; and so on.
2868*/
2869void QWindowPrivate::maybeSynthesizeContextMenuEvent(QMouseEvent *event)
2870{
2871#ifndef QT_NO_CONTEXTMENU
2872 if (event->button() == Qt::RightButton
2873 && event->type() == QGuiApplicationPrivate::contextMenuEventType()) {
2874 QContextMenuEvent e(QContextMenuEvent::Mouse, event->scenePosition().toPoint(),
2875 event->globalPosition().toPoint(), event->modifiers());
2876 qCDebug(lcPopup) << "synthesized after"
2877 << (event->isAccepted() ? "ACCEPTED (legacy behavior)" : "ignored")
2878 << event->type() << ":" << &e;
2879 QCoreApplication::forwardEvent(q_func(), &e, event);
2880 if (e.isAccepted())
2881 event->accept();
2882 }
2883#endif
2884}
2885
2886/*!
2887 Schedules a QEvent::UpdateRequest event to be delivered to this window.
2888
2889 The event is delivered in sync with the display vsync on platforms where
2890 this is possible. Otherwise, the event is delivered after a delay of at
2891 most 5 ms. If the window's associated screen reports a
2892 \l{QScreen::refreshRate()}{refresh rate} higher than 60 Hz, the interval is
2893 scaled down to a value smaller than 5. The additional time is there to give
2894 the event loop a bit of idle time to gather system events, and can be
2895 overridden using the QT_QPA_UPDATE_IDLE_TIME environment variable.
2896
2897 When driving animations, this function should be called once after drawing
2898 has completed. Calling this function multiple times will result in a single
2899 event being delivered to the window.
2900
2901 Subclasses of QWindow should reimplement event(), intercept the event and
2902 call the application's rendering code, then call the base class
2903 implementation.
2904
2905 \note The subclass' reimplementation of event() must invoke the base class
2906 implementation, unless it is absolutely sure that the event does not need to
2907 be handled by the base class. For example, the default implementation of
2908 this function relies on QEvent::Timer events. Filtering them away would
2909 therefore break the delivery of the update events.
2910
2911 \since 5.5
2912*/
2913void QWindow::requestUpdate()
2914{
2915 Q_ASSERT_X(QThread::isMainThread(),
2916 "QWindow", "Updates can only be scheduled from the GUI (main) thread");
2917
2918 Q_D(QWindow);
2919 if (d->updateRequestPending || !d->platformWindow)
2920 return;
2921 d->updateRequestPending = true;
2922 d->platformWindow->requestUpdate();
2923}
2924
2925/*!
2926 Override this to handle key press events (\a ev).
2927
2928 \sa keyReleaseEvent()
2929*/
2930void QWindow::keyPressEvent(QKeyEvent *ev)
2931{
2932 ev->ignore();
2933}
2934
2935/*!
2936 Override this to handle key release events (\a ev).
2937
2938 \sa keyPressEvent()
2939*/
2940void QWindow::keyReleaseEvent(QKeyEvent *ev)
2941{
2942 ev->ignore();
2943}
2944
2945/*!
2946 Override this to handle focus in events (\a ev).
2947
2948 Focus in events are sent when the window receives keyboard focus.
2949
2950 \sa focusOutEvent()
2951*/
2952void QWindow::focusInEvent(QFocusEvent *ev)
2953{
2954 ev->ignore();
2955}
2956
2957/*!
2958 Override this to handle focus out events (\a ev).
2959
2960 Focus out events are sent when the window loses keyboard focus.
2961
2962 \sa focusInEvent()
2963*/
2964void QWindow::focusOutEvent(QFocusEvent *ev)
2965{
2966 ev->ignore();
2967}
2968
2969/*!
2970 Override this to handle mouse press events (\a ev).
2971
2972 \sa mouseReleaseEvent()
2973*/
2974void QWindow::mousePressEvent(QMouseEvent *ev)
2975{
2976 ev->ignore();
2977}
2978
2979/*!
2980 Override this to handle mouse release events (\a ev).
2981
2982 \sa mousePressEvent()
2983*/
2984void QWindow::mouseReleaseEvent(QMouseEvent *ev)
2985{
2986 ev->ignore();
2987}
2988
2989/*!
2990 Override this to handle mouse double click events (\a ev).
2991
2992 \sa mousePressEvent(), QStyleHints::mouseDoubleClickInterval()
2993*/
2994void QWindow::mouseDoubleClickEvent(QMouseEvent *ev)
2995{
2996 ev->ignore();
2997}
2998
2999/*!
3000 Override this to handle mouse move events (\a ev).
3001*/
3002void QWindow::mouseMoveEvent(QMouseEvent *ev)
3003{
3004 ev->ignore();
3005}
3006
3007#if QT_CONFIG(wheelevent)
3008/*!
3009 Override this to handle mouse wheel or other wheel events (\a ev).
3010*/
3011void QWindow::wheelEvent(QWheelEvent *ev)
3012{
3013 ev->ignore();
3014}
3015#endif // QT_CONFIG(wheelevent)
3016
3017/*!
3018 Override this to handle touch events (\a ev).
3019*/
3020void QWindow::touchEvent(QTouchEvent *ev)
3021{
3022 ev->ignore();
3023}
3024
3025#if QT_CONFIG(tabletevent)
3026/*!
3027 Override this to handle tablet press, move, and release events (\a ev).
3028
3029 Proximity enter and leave events are not sent to windows, they are
3030 delivered to the application instance.
3031*/
3032void QWindow::tabletEvent(QTabletEvent *ev)
3033{
3034 ev->ignore();
3035}
3036#endif
3037
3038/*!
3039 Override this to handle platform dependent events.
3040 Will be given \a eventType, \a message and \a result.
3041
3042 This might make your application non-portable.
3043
3044 Should return true only if the event was handled.
3045*/
3046
3047bool QWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
3048{
3049 Q_UNUSED(eventType);
3050 Q_UNUSED(message);
3051 Q_UNUSED(result);
3052 return false;
3053}
3054
3055/*!
3056 \fn QPointF QWindow::mapToGlobal(const QPointF &pos) const
3057
3058 Translates the window coordinate \a pos to global screen
3059 coordinates. For example, \c{mapToGlobal(QPointF(0,0))} would give
3060 the global coordinates of the top-left pixel of the window.
3061
3062 \sa mapFromGlobal()
3063 \since 6.0
3064*/
3065QPointF QWindow::mapToGlobal(const QPointF &pos) const
3066{
3067 Q_D(const QWindow);
3068 // QTBUG-43252, prefer platform implementation for foreign windows.
3069 if (d->platformWindow
3070 && (d->platformWindow->isForeignWindow() || d->platformWindow->isEmbedded())) {
3071 return QHighDpi::fromNativeGlobalPosition(d->platformWindow->mapToGlobalF(QHighDpi::toNativeLocalPosition(pos, this)), this);
3072 }
3073
3074 if (!QHighDpiScaling::isActive())
3075 return pos + d->globalPosition();
3076
3077 // The normal pos + windowGlobalPos calculation may give a point which is outside
3078 // screen geometry for windows which span multiple screens, due to the way QHighDpiScaling
3079 // creates gaps between screens in the the device indendent cooordinate system.
3080 //
3081 // Map the position (and the window's global position) to native coordinates, perform
3082 // the addition, and then map back to device independent coordinates.
3083 QPointF nativeLocalPos = QHighDpi::toNativeLocalPosition(pos, this);
3084 // Get the native window position directly from the platform window
3085 // if available (it can be null if the window hasn't been shown yet),
3086 // or fall back to scaling the QWindow position.
3087 QPointF nativeWindowGlobalPos = d->platformWindow
3088 ? d->platformWindow->mapToGlobal(QPoint(0,0)).toPointF()
3089 : QHighDpi::toNativeGlobalPosition(QPointF(d->globalPosition()), this);
3090 QPointF nativeGlobalPos = nativeLocalPos + nativeWindowGlobalPos;
3091 QPointF deviceIndependentGlobalPos = QHighDpi::fromNativeGlobalPosition(nativeGlobalPos, this);
3092 return deviceIndependentGlobalPos;
3093}
3094
3095/*!
3096 \overload
3097*/
3098QPoint QWindow::mapToGlobal(const QPoint &pos) const
3099{
3100 return mapToGlobal(QPointF(pos)).toPoint();
3101}
3102
3103/*!
3104 \fn QPointF QWindow::mapFromGlobal(const QPointF &pos) const
3105
3106 Translates the global screen coordinate \a pos to window
3107 coordinates.
3108
3109 \sa mapToGlobal()
3110 \since 6.0
3111*/
3112QPointF QWindow::mapFromGlobal(const QPointF &pos) const
3113{
3114 Q_D(const QWindow);
3115 // QTBUG-43252, prefer platform implementation for foreign windows.
3116 if (d->platformWindow
3117 && (d->platformWindow->isForeignWindow() || d->platformWindow->isEmbedded())) {
3118 return QHighDpi::fromNativeLocalPosition(d->platformWindow->mapFromGlobalF(QHighDpi::toNativeGlobalPosition(pos, this)), this);
3119 }
3120
3121 if (!QHighDpiScaling::isActive())
3122 return pos - d->globalPosition();
3123
3124 // Calculate local position in the native coordinate system. (See comment for the
3125 // corresponding mapToGlobal() code above).
3126 QPointF nativeGlobalPos = QHighDpi::toNativeGlobalPosition(pos, this);
3127 // Get the native window position directly from the platform window
3128 // if available (it can be null if the window hasn't been shown yet),
3129 // or fall back to scaling the QWindow position.
3130 QPointF nativeWindowGlobalPos = d->platformWindow
3131 ? d->platformWindow->mapToGlobal(QPoint(0,0)).toPointF()
3132 : QHighDpi::toNativeGlobalPosition(QPointF(d->globalPosition()), this);
3133 QPointF nativeLocalPos = nativeGlobalPos - nativeWindowGlobalPos;
3134 QPointF deviceIndependentLocalPos = QHighDpi::fromNativeLocalPosition(nativeLocalPos, this);
3135 return deviceIndependentLocalPos;
3136}
3137
3138/*!
3139 \overload
3140*/
3141QPoint QWindow::mapFromGlobal(const QPoint &pos) const
3142{
3143 return QWindow::mapFromGlobal(QPointF(pos)).toPoint();
3144}
3145
3146QPoint QWindowPrivate::globalPosition() const
3147{
3148 Q_Q(const QWindow);
3149 QPoint offset = q->position();
3150 for (const QWindow *p = q->parent(); p; p = p->parent()) {
3151 QPlatformWindow *pw = p->handle();
3152 if (pw && (pw->isForeignWindow() || pw->isEmbedded())) {
3153 // Use mapToGlobal() for foreign windows
3154 offset += p->mapToGlobal(QPoint(0, 0));
3155 break;
3156 } else {
3157 offset += p->position();
3158 }
3159 }
3160 return offset;
3161}
3162
3163Q_GUI_EXPORT QWindowPrivate *qt_window_private(QWindow *window)
3164{
3165 return window->d_func();
3166}
3167
3168QWindow *QWindowPrivate::topLevelWindow(QWindow::AncestorMode mode) const
3169{
3170 Q_Q(const QWindow);
3171
3172 QWindow *window = const_cast<QWindow *>(q);
3173
3174 while (window) {
3175 QWindow *parent = window->parent(mode);
3176 if (!parent)
3177 break;
3178
3179 window = parent;
3180 }
3181
3182 return window;
3183}
3184
3185/*
3186 \internal
3187 \class QForeignWindow
3188
3189 QForeignWindow represents a native window handle created by another
3190 UI toolkit, wrapped via QWindow::fromWinId().
3191*/
3193{
3194 Q_OBJECT
3195public:
3196#if QT_CONFIG(accessibility)
3197 /*
3198 Represent the foreign window as itself in the accessibility tree, so
3199 that the accessibility bridges can substitute it for the underlying
3200 native handle if needed, or otherwise represent it as an opaque node
3201 with possible child windows.
3202 */
3204 {
3205 return QAccessible::queryAccessibleInterface(const_cast<QForeignWindow *>(this));
3206 }
3207#endif
3208};
3209
3210/*!
3211 Creates a local representation of a window created by another process or by
3212 using native libraries below Qt.
3213
3214 Given the handle \a id to a native window, this method creates a QWindow
3215 object which can be used to represent the window when invoking methods like
3216 setParent() and setTransientParent().
3217
3218 This can be used, on platforms which support it, to embed a QWindow inside a
3219 native window, or to embed a native window inside a QWindow.
3220
3221 If foreign windows are not supported or embedding the native window
3222 failed in the platform plugin, this function returns \nullptr.
3223
3224 \note The resulting QWindow should not be used to manipulate the underlying
3225 native window (besides re-parenting), or to observe state changes of the
3226 native window. Any support for these kind of operations is incidental, highly
3227 platform dependent and untested.
3228
3229 \sa setParent()
3230*/
3231QWindow *QWindow::fromWinId(WId id)
3232{
3233 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ForeignWindows)) {
3234 qWarning("QWindow::fromWinId(): platform plugin does not support foreign windows.");
3235 return nullptr;
3236 }
3237
3238 QWindow *window = new QForeignWindow;
3239
3240 // Persist the winId in a private property so that we
3241 // can recreate the window after being destroyed.
3242 window->setProperty(kForeignWindowId, id);
3243 window->create();
3244
3245 if (!window->handle()) {
3246 delete window;
3247 return nullptr;
3248 }
3249
3250 return window;
3251}
3252
3253/*!
3254 Causes an alert to be shown for \a msec milliseconds. If \a msec is \c 0 (the
3255 default), then the alert is shown indefinitely until the window becomes
3256 active again. This function has no effect on an active window.
3257
3258 In alert state, the window indicates that it demands attention, for example by
3259 flashing or bouncing the taskbar entry.
3260
3261 \since 5.1
3262*/
3263
3264void QWindow::alert(int msec)
3265{
3266 Q_D(QWindow);
3267 if (!d->platformWindow || d->platformWindow->isAlertState() || isActive())
3268 return;
3269 d->platformWindow->setAlertState(true);
3270 if (d->platformWindow->isAlertState() && msec)
3271 QTimer::singleShot(msec, this, SLOT(_q_clearAlert()));
3272}
3273
3274void QWindowPrivate::_q_clearAlert()
3275{
3276 if (platformWindow && platformWindow->isAlertState())
3277 platformWindow->setAlertState(false);
3278}
3279
3280#ifndef QT_NO_CURSOR
3281/*!
3282 \brief set the cursor shape for this window
3283
3284 The mouse \a cursor will assume this shape when it is over this
3285 window, unless an override cursor is set.
3286 See the \l{Qt::CursorShape}{list of predefined cursor objects} for a
3287 range of useful shapes.
3288
3289 If no cursor has been set, or after a call to unsetCursor(), the
3290 parent window's cursor is used.
3291
3292 By default, the cursor has the Qt::ArrowCursor shape.
3293
3294 Some underlying window implementations will reset the cursor if it
3295 leaves a window even if the mouse is grabbed. If you want to have
3296 a cursor set for all windows, even when outside the window, consider
3297 QGuiApplication::setOverrideCursor().
3298
3299 \sa QGuiApplication::setOverrideCursor()
3300*/
3301void QWindow::setCursor(const QCursor &cursor)
3302{
3303 Q_D(QWindow);
3304 d->setCursor(&cursor);
3305}
3306
3307/*!
3308 \brief Restores the default arrow cursor for this window.
3309 */
3310void QWindow::unsetCursor()
3311{
3312 Q_D(QWindow);
3313 d->setCursor(nullptr);
3314}
3315
3316/*!
3317 \brief the cursor shape for this window
3318
3319 \sa setCursor(), unsetCursor()
3320*/
3321QCursor QWindow::cursor() const
3322{
3323 Q_D(const QWindow);
3324 return d->cursor;
3325}
3326
3327void QWindowPrivate::setCursor(const QCursor *newCursor)
3328{
3329
3330 Q_Q(QWindow);
3331 if (newCursor) {
3332 const Qt::CursorShape newShape = newCursor->shape();
3333 if (newShape <= Qt::LastCursor && hasCursor && newShape == cursor.shape())
3334 return; // Unchanged and no bitmap/custom cursor.
3335 cursor = *newCursor;
3336 hasCursor = true;
3337 } else {
3338 if (!hasCursor)
3339 return;
3340 cursor = QCursor(Qt::ArrowCursor);
3341 hasCursor = false;
3342 }
3343 // Only attempt to emit signal if there is an actual platform cursor
3344 if (applyCursor()) {
3345 QEvent event(QEvent::CursorChange);
3346 QGuiApplication::sendEvent(q, &event);
3347 }
3348}
3349
3350// Apply the cursor and returns true iff the platform cursor exists
3351bool QWindowPrivate::applyCursor()
3352{
3353 Q_Q(QWindow);
3354 if (QScreen *screen = q->screen()) {
3355 if (QPlatformCursor *platformCursor = screen->handle()->cursor()) {
3356 if (!platformWindow)
3357 return true;
3358 QCursor *c = QGuiApplication::overrideCursor();
3359 if (c != nullptr && platformCursor->capabilities().testFlag(QPlatformCursor::OverrideCursor))
3360 return true;
3361 if (!c && hasCursor)
3362 c = &cursor;
3363 platformCursor->changeCursor(c, q);
3364 return true;
3365 }
3366 }
3367 return false;
3368}
3369#endif // QT_NO_CURSOR
3370
3371void *QWindow::resolveInterface(const char *name, int revision) const
3372{
3373 using namespace QNativeInterface::Private;
3374
3375 auto *platformWindow = handle();
3376 Q_UNUSED(platformWindow);
3377 Q_UNUSED(name);
3378 Q_UNUSED(revision);
3379
3380#if defined(Q_OS_WIN)
3381 QT_NATIVE_INTERFACE_RETURN_IF(QWindowsWindow, platformWindow);
3382#endif
3383
3384#if QT_CONFIG(xcb)
3385 QT_NATIVE_INTERFACE_RETURN_IF(QXcbWindow, platformWindow);
3386#endif
3387
3388#if defined(Q_OS_MACOS)
3389 QT_NATIVE_INTERFACE_RETURN_IF(QCocoaWindow, platformWindow);
3390#endif
3391
3392#if QT_CONFIG(wayland)
3393 QT_NATIVE_INTERFACE_RETURN_IF(QWaylandWindow, platformWindow);
3394#endif
3395
3396#if defined(Q_OS_WASM)
3397 QT_NATIVE_INTERFACE_RETURN_IF(QWasmWindow, platformWindow);
3398#endif
3399
3400 return nullptr;
3401}
3402
3403#ifndef QT_NO_DEBUG_STREAM
3404QDebug operator<<(QDebug debug, const QWindow *window)
3405{
3406 QDebugStateSaver saver(debug);
3407 debug.nospace();
3408 if (window) {
3409 debug << window->metaObject()->className() << '(' << (const void *)window;
3410 if (!window->objectName().isEmpty())
3411 debug << ", name=" << window->objectName();
3412 if (debug.verbosity() > 2) {
3413 const QRect geometry = window->geometry();
3414 if (window->isVisible())
3415 debug << ", visible";
3416 if (window->isExposed())
3417 debug << ", exposed";
3418 debug << ", state=" << window->windowState()
3419 << ", type=" << window->type() << ", flags=" << window->flags()
3420 << ", surface type=" << window->surfaceType();
3421 if (window->isTopLevel())
3422 debug << ", toplevel";
3423 debug << ", " << geometry.width() << 'x' << geometry.height()
3424 << Qt::forcesign << geometry.x() << geometry.y() << Qt::noforcesign;
3425 const QMargins margins = window->frameMargins();
3426 if (!margins.isNull())
3427 debug << ", margins=" << margins;
3428 const QMargins safeAreaMargins = window->safeAreaMargins();
3429 if (!safeAreaMargins.isNull())
3430 debug << ", safeAreaMargins=" << safeAreaMargins;
3431 debug << ", devicePixelRatio=" << window->devicePixelRatio();
3432 if (const QPlatformWindow *platformWindow = window->handle())
3433 debug << ", winId=0x" << Qt::hex << platformWindow->winId() << Qt::dec;
3434 if (const QScreen *screen = window->screen())
3435 debug << ", on " << screen->name();
3436 }
3437 debug << ')';
3438 } else {
3439 debug << "QWindow(0x0)";
3440 }
3441 return debug;
3442}
3443#endif // !QT_NO_DEBUG_STREAM
3444
3445#if QT_CONFIG(vulkan) || defined(Q_QDOC)
3446
3447/*!
3448 Associates this window with the specified Vulkan \a instance.
3449
3450 \a instance must stay valid as long as this QWindow instance exists.
3451 */
3452void QWindow::setVulkanInstance(QVulkanInstance *instance)
3453{
3454 Q_D(QWindow);
3455 d->vulkanInstance = instance;
3456}
3457
3458/*!
3459 \return the associated Vulkan instance if any was set, otherwise \nullptr.
3460 */
3461QVulkanInstance *QWindow::vulkanInstance() const
3462{
3463 Q_D(const QWindow);
3464 return d->vulkanInstance;
3465}
3466
3467#endif // QT_CONFIG(vulkan)
3468
3469QT_END_NAMESPACE
3470
3471#include "moc_qwindow.cpp"
3472#include "qwindow.moc"
Combined button and popup list for selecting options.
static constexpr auto kForeignWindowId
Definition qwindow.cpp:543