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
qdialog.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 "kernel/qwidget_p.h"
6#include <QtWidgets/qtwidgetsglobal.h>
7#include <utility>
8#if QT_CONFIG(colordialog)
9#include "qcolordialog.h"
10#endif
11#if QT_CONFIG(fontdialog)
12#include "qfontdialog.h"
13#endif
14#if QT_CONFIG(filedialog)
15#include "qfiledialog.h"
16#endif
17
18#include "qevent.h"
19#include "qapplication.h"
20#include "qlayout.h"
21#if QT_CONFIG(sizegrip)
22#include "qsizegrip.h"
23#endif
24#if QT_CONFIG(whatsthis)
25#include "qwhatsthis.h"
26#endif
27#if QT_CONFIG(menu)
28#include "qmenu.h"
29#endif
30#include "qcursor.h"
31#if QT_CONFIG(messagebox)
32#include "qmessagebox.h"
33#endif
34#if QT_CONFIG(errormessage)
35#include "qerrormessage.h"
36#endif
37#include <qpa/qplatformtheme.h>
38#include "private/qdialog_p.h"
39#include "private/qguiapplication_p.h"
40#if QT_CONFIG(accessibility)
41#include "qaccessible.h"
42#endif
43
45
46static inline std::optional<QPlatformTheme::DialogType> themeDialogType(const QDialog *dialog)
47{
48#if QT_CONFIG(filedialog)
49 if (qobject_cast<const QFileDialog *>(dialog))
50 return QPlatformTheme::FileDialog;
51#endif
52#if QT_CONFIG(colordialog)
53 if (qobject_cast<const QColorDialog *>(dialog))
54 return QPlatformTheme::ColorDialog;
55#endif
56#if QT_CONFIG(fontdialog)
57 if (qobject_cast<const QFontDialog *>(dialog))
58 return QPlatformTheme::FontDialog;
59#endif
60#if QT_CONFIG(messagebox)
61 if (qobject_cast<const QMessageBox *>(dialog))
62 return QPlatformTheme::MessageDialog;
63#endif
64#if QT_CONFIG(errormessage)
65 if (qobject_cast<const QErrorMessage *>(dialog))
66 return QPlatformTheme::MessageDialog;
67#endif
68#if !QT_CONFIG(filedialog) && !QT_CONFIG(colordialog) && !QT_CONFIG(fontdialog) &&
69 !QT_CONFIG(messagebox) && !QT_CONFIG(errormessage)
70 Q_UNUSED(dialog);
71#endif
72 return std::nullopt;
73}
74
75QDialogPrivate::~QDialogPrivate()
76{
77 delete m_platformHelper;
78}
79
80QPlatformDialogHelper *QDialogPrivate::platformHelper() const
81{
82 // Delayed creation of the platform, ensuring that
83 // that qobject_cast<> on the dialog works in the plugin.
84 if (!m_platformHelperCreated && canBeNativeDialog()) {
85 m_platformHelperCreated = true;
86 QDialogPrivate *ncThis = const_cast<QDialogPrivate *>(this);
87 QDialog *dialog = ncThis->q_func();
88 const auto type = themeDialogType(dialog);
89 if (type) {
90 m_platformHelper =
91 QGuiApplicationPrivate::platformTheme()->createPlatformDialogHelper(*type);
92 if (m_platformHelper) {
93 QObject::connect(m_platformHelper, SIGNAL(accept()), dialog, SLOT(accept()));
94 QObject::connect(m_platformHelper, SIGNAL(reject()), dialog, SLOT(reject()));
95 ncThis->initHelper(m_platformHelper);
96 }
97 }
98 }
99 return m_platformHelper;
100}
101
102bool QDialogPrivate::canBeNativeDialog() const
103{
104 if (QCoreApplication::testAttribute(Qt::AA_DontUseNativeDialogs))
105 return false;
106
107 QDialogPrivate *ncThis = const_cast<QDialogPrivate *>(this);
108 QDialog *dialog = ncThis->q_func();
109 const auto type = themeDialogType(dialog);
110 if (type)
111 return QGuiApplicationPrivate::platformTheme()->usePlatformNativeDialog(*type);
112 return false;
113}
114
115/*!
116 \internal
117
118 Properly closes dialog and sets the \a resultCode.
119 */
120void QDialogPrivate::close(int resultCode)
121{
122 Q_Q(QDialog);
123
124 q->setResult(resultCode);
125
126 if (!data.is_closing) {
127 // Until Qt 6.3 we didn't close dialogs, so they didn't receive a QCloseEvent.
128 // It is likely that subclasses implement closeEvent and handle them as rejection
129 // (like QMessageBox and QProgressDialog do), so eat those events.
130 struct CloseEventEater : QObject
131 {
132 using QObject::QObject;
133 protected:
134 bool eventFilter(QObject *o, QEvent *e) override
135 {
136 if (e->type() == QEvent::Close)
137 return true;
138 return QObject::eventFilter(o, e);
139 }
140 } closeEventEater;
141 q->installEventFilter(&closeEventEater);
142 QWidgetPrivate::close();
143 } else {
144 // If the close was initiated outside of QDialog we will end up
145 // here via QDialog::closeEvent calling reject(), in which case
146 // we need to hide the dialog to ensure QDialog::closeEvent does
147 // not ignore the close event. FIXME: Why is QDialog doing this?
148 q->hide();
149 }
150
151 resetModalitySetByOpen();
152}
153
154void QDialogPrivate::recreate()
155{
156 // Calling destroy while having the eventLoop pointer in place would cause the
157 // event loop to exit - however, with recreate, we do not actually want this behavior
158 // but want to keep the QDialog alive, just with a different RHI configuration
159 QPointer<QEventLoop> existingEventLoop = std::exchange(eventLoop, nullptr);
160 QWidgetPrivate::recreate();
161 eventLoop = existingEventLoop;
162}
163
164QWindow *QDialogPrivate::transientParentWindow() const
165{
166 Q_Q(const QDialog);
167 if (const QWidget *parent = q->nativeParentWidget())
168 return parent->windowHandle();
169 else if (q->windowHandle())
170 return q->windowHandle()->transientParent();
171 return nullptr;
172}
173
174bool QDialogPrivate::setNativeDialogVisible(bool visible)
175{
176 if (QPlatformDialogHelper *helper = platformHelper()) {
177 if (visible) {
178 Q_Q(QDialog);
179 helperPrepareShow(helper);
180 nativeDialogInUse = helper->show(q->windowFlags(), q->windowModality(), transientParentWindow());
181 } else if (nativeDialogInUse) {
182 helper->hide();
183 }
184 }
185 return nativeDialogInUse;
186}
187
188QVariant QDialogPrivate::styleHint(QPlatformDialogHelper::StyleHint hint) const
189{
190 if (const QPlatformDialogHelper *helper = platformHelper())
191 return helper->styleHint(hint);
192 return QPlatformDialogHelper::defaultStyleHint(hint);
193}
194
195/*!
196 \class QDialog
197 \brief The QDialog class is the base class of dialog windows.
198
199 \ingroup dialog-classes
200 \ingroup abstractwidgets
201 \inmodule QtWidgets
202
203 A dialog window is a top-level window mostly used for short-term
204 tasks and brief communications with the user. QDialogs may be
205 modal or modeless. QDialogs can
206 provide a \l{#return}{return value}, and they can have \l{#default}{default buttons}. QDialogs can also have a QSizeGrip in their
207 lower-right corner, using setSizeGripEnabled().
208
209 Note that QDialog (and any other widget that has type \c Qt::Dialog) uses
210 the parent widget slightly differently from other classes in Qt. A dialog is
211 always a top-level widget, but if it has a parent, its default location is
212 centered on top of the parent's top-level widget (if it is not top-level
213 itself). It will also share the parent's taskbar entry.
214
215 Use the overload of the QWidget::setParent() function to change
216 the ownership of a QDialog widget. This function allows you to
217 explicitly set the window flags of the reparented widget; using
218 the overloaded function will clear the window flags specifying the
219 window-system properties for the widget (in particular it will
220 reset the Qt::Dialog flag).
221
222 \note The parent relationship of the dialog does \e{not} imply
223 that the dialog will always be stacked on top of the parent
224 window. To ensure that the dialog is always on top, make the
225 dialog modal. This also applies for child windows of the dialog
226 itself. To ensure that child windows of the dialog stay on top
227 of the dialog, make the child windows modal as well.
228
229 \section1 Modal Dialogs
230
231 A \b{modal} dialog is a dialog that blocks input to other
232 visible windows in the same application. Dialogs that are used to
233 request a file name from the user or that are used to set
234 application preferences are usually modal. Dialogs can be
235 \l{Qt::ApplicationModal}{application modal} (the default) or
236 \l{Qt::WindowModal}{window modal}.
237
238 When an application modal dialog is opened, the user must finish
239 interacting with the dialog and close it before they can access
240 any other window in the application. Window modal dialogs only
241 block access to the window associated with the dialog, allowing
242 the user to continue to use other windows in an application.
243
244 The most common way to display a modal dialog is to call its
245 \l open() function. Alternatively, you can call \l{setModal()}{setModal(true)} or
246 \l setWindowModality(), and then \l show(). In both cases, once the dialog is
247 displayed, the control is immediately returned to the caller. You must connect
248 to the \l finished() signal to know when the dialog is closed and what its
249 \l {#return} {return value} is. Alternatively, you can connect to the
250 \l accepted() and \l rejected() signals.
251
252 When implementing a custom dialog, to close the dialog and return an
253 appropriate value, connect a default button, for example, an OK button, to the
254 \l accept() slot, and a Cancel button to the \l reject() slot. Alternatively,
255 you can call the \l done() slot with \c Accepted or \c Rejected.
256
257 If you show the modal dialog to perform a long-running operation, it is
258 recommended to perform the operation in a background worker thread, so that
259 it does not interfere with the GUI thread.
260
261 \warning When using \l open() or \l show(), the modal dialog should not be
262 created on the stack, so that it does not get destroyed as soon as the control
263 returns to the caller.
264
265 \note There is a way to show a modal dialog in a blocking mode by calling
266 \l exec(). In this case, the control returns to the GUI thread only when the
267 dialog is closed. However, such approach is discouraged, because it creates a
268 nested event loop, which is not fully supported by some platforms.
269
270 \section1 Modeless Dialogs
271
272 A \b{modeless} dialog is a dialog that operates
273 independently of other windows in the same application. Find and
274 replace dialogs in word-processors are often modeless to allow the
275 user to interact with both the application's main window and with
276 the dialog.
277
278 Modeless dialogs are displayed using show(), which returns control
279 to the caller immediately.
280
281 If you invoke the \l{QWidget::show()}{show()} function after hiding
282 a dialog, the dialog will be displayed in its original position. This is
283 because the window manager decides the position for windows that
284 have not been explicitly placed by the programmer. To preserve the
285 position of a dialog that has been moved by the user, save its position
286 in your \l{QWidget::closeEvent()}{closeEvent()} handler and then
287 move the dialog to that position, before showing it again.
288
289 \target default
290 \section1 Default Button
291
292 A dialog's \e default button is the button that's pressed when the
293 user presses Enter (Return). This button is used to signify that
294 the user accepts the dialog's settings and wants to close the
295 dialog. Use QPushButton::setDefault(), QPushButton::isDefault()
296 and QPushButton::autoDefault() to set and control the dialog's
297 default button.
298
299 \target escapekey
300 \section1 Escape Key
301
302 If the user presses the Esc key in a dialog, QDialog::reject()
303 will be called. This will cause the window to close:
304 The \l{QCloseEvent}{close event} cannot be \l{QEvent::ignore()}{ignored}.
305
306 \section1 Extensibility
307
308 Extensibility is the ability to show the dialog in two ways: a
309 partial dialog that shows the most commonly used options, and a
310 full dialog that shows all the options. Typically an extensible
311 dialog will initially appear as a partial dialog, but with a
312 \uicontrol More toggle button. If the user presses the
313 \uicontrol More button down, the dialog is expanded.
314
315 \target return
316 \section1 Return Value (Modal Dialogs)
317
318 Modal dialogs are often used in situations where a return value is
319 required, e.g. to indicate whether the user pressed \uicontrol OK or
320 \uicontrol Cancel. A dialog can be closed by calling the accept() or the
321 reject() slots, and exec() will return \c Accepted or \c Rejected
322 as appropriate. The exec() call returns the result of the dialog.
323 The result is also available from result() if the dialog has not
324 been destroyed.
325
326 In order to modify your dialog's close behavior, you can reimplement
327 the functions accept(), reject() or done(). The
328 \l{QWidget::closeEvent()}{closeEvent()} function should only be
329 reimplemented to preserve the dialog's position or to override the
330 standard close or reject behavior.
331
332 \target examples
333 \section1 Code Examples
334
335 A modal dialog:
336
337 \snippet dialogs/dialogs.cpp 1
338
339 A modeless dialog:
340
341 \snippet dialogs/dialogs.cpp 0
342
343 A dialog with an extension:
344
345 \snippet dialogs/dialogs.cpp extension
346
347 By setting the \l{QLayout::}{sizeConstraint} property of the dialog's
348 layout to \l{QLayout::}{SetFixedSize}, the dialog will not be resizable
349 by the user, and will automatically shrink when the extension gets hidden.
350
351 \sa QDialogButtonBox, QTabWidget, QWidget, QProgressDialog,
352 {Standard Dialogs Example}
353*/
354
355/*! \enum QDialog::DialogCode
356
357 The value returned by a modal dialog.
358
359 \value Accepted
360 \value Rejected
361*/
362
363/*!
364 \property QDialog::sizeGripEnabled
365 \brief whether the size grip is enabled
366
367 A QSizeGrip is placed in the bottom-right corner of the dialog when this
368 property is enabled. By default, the size grip is disabled.
369*/
370
371
372/*!
373 Constructs a dialog with parent \a parent.
374
375 A dialog is always a top-level widget, but if it has a parent, its
376 default location is centered on top of the parent. It will also
377 share the parent's taskbar entry.
378
379 The widget flags \a f are passed on to the QWidget constructor.
380 If, for example, you don't want a What's This button in the title bar
381 of the dialog, pass Qt::WindowTitleHint | Qt::WindowSystemMenuHint in \a f.
382
383 \sa QWidget::setWindowFlags()
384*/
385
386QDialog::QDialog(QWidget *parent, Qt::WindowFlags f)
387 : QWidget(*new QDialogPrivate, parent,
388 f | ((f & Qt::WindowType_Mask) == 0 ? Qt::Dialog : Qt::WindowType(0)))
389{
390}
391
392/*!
393 \overload
394 \internal
395*/
396QDialog::QDialog(QDialogPrivate &dd, QWidget *parent, Qt::WindowFlags f)
397 : QWidget(dd, parent, f | ((f & Qt::WindowType_Mask) == 0 ? Qt::Dialog : Qt::WindowType(0)))
398{
399}
400
401/*!
402 Destroys the QDialog, deleting all its children.
403*/
404
405QDialog::~QDialog()
406{
407 QT_TRY {
408 // Need to hide() here, as our (to-be) overridden hide()
409 // will not be called in ~QWidget.
410 hide();
411 } QT_CATCH(...) {
412 // we're in the destructor - just swallow the exception
413 }
414}
415
416/*!
417 \internal
418 This function is called by the push button \a pushButton when it
419 becomes the default button. If \a pushButton is \nullptr, the dialogs
420 default default button becomes the default button. This is what a
421 push button calls when it loses focus.
422*/
423#if QT_CONFIG(pushbutton)
424void QDialogPrivate::setDefault(QPushButton *pushButton)
425{
426 Q_Q(QDialog);
427 bool hasMain = false;
428 const auto pbList = q->findChildren<QPushButton *>();
429 for (QPushButton *pb : pbList) {
430 if (pb->window() == q) {
431 if (pb == mainDef)
432 hasMain = true;
433 if (pb != pushButton)
434 pb->setDefault(false);
435 }
436 }
437 if (!pushButton && hasMain)
438 mainDef->setDefault(true);
439 if (!hasMain)
440 mainDef = pushButton;
441}
442
443/*!
444 \internal
445 This function sets the default default push button to \a pushButton.
446 This function is called by QPushButton::setDefault().
447*/
448void QDialogPrivate::setMainDefault(QPushButton *pushButton)
449{
450 mainDef = nullptr;
451 setDefault(pushButton);
452}
453
454/*!
455 \internal
456 Hides the default button indicator. Called when non auto-default
457 push button get focus.
458 */
459void QDialogPrivate::hideDefault()
460{
461 Q_Q(QDialog);
462 const auto pbList = q->findChildren<QPushButton *>();
463 for (QPushButton *pb : pbList)
464 pb->setDefault(false);
465}
466#endif
467
468void QDialogPrivate::resetModalitySetByOpen()
469{
470 Q_Q(QDialog);
471 if (resetModalityTo != -1 && !q->testAttribute(Qt::WA_SetWindowModality)) {
472 // open() changed the window modality and the user didn't touch it afterwards; restore it
473 q->setWindowModality(Qt::WindowModality(resetModalityTo));
474 q->setAttribute(Qt::WA_SetWindowModality, wasModalitySet);
475#ifdef Q_OS_MACOS
476 Q_ASSERT(resetModalityTo != Qt::WindowModal);
477 q->setParent(q->parentWidget(), Qt::Dialog);
478#endif
479 }
480 resetModalityTo = -1;
481}
482
483/*!
484 In general returns the modal dialog's result code, \c Accepted or
485 \c Rejected.
486
487 \note When called on a QMessageBox instance, the returned value is a
488 value of the \l QMessageBox::StandardButton enum.
489
490 Do not call this function if the dialog was constructed with the
491 Qt::WA_DeleteOnClose attribute.
492*/
493int QDialog::result() const
494{
495 Q_D(const QDialog);
496 return d->rescode;
497}
498
499/*!
500 \fn void QDialog::setResult(int i)
501
502 Sets the modal dialog's result code to \a i.
503
504 \note We recommend that you use one of the values defined by
505 QDialog::DialogCode.
506*/
507void QDialog::setResult(int r)
508{
509 Q_D(QDialog);
510 d->rescode = r;
511}
512
513/*!
514 Shows the dialog as a \l{QDialog#Modal Dialogs}{window modal dialog},
515 returning immediately.
516
517 \sa exec(), show(), result(), setWindowModality()
518*/
519void QDialog::open()
520{
521 Q_D(QDialog);
522
523 Qt::WindowModality modality = windowModality();
524 if (modality != Qt::WindowModal) {
525 d->resetModalityTo = modality;
526 d->wasModalitySet = testAttribute(Qt::WA_SetWindowModality);
527 setWindowModality(Qt::WindowModal);
528 setAttribute(Qt::WA_SetWindowModality, false);
529#ifdef Q_OS_MACOS
530 setParent(parentWidget(), Qt::Sheet);
531#endif
532 }
533
534 setResult(0);
535 show();
536}
537
538/*!
539 Shows the dialog as a \l{QDialog#Modal Dialogs}{modal dialog},
540 blocking until the user closes it. The function returns a \l
541 DialogCode result.
542
543 If the dialog is \l{Qt::ApplicationModal}{application modal}, users cannot
544 interact with any other window in the same application until they close
545 the dialog. If the dialog is \l{Qt::ApplicationModal}{window modal}, only
546 interaction with the parent window is blocked while the dialog is open.
547 By default, the dialog is application modal.
548
549 \note Avoid using this function; instead, use \c{open()}. Unlike exec(),
550 open() is asynchronous, and does not spin an additional event loop. This
551 prevents a series of dangerous bugs from happening (e.g. deleting the
552 dialog's parent while the dialog is open via exec()). When using open() you
553 can connect to the finished() signal of QDialog to be notified when the
554 dialog is closed.
555
556 \sa open(), show(), result(), setWindowModality()
557*/
558
559int QDialog::exec()
560{
561 Q_D(QDialog);
562
563 if (Q_UNLIKELY(d->eventLoop)) {
564 qWarning("QDialog::exec: Recursive call detected");
565 return -1;
566 }
567
568 bool deleteOnClose = testAttribute(Qt::WA_DeleteOnClose);
569 setAttribute(Qt::WA_DeleteOnClose, false);
570
571 d->resetModalitySetByOpen();
572
573 bool wasShowModal = testAttribute(Qt::WA_ShowModal);
574 setAttribute(Qt::WA_ShowModal, true);
575 setResult(0);
576
577 show();
578
579 QPointer<QDialog> guard = this;
580 if (d->nativeDialogInUse) {
581 d->platformHelper()->exec();
582 } else {
583 QEventLoop eventLoop;
584 d->eventLoop = &eventLoop;
585 (void) eventLoop.exec(QEventLoop::DialogExec);
586 }
587 if (guard.isNull())
588 return QDialog::Rejected;
589 d->eventLoop = nullptr;
590
591 setAttribute(Qt::WA_ShowModal, wasShowModal);
592
593 int res = result();
594 if (d->nativeDialogInUse)
595 d->helperDone(static_cast<QDialog::DialogCode>(res), d->platformHelper());
596 if (deleteOnClose)
597 delete this;
598 return res;
599}
600
601/*!
602 Closes the dialog and sets its result code to \a r. The finished() signal
603 will emit \a r; if \a r is QDialog::Accepted or QDialog::Rejected, the
604 accepted() or the rejected() signals will also be emitted, respectively.
605
606 If this dialog is shown with exec(), done() also causes the local event loop
607 to finish, and exec() to return \a r.
608
609 As with QWidget::close(), done() deletes the dialog if the
610 Qt::WA_DeleteOnClose flag is set. If the dialog is the application's
611 main widget, the application terminates. If the dialog is the
612 last window closed, the QGuiApplication::lastWindowClosed() signal is
613 emitted.
614
615 \sa accept(), reject(), QApplication::activeWindow(), QCoreApplication::quit()
616*/
617
618void QDialog::done(int r)
619{
620 QPointer<QDialog> guard(this);
621
622 Q_D(QDialog);
623 d->close(r);
624
625 if (!guard)
626 return;
627
628 int dialogCode = d->dialogCode();
629 if (dialogCode == QDialog::Accepted)
630 emit accepted();
631 else if (dialogCode == QDialog::Rejected)
632 emit rejected();
633
634 if (guard)
635 emit finished(r);
636}
637
638/*!
639 Hides the modal dialog and sets the result code to \c Accepted.
640
641 \sa reject(), done()
642*/
643
644void QDialog::accept()
645{
646 done(Accepted);
647}
648
649/*!
650 Hides the modal dialog and sets the result code to \c Rejected.
651
652 \sa accept(), done()
653*/
654
655void QDialog::reject()
656{
657 done(Rejected);
658}
659
660/*! \reimp */
661bool QDialog::eventFilter(QObject *o, QEvent *e)
662{
663 return QWidget::eventFilter(o, e);
664}
665
666/*****************************************************************************
667 Event handlers
668 *****************************************************************************/
669
670#ifndef QT_NO_CONTEXTMENU
671/*! \reimp */
672void QDialog::contextMenuEvent(QContextMenuEvent *e)
673{
674#if !QT_CONFIG(whatsthis) || !QT_CONFIG(menu)
675 Q_UNUSED(e);
676#else
677 QWidget *w = childAt(e->pos());
678 if (!w) {
679 w = rect().contains(e->pos()) ? this : nullptr;
680 if (!w)
681 return;
682 }
683 while (w && w->whatsThis().size() == 0 && !w->testAttribute(Qt::WA_CustomWhatsThis))
684 w = w->isWindow() ? nullptr : w->parentWidget();
685 if (w) {
686 QPointer<QMenu> p = new QMenu(this);
687 QAction *wt = p.data()->addAction(tr("What's This?"));
688 if (p.data()->exec(e->globalPos()) == wt) {
689 QHelpEvent e(QEvent::WhatsThis, w->rect().center(),
690 w->mapToGlobal(w->rect().center()));
691 QCoreApplication::sendEvent(w, &e);
692 }
693 delete p.data();
694 }
695#endif
696}
697#endif // QT_NO_CONTEXTMENU
698
699/*! \reimp */
700void QDialog::keyPressEvent(QKeyEvent *e)
701{
702#ifndef QT_NO_SHORTCUT
703 // Calls reject() if Escape is pressed. Simulates a button
704 // click for the default button if Enter is pressed. Move focus
705 // for the arrow keys. Ignore the rest.
706 if (e->matches(QKeySequence::Cancel)) {
707 reject();
708 } else
709#endif
710 if (!e->modifiers() || (e->modifiers() & Qt::KeypadModifier && e->key() == Qt::Key_Enter)) {
711 switch (e->key()) {
712#if QT_CONFIG(pushbutton)
713 case Qt::Key_Enter:
714 case Qt::Key_Return: {
715 const auto pbList = findChildren<QPushButton *>();
716 for (QPushButton *pb : pbList) {
717 if (pb->isDefault() && pb->isVisible()) {
718 if (pb->isEnabled())
719 pb->click();
720 return;
721 }
722 }
723 }
724 break;
725#endif
726 default:
727 e->ignore();
728 return;
729 }
730 } else {
731 e->ignore();
732 }
733}
734
735/*! \reimp */
736void QDialog::closeEvent(QCloseEvent *e)
737{
738#if QT_CONFIG(whatsthis)
739 if (isModal() && QWhatsThis::inWhatsThisMode())
740 QWhatsThis::leaveWhatsThisMode();
741#endif
742 if (isVisible()) {
743 QPointer<QObject> that = this;
744 reject();
745 if (that && isVisible())
746 e->ignore();
747 } else {
748 e->accept();
749 }
750}
751
752/*****************************************************************************
753 Geometry management.
754 *****************************************************************************/
755
756/*! \reimp
757*/
758
759void QDialog::setVisible(bool visible)
760{
761 QWidget::setVisible(visible);
762}
763
764void QDialogPrivate::setVisible(bool visible)
765{
766 Q_Q(QDialog);
767 if (!q->testAttribute(Qt::WA_DontShowOnScreen) && canBeNativeDialog() && setNativeDialogVisible(visible))
768 return;
769
770 // We should not block windows by the invisible modal dialog
771 // if a platform-specific dialog is implemented as an in-process
772 // Qt window, because in this case it will also be blocked.
773 const bool dontBlockWindows = q->testAttribute(Qt::WA_DontShowOnScreen)
774 && styleHint(QPlatformDialogHelper::DialogIsQtWindow).toBool();
775 Qt::WindowModality oldModality;
776 bool wasModalitySet;
777
778 if (dontBlockWindows) {
779 oldModality = q->windowModality();
780 wasModalitySet = q->testAttribute(Qt::WA_SetWindowModality);
781 q->setWindowModality(Qt::NonModal);
782 }
783
784 if (visible) {
785 QWidgetPrivate::setVisible(visible);
786
787 // Window activation might be prevented. We can't test isActiveWindow here,
788 // as the window will be activated asynchronously by the window manager.
789 if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
790 QWidget *fw = q->window()->focusWidget();
791 if (!fw)
792 fw = q;
793
794 /*
795 The following block is to handle a special case, and does not
796 really follow proper logic in concern of autoDefault and TAB
797 order. However, it's here to ease usage for the users. If a
798 dialog has a default QPushButton, and first widget in the TAB
799 order also is a QPushButton, then we give focus to the main
800 default QPushButton. This simplifies code for the developers,
801 and actually catches most cases... If not, then they simply
802 have to use [widget*]->setFocus() themselves...
803 */
804#if QT_CONFIG(pushbutton)
805 if (mainDef && fw->focusPolicy() == Qt::NoFocus) {
806 QWidget *first = fw;
807 while ((first = first->nextInFocusChain()) != fw && first->focusPolicy() == Qt::NoFocus)
808 ;
809 if (first != mainDef && qobject_cast<QPushButton*>(first))
810 mainDef->setFocus();
811 }
812 if (!mainDef && q->isWindow()) {
813 QWidget *w = fw;
814 while ((w = w->nextInFocusChain()) != fw) {
815 QPushButton *pb = qobject_cast<QPushButton *>(w);
816 if (pb && pb->autoDefault() && pb->focusPolicy() != Qt::NoFocus) {
817 pb->setDefault(true);
818 break;
819 }
820 }
821 }
822#endif
823 if (fw && !fw->hasFocus()) {
824 QFocusEvent e(QEvent::FocusIn, Qt::TabFocusReason);
825 QCoreApplication::sendEvent(fw, &e);
826 }
827 }
828
829#if QT_CONFIG(accessibility)
830 QAccessibleEvent event(q, QAccessible::DialogStart);
831 QAccessible::updateAccessibility(&event);
832#endif
833
834 } else {
835
836#if QT_CONFIG(accessibility)
837 if (q->isVisible()) {
838 QAccessibleEvent event(q, QAccessible::DialogEnd);
839 QAccessible::updateAccessibility(&event);
840 }
841#endif
842
843 // Reimplemented to exit a modal event loop when the dialog is hidden.
844 QWidgetPrivate::setVisible(visible);
845 if (eventLoop)
846 eventLoop->exit();
847 }
848
849 if (dontBlockWindows) {
850 q->setWindowModality(oldModality);
851 q->setAttribute(Qt::WA_SetWindowModality, wasModalitySet);
852 }
853
854#if QT_CONFIG(pushbutton)
855 const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme();
856 if (mainDef && q->isActiveWindow()
857 && theme->themeHint(QPlatformTheme::DialogSnapToDefaultButton).toBool())
858 QCursor::setPos(mainDef->mapToGlobal(mainDef->rect().center()));
859#endif
860}
861
862/*!\reimp */
863void QDialog::showEvent(QShowEvent *event)
864{
865 if (!event->spontaneous() && !testAttribute(Qt::WA_Moved)) {
866 Qt::WindowStates state = windowState();
867 adjustPosition(parentWidget());
868 setAttribute(Qt::WA_Moved, false); // not really an explicit position
869 if (state != windowState())
870 setWindowState(state);
871 }
872}
873
874/*! \internal */
875void QDialog::adjustPosition(QWidget* w)
876{
877 Q_D(QDialog);
878
879 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
880 if (theme->themeHint(QPlatformTheme::WindowAutoPlacement).toBool())
881 return;
882 QPoint p(0, 0);
883 int extraw = 0, extrah = 0;
884 const QWindow *parentWindow = nullptr;
885 if (w) {
886 w = w->window();
887 } else {
888 parentWindow = d->transientParentWindow();
889 }
890 QRect desk;
891 QScreen *scrn = nullptr;
892 if (w)
893 scrn = w->screen();
894 else if (parentWindow)
895 scrn = parentWindow->screen();
896 else if (QGuiApplication::primaryScreen()->virtualSiblings().size() > 1)
897 scrn = QGuiApplication::screenAt(QCursor::pos());
898 else
899 scrn = screen();
900 if (scrn)
901 desk = scrn->availableGeometry();
902
903 const QWidgetList tlwList = QApplication::topLevelWidgets();
904 for (const QWidget *current : tlwList) {
905 if (current->isVisible()) {
906 int framew = current->geometry().x() - current->x();
907 int frameh = current->geometry().y() - current->y();
908
909 extraw = qMax(extraw, framew);
910 extrah = qMax(extrah, frameh);
911 if (extraw != 0 && extrah != 0)
912 break;
913 }
914 }
915
916 // sanity check for decoration frames. With embedding, we
917 // might get extraordinary values
918 if (extraw == 0 || extrah == 0 || extraw >= 10 || extrah >= 40) {
919 extrah = 40;
920 extraw = 10;
921 }
922
923
924 if (w) {
925 // Use pos() if the widget is embedded into a native window
926 QPoint pp;
927 if (w->windowHandle() && qvariant_cast<WId>(w->windowHandle()->property("_q_embedded_native_parent_handle")))
928 pp = w->pos();
929 else
930 pp = w->mapToGlobal(QPoint(0,0));
931 p = QPoint(pp.x() + w->width()/2,
932 pp.y() + w->height()/ 2);
933 } else if (parentWindow) {
934 // QTBUG-63406: Widget-based dialog in QML, which has no Widget parent
935 // but a transient parent window.
936 QPoint pp = parentWindow->mapToGlobal(QPoint(0, 0));
937 p = QPoint(pp.x() + parentWindow->width() / 2, pp.y() + parentWindow->height() / 2);
938 } else {
939 // p = middle of the desktop
940 p = QPoint(desk.x() + desk.width()/2, desk.y() + desk.height()/2);
941 }
942
943 // p = origin of this
944 p = QPoint(p.x()-width()/2 - extraw,
945 p.y()-height()/2 - extrah);
946
947
948 if (p.x() + extraw + width() > desk.x() + desk.width())
949 p.setX(desk.x() + desk.width() - width() - extraw);
950 if (p.x() < desk.x())
951 p.setX(desk.x());
952
953 if (p.y() + extrah + height() > desk.y() + desk.height())
954 p.setY(desk.y() + desk.height() - height() - extrah);
955 if (p.y() < desk.y())
956 p.setY(desk.y());
957
958 move(p);
959}
960
961/*! \reimp */
962QSize QDialog::sizeHint() const
963{
964 Q_D(const QDialog);
965 if (d->extension) {
966 if (d->orientation == Qt::Horizontal)
967 return QSize(QWidget::sizeHint().width(),
968 qMax(QWidget::sizeHint().height(),d->extension->sizeHint().height()));
969 else
970 return QSize(qMax(QWidget::sizeHint().width(), d->extension->sizeHint().width()),
971 QWidget::sizeHint().height());
972 }
973 return QWidget::sizeHint();
974}
975
976
977/*! \reimp */
978QSize QDialog::minimumSizeHint() const
979{
980 Q_D(const QDialog);
981 if (d->extension) {
982 if (d->orientation == Qt::Horizontal)
983 return QSize(QWidget::minimumSizeHint().width(),
984 qMax(QWidget::minimumSizeHint().height(), d->extension->minimumSizeHint().height()));
985 else
986 return QSize(qMax(QWidget::minimumSizeHint().width(), d->extension->minimumSizeHint().width()),
987 QWidget::minimumSizeHint().height());
988 }
989
990 return QWidget::minimumSizeHint();
991}
992
993/*!
994 \property QDialog::modal
995 \brief whether show() should pop up the dialog as modal or modeless
996
997 By default, this property is \c false and show() pops up the dialog
998 as modeless. Setting this property to true is equivalent to setting
999 QWidget::windowModality to Qt::ApplicationModal.
1000
1001 exec() ignores the value of this property and always pops up the
1002 dialog as modal.
1003
1004 \sa QWidget::windowModality, show(), exec()
1005*/
1006
1007void QDialog::setModal(bool modal)
1008{
1009 setAttribute(Qt::WA_ShowModal, modal);
1010}
1011
1012
1013bool QDialog::isSizeGripEnabled() const
1014{
1015#if QT_CONFIG(sizegrip)
1016 Q_D(const QDialog);
1017 return !!d->resizer;
1018#else
1019 return false;
1020#endif
1021}
1022
1023
1024void QDialog::setSizeGripEnabled(bool enabled)
1025{
1026#if !QT_CONFIG(sizegrip)
1027 Q_UNUSED(enabled);
1028#else
1029 Q_D(QDialog);
1030#if QT_CONFIG(sizegrip)
1031 d->sizeGripEnabled = enabled;
1032 if (enabled && d->doShowExtension)
1033 return;
1034#endif
1035 if (!enabled != !d->resizer) {
1036 if (enabled) {
1037 d->resizer = new QSizeGrip(this);
1038 // adjustSize() processes all events, which is suboptimal
1039 d->resizer->resize(d->resizer->sizeHint());
1040 if (isRightToLeft())
1041 d->resizer->move(rect().bottomLeft() -d->resizer->rect().bottomLeft());
1042 else
1043 d->resizer->move(rect().bottomRight() -d->resizer->rect().bottomRight());
1044 d->resizer->raise();
1045 d->resizer->show();
1046 } else {
1047 delete d->resizer;
1048 d->resizer = nullptr;
1049 }
1050 }
1051#endif // QT_CONFIG(sizegrip)
1052}
1053
1054
1055
1056/*! \reimp */
1057void QDialog::resizeEvent(QResizeEvent *)
1058{
1059#if QT_CONFIG(sizegrip)
1060 Q_D(QDialog);
1061 if (d->resizer) {
1062 if (isRightToLeft())
1063 d->resizer->move(rect().bottomLeft() -d->resizer->rect().bottomLeft());
1064 else
1065 d->resizer->move(rect().bottomRight() -d->resizer->rect().bottomRight());
1066 d->resizer->raise();
1067 }
1068#endif
1069}
1070
1071/*! \fn void QDialog::finished(int result)
1072
1073 This signal is emitted when the dialog's \a result code has been
1074 set, either by the user or by calling done(), accept(), or
1075 reject().
1076
1077 Note that this signal is \e not emitted when hiding the dialog
1078 with hide() or setVisible(false). This includes deleting the
1079 dialog while it is visible.
1080
1081 \sa accepted(), rejected()
1082*/
1083
1084/*! \fn void QDialog::accepted()
1085
1086 This signal is emitted when the dialog has been accepted either by
1087 the user or by calling accept() or done() with the
1088 QDialog::Accepted argument.
1089
1090 Note that this signal is \e not emitted when hiding the dialog
1091 with hide() or setVisible(false). This includes deleting the
1092 dialog while it is visible.
1093
1094 \sa finished(), rejected()
1095*/
1096
1097/*! \fn void QDialog::rejected()
1098
1099 This signal is emitted when the dialog has been rejected either by
1100 the user or by calling reject() or done() with the
1101 QDialog::Rejected argument.
1102
1103 Note that this signal is \e not emitted when hiding the dialog
1104 with hide() or setVisible(false). This includes deleting the
1105 dialog while it is visible.
1106
1107 \sa finished(), accepted()
1108*/
1109
1110QT_END_NAMESPACE
1111#include "moc_qdialog.cpp"
Combined button and popup list for selecting options.
static QT_BEGIN_NAMESPACE std::optional< QPlatformTheme::DialogType > themeDialogType(const QDialog *dialog)
Definition qdialog.cpp:46