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