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