summaryrefslogtreecommitdiffstats
path: root/src/widgets
diff options
context:
space:
mode:
Diffstat (limited to 'src/widgets')
-rw-r--r--src/widgets/accessible/qaccessiblemenu.cpp13
-rw-r--r--src/widgets/accessible/qaccessiblewidget.cpp20
-rw-r--r--src/widgets/accessible/qaccessiblewidgets.cpp4
-rw-r--r--src/widgets/accessible/simplewidgets.cpp3
-rw-r--r--src/widgets/configure.json7
-rw-r--r--src/widgets/dialogs/qcolordialog.cpp7
-rw-r--r--src/widgets/dialogs/qdialog.cpp17
-rw-r--r--src/widgets/dialogs/qdialog_p.h20
-rw-r--r--src/widgets/dialogs/qerrormessage.cpp6
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp123
-rw-r--r--src/widgets/dialogs/qfiledialog.h5
-rw-r--r--src/widgets/dialogs/qfiledialog_p.h20
-rw-r--r--src/widgets/dialogs/qfileinfogatherer.cpp143
-rw-r--r--src/widgets/dialogs/qfileinfogatherer_p.h28
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.cpp160
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.h17
-rw-r--r--src/widgets/dialogs/qfilesystemmodel_p.h61
-rw-r--r--src/widgets/dialogs/qfontdialog.cpp4
-rw-r--r--src/widgets/dialogs/qfscompleter_p.h4
-rw-r--r--src/widgets/dialogs/qmessagebox.cpp13
-rw-r--r--src/widgets/dialogs/qprogressdialog.cpp4
-rw-r--r--src/widgets/dialogs/qsidebar_p.h6
-rw-r--r--src/widgets/dialogs/qwizard.cpp22
-rw-r--r--src/widgets/dialogs/qwizard.h4
-rw-r--r--src/widgets/dialogs/qwizard_win.cpp62
-rw-r--r--src/widgets/dialogs/qwizard_win_p.h24
-rw-r--r--src/widgets/doc/snippets/code/doc_src_styles.cpp5
-rw-r--r--src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp5
-rw-r--r--src/widgets/doc/snippets/macmainwindow.mm290
-rw-r--r--src/widgets/doc/snippets/timeline/main.cpp4
-rw-r--r--src/widgets/doc/src/model-view-programming.qdoc2
-rw-r--r--src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc4
-rw-r--r--src/widgets/effects/qgraphicseffect_p.h8
-rw-r--r--src/widgets/effects/qpixmapfilter_p.h8
-rw-r--r--src/widgets/graphicsview/graphicsview.pri7
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp2
-rw-r--r--src/widgets/graphicsview/qgraphicsanchorlayout_p.h12
-rw-r--r--src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h4
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.cpp25
-rw-r--r--src/widgets/graphicsview/qgraphicsitem.h6
-rw-r--r--src/widgets/graphicsview/qgraphicsitem_p.h28
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.cpp33
-rw-r--r--src/widgets/graphicsview/qgraphicsitemanimation.h5
-rw-r--r--src/widgets/graphicsview/qgraphicslayout.cpp2
-rw-r--r--src/widgets/graphicsview/qgraphicslayout_p.cpp2
-rw-r--r--src/widgets/graphicsview/qgraphicslayout_p.h4
-rw-r--r--src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsproxywidget.cpp59
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.cpp49
-rw-r--r--src/widgets/graphicsview/qgraphicsscene.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsscene_p.h8
-rw-r--r--src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicssceneindex_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsscenelinearindex_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicstransform_p.h2
-rw-r--r--src/widgets/graphicsview/qgraphicsview.cpp77
-rw-r--r--src/widgets/graphicsview/qgraphicsview.h4
-rw-r--r--src/widgets/graphicsview/qgraphicsview_p.h22
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.cpp154
-rw-r--r--src/widgets/graphicsview/qgraphicswidget.h2
-rw-r--r--src/widgets/graphicsview/qgraphicswidget_p.cpp47
-rw-r--r--src/widgets/graphicsview/qgraphicswidget_p.h12
-rw-r--r--src/widgets/graphicsview/qsimplex_p.cpp2
-rw-r--r--src/widgets/graphicsview/qsimplex_p.h2
-rw-r--r--src/widgets/itemviews/qabstractitemview.cpp46
-rw-r--r--src/widgets/itemviews/qcolumnview_p.h4
-rw-r--r--src/widgets/itemviews/qcolumnviewgrip_p.h4
-rw-r--r--src/widgets/itemviews/qdirmodel.cpp4
-rw-r--r--src/widgets/itemviews/qheaderview.cpp84
-rw-r--r--src/widgets/itemviews/qheaderview_p.h2
-rw-r--r--src/widgets/itemviews/qitemeditorfactory.cpp8
-rw-r--r--src/widgets/itemviews/qlistview.cpp21
-rw-r--r--src/widgets/itemviews/qlistview_p.h2
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp6
-rw-r--r--src/widgets/itemviews/qtableview.cpp63
-rw-r--r--src/widgets/itemviews/qtableview_p.h11
-rw-r--r--src/widgets/itemviews/qtablewidget.cpp4
-rw-r--r--src/widgets/itemviews/qtreeview.cpp35
-rw-r--r--src/widgets/itemviews/qtreeview.h2
-rw-r--r--src/widgets/itemviews/qtreeview_p.h4
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp4
-rw-r--r--src/widgets/itemviews/qtreewidget_p.h4
-rw-r--r--src/widgets/kernel/kernel.pri11
-rw-r--r--src/widgets/kernel/mac.pri5
-rw-r--r--src/widgets/kernel/qaction.cpp85
-rw-r--r--src/widgets/kernel/qaction.h4
-rw-r--r--src/widgets/kernel/qaction_p.h18
-rw-r--r--src/widgets/kernel/qactiongroup.cpp119
-rw-r--r--src/widgets/kernel/qactiongroup.h11
-rw-r--r--src/widgets/kernel/qapplication.cpp163
-rw-r--r--src/widgets/kernel/qapplication_p.h60
-rw-r--r--src/widgets/kernel/qboxlayout.cpp2
-rw-r--r--src/widgets/kernel/qdesktopwidget.cpp16
-rw-r--r--src/widgets/kernel/qdesktopwidget_p.h2
-rw-r--r--src/widgets/kernel/qformlayout.cpp4
-rw-r--r--src/widgets/kernel/qgesture_p.h2
-rw-r--r--src/widgets/kernel/qgesturemanager.cpp66
-rw-r--r--src/widgets/kernel/qlayout.cpp6
-rw-r--r--src/widgets/kernel/qlayout_p.h2
-rw-r--r--src/widgets/kernel/qlayoutengine_p.h6
-rw-r--r--src/widgets/kernel/qlayoutitem.cpp11
-rw-r--r--src/widgets/kernel/qopenglwidget.cpp11
-rw-r--r--src/widgets/kernel/qshortcut.cpp82
-rw-r--r--src/widgets/kernel/qsizepolicy.cpp4
-rw-r--r--src/widgets/kernel/qsizepolicy.h56
-rw-r--r--src/widgets/kernel/qtooltip.cpp47
-rw-r--r--src/widgets/kernel/qtooltip.h2
-rw-r--r--src/widgets/kernel/qwhatsthis.cpp30
-rw-r--r--src/widgets/kernel/qwhatsthis.h2
-rw-r--r--src/widgets/kernel/qwidget.cpp1040
-rw-r--r--src/widgets/kernel/qwidget.h14
-rw-r--r--src/widgets/kernel/qwidget_p.h308
-rw-r--r--src/widgets/kernel/qwidgetbackingstore_p.h311
-rw-r--r--src/widgets/kernel/qwidgetrepaintmanager.cpp (renamed from src/widgets/kernel/qwidgetbackingstore.cpp)1257
-rw-r--r--src/widgets/kernel/qwidgetrepaintmanager_p.h153
-rw-r--r--src/widgets/kernel/qwidgetwindow.cpp46
-rw-r--r--src/widgets/kernel/qwidgetwindow_p.h4
-rw-r--r--src/widgets/kernel/qwindowcontainer.cpp2
-rw-r--r--src/widgets/kernel/qwindowcontainer_p.h2
-rw-r--r--src/widgets/kernel/win.pri5
-rw-r--r--src/widgets/statemachine/qbasickeyeventtransition_p.h6
-rw-r--r--src/widgets/statemachine/qbasicmouseeventtransition_p.h4
-rw-r--r--src/widgets/styles/qcommonstyle.cpp141
-rw-r--r--src/widgets/styles/qcommonstyle_p.h2
-rw-r--r--src/widgets/styles/qfusionstyle.cpp70
-rw-r--r--src/widgets/styles/qfusionstyle_p.h18
-rw-r--r--src/widgets/styles/qpixmapstyle.cpp8
-rw-r--r--src/widgets/styles/qpixmapstyle_p.h2
-rw-r--r--src/widgets/styles/qproxystyle_p.h2
-rw-r--r--src/widgets/styles/qstyle.cpp18
-rw-r--r--src/widgets/styles/qstyle.h7
-rw-r--r--src/widgets/styles/qstyle_p.h2
-rw-r--r--src/widgets/styles/qstylehelper.cpp43
-rw-r--r--src/widgets/styles/qstylehelper_p.h13
-rw-r--r--src/widgets/styles/qstyleoption.cpp9
-rw-r--r--src/widgets/styles/qstylesheetstyle.cpp52
-rw-r--r--src/widgets/styles/qstylesheetstyle_p.h32
-rw-r--r--src/widgets/styles/qwindowsstyle.cpp75
-rw-r--r--src/widgets/styles/qwindowsstyle_p.h22
-rw-r--r--src/widgets/styles/qwindowsstyle_p_p.h8
-rw-r--r--src/widgets/util/qcompleter.cpp13
-rw-r--r--src/widgets/util/qcompleter_p.h2
-rw-r--r--src/widgets/util/qflickgesture.cpp23
-rw-r--r--src/widgets/util/qflickgesture_p.h2
-rw-r--r--src/widgets/util/qscroller.cpp3
-rw-r--r--src/widgets/util/qscroller_mac.mm72
-rw-r--r--src/widgets/util/qscrollerproperties.cpp7
-rw-r--r--src/widgets/util/qsystemtrayicon.cpp11
-rw-r--r--src/widgets/util/qsystemtrayicon_x11.cpp4
-rw-r--r--src/widgets/util/qundostack_p.h4
-rw-r--r--src/widgets/util/util.pri4
-rw-r--r--src/widgets/widgets.pro2
-rw-r--r--src/widgets/widgets/qabstractbutton.cpp7
-rw-r--r--src/widgets/widgets/qabstractscrollarea.cpp162
-rw-r--r--src/widgets/widgets/qabstractscrollarea_p.h9
-rw-r--r--src/widgets/widgets/qabstractslider.cpp32
-rw-r--r--src/widgets/widgets/qabstractslider_p.h2
-rw-r--r--src/widgets/widgets/qabstractspinbox.cpp54
-rw-r--r--src/widgets/widgets/qabstractspinbox_p.h2
-rw-r--r--src/widgets/widgets/qcalendarwidget.cpp434
-rw-r--r--src/widgets/widgets/qcalendarwidget.h5
-rw-r--r--src/widgets/widgets/qcombobox.cpp133
-rw-r--r--src/widgets/widgets/qcombobox.h10
-rw-r--r--src/widgets/widgets/qcombobox_p.h14
-rw-r--r--src/widgets/widgets/qdatetimeedit.cpp120
-rw-r--r--src/widgets/widgets/qdatetimeedit.h4
-rw-r--r--src/widgets/widgets/qdatetimeedit_p.h22
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.cpp13
-rw-r--r--src/widgets/widgets/qdockarealayout.cpp52
-rw-r--r--src/widgets/widgets/qdockarealayout_p.h6
-rw-r--r--src/widgets/widgets/qdockwidget.cpp43
-rw-r--r--src/widgets/widgets/qdockwidget_p.h8
-rw-r--r--src/widgets/widgets/qeffects.cpp10
-rw-r--r--src/widgets/widgets/qgroupbox.cpp8
-rw-r--r--src/widgets/widgets/qlineedit.cpp99
-rw-r--r--src/widgets/widgets/qlineedit.h3
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp28
-rw-r--r--src/widgets/widgets/qlineedit_p.h19
-rw-r--r--src/widgets/widgets/qmaccocoaviewcontainer_mac.mm26
-rw-r--r--src/widgets/widgets/qmainwindow.cpp6
-rw-r--r--src/widgets/widgets/qmainwindow.h2
-rw-r--r--src/widgets/widgets/qmainwindowlayout.cpp67
-rw-r--r--src/widgets/widgets/qmainwindowlayout_p.h14
-rw-r--r--src/widgets/widgets/qmdiarea.cpp21
-rw-r--r--src/widgets/widgets/qmdiarea_p.h4
-rw-r--r--src/widgets/widgets/qmdisubwindow.cpp49
-rw-r--r--src/widgets/widgets/qmdisubwindow_p.h8
-rw-r--r--src/widgets/widgets/qmenu.cpp57
-rw-r--r--src/widgets/widgets/qmenu_p.h8
-rw-r--r--src/widgets/widgets/qmenubar.cpp4
-rw-r--r--src/widgets/widgets/qmenubar_p.h4
-rw-r--r--src/widgets/widgets/qplaintextedit.cpp30
-rw-r--r--src/widgets/widgets/qpushbutton.cpp32
-rw-r--r--src/widgets/widgets/qpushbutton_p.h3
-rw-r--r--src/widgets/widgets/qrubberband.cpp13
-rw-r--r--src/widgets/widgets/qscrollarea.cpp5
-rw-r--r--src/widgets/widgets/qscrollarea_p.h2
-rw-r--r--src/widgets/widgets/qscrollbar.cpp10
-rw-r--r--src/widgets/widgets/qsizegrip.cpp34
-rw-r--r--src/widgets/widgets/qslider.cpp3
-rw-r--r--src/widgets/widgets/qspinbox.cpp55
-rw-r--r--src/widgets/widgets/qspinbox.h8
-rw-r--r--src/widgets/widgets/qsplashscreen.cpp6
-rw-r--r--src/widgets/widgets/qsplitter.cpp11
-rw-r--r--src/widgets/widgets/qsplitter_p.h6
-rw-r--r--src/widgets/widgets/qstatusbar.cpp41
-rw-r--r--src/widgets/widgets/qtabbar.cpp33
-rw-r--r--src/widgets/widgets/qtabbar_p.h10
-rw-r--r--src/widgets/widgets/qtabwidget.cpp7
-rw-r--r--src/widgets/widgets/qtextbrowser.cpp122
-rw-r--r--src/widgets/widgets/qtextbrowser.h11
-rw-r--r--src/widgets/widgets/qtextedit.cpp114
-rw-r--r--src/widgets/widgets/qtextedit.h14
-rw-r--r--src/widgets/widgets/qtextedit_p.h3
-rw-r--r--src/widgets/widgets/qtoolbar.cpp10
-rw-r--r--src/widgets/widgets/qtoolbar_p.h2
-rw-r--r--src/widgets/widgets/qtoolbararealayout_p.h2
-rw-r--r--src/widgets/widgets/qtoolbarlayout_p.h2
-rw-r--r--src/widgets/widgets/qtoolbox.cpp86
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol.cpp20
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol_p.h28
-rw-r--r--src/widgets/widgets/qwidgetresizehandler.cpp15
-rw-r--r--src/widgets/widgets/qwidgetresizehandler_p.h2
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp96
-rw-r--r--src/widgets/widgets/qwidgettextcontrol_p.h29
-rw-r--r--src/widgets/widgets/qwidgettextcontrol_p_p.h8
226 files changed, 4030 insertions, 5073 deletions
diff --git a/src/widgets/accessible/qaccessiblemenu.cpp b/src/widgets/accessible/qaccessiblemenu.cpp
index 507584eb02..7f87288520 100644
--- a/src/widgets/accessible/qaccessiblemenu.cpp
+++ b/src/widgets/accessible/qaccessiblemenu.cpp
@@ -47,6 +47,7 @@
#endif
#include <QtWidgets/QAction>
#include <qstyle.h>
+#include <private/qwidget_p.h>
#ifndef QT_NO_ACCESSIBILITY
@@ -241,15 +242,9 @@ QObject *QAccessibleMenuItem::object() const
/*! \reimp */
QWindow *QAccessibleMenuItem::window() const
{
- QWindow *result = nullptr;
- if (!m_owner.isNull()) {
- result = m_owner->windowHandle();
- if (!result) {
- if (const QWidget *nativeParent = m_owner->nativeParentWidget())
- result = nativeParent->windowHandle();
- }
- }
- return result;
+ return m_owner.isNull()
+ ? nullptr
+ : qt_widget_private(m_owner.data())->windowHandle(QWidgetPrivate::WindowHandleMode::Closest);
}
QRect QAccessibleMenuItem::rect() const
diff --git a/src/widgets/accessible/qaccessiblewidget.cpp b/src/widgets/accessible/qaccessiblewidget.cpp
index c96d213e7b..27e6b09dc7 100644
--- a/src/widgets/accessible/qaccessiblewidget.cpp
+++ b/src/widgets/accessible/qaccessiblewidget.cpp
@@ -273,22 +273,6 @@ QRect QAccessibleWidget::rect() const
return QRect(wpos.x(), wpos.y(), w->width(), w->height());
}
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <private/qobject_p.h>
-QT_END_INCLUDE_NAMESPACE
-
-class QACConnectionObject : public QObject
-{
- Q_DECLARE_PRIVATE(QObject)
-public:
- inline bool isSender(const QObject *receiver, const char *signal) const
- { return d_func()->isSender(receiver, signal); }
- inline QObjectList receiverList(const char *signal) const
- { return d_func()->receiverList(signal); }
- inline QObjectList senderList() const
- { return d_func()->senderList(); }
-};
-
/*!
Registers \a signal as a controlling signal.
@@ -347,9 +331,9 @@ QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRel
if (match & QAccessible::Controlled) {
QObjectList allReceivers;
- QACConnectionObject *connectionObject = (QACConnectionObject*)object();
+ QObject *connectionObject = object();
for (int sig = 0; sig < d->primarySignals.count(); ++sig) {
- const QObjectList receivers = connectionObject->receiverList(d->primarySignals.at(sig).toLatin1());
+ const QObjectList receivers = connectionObject->d_func()->receiverList(d->primarySignals.at(sig).toLatin1());
allReceivers += receivers;
}
diff --git a/src/widgets/accessible/qaccessiblewidgets.cpp b/src/widgets/accessible/qaccessiblewidgets.cpp
index 0d87cc486d..52c953ed3a 100644
--- a/src/widgets/accessible/qaccessiblewidgets.cpp
+++ b/src/widgets/accessible/qaccessiblewidgets.cpp
@@ -101,9 +101,9 @@ QString qt_accHotKey(const QString &text);
QList<QWidget*> childWidgets(const QWidget *widget)
{
- if (widget == 0)
- return QList<QWidget*>();
QList<QWidget*> widgets;
+ if (!widget)
+ return widgets;
for (QObject *o : widget->children()) {
QWidget *w = qobject_cast<QWidget *>(o);
if (!w)
diff --git a/src/widgets/accessible/simplewidgets.cpp b/src/widgets/accessible/simplewidgets.cpp
index 716c833fc9..ca74ee4b12 100644
--- a/src/widgets/accessible/simplewidgets.cpp
+++ b/src/widgets/accessible/simplewidgets.cpp
@@ -779,8 +779,7 @@ int QAccessibleLineEdit::cursorPosition() const
QRect QAccessibleLineEdit::characterRect(int offset) const
{
int x = lineEdit()->d_func()->control->cursorToX(offset);
- int y;
- lineEdit()->getTextMargins(0, &y, 0, 0);
+ int y = lineEdit()->textMargins().top();
QFontMetrics fm(lineEdit()->font());
const QString ch = text(offset, offset + 1);
if (ch.isEmpty())
diff --git a/src/widgets/configure.json b/src/widgets/configure.json
index cc9019dfdd..0a68f082a2 100644
--- a/src/widgets/configure.json
+++ b/src/widgets/configure.json
@@ -378,6 +378,7 @@
"label": "QScroller",
"purpose": "Enables kinetic scrolling for any scrolling widget or graphics item.",
"section": "Widgets",
+ "condition": "features.easingcurve",
"output": [ "publicFeature" ]
},
"graphicsview": {
@@ -626,12 +627,6 @@
"condition": "features.listview",
"output": [ "publicFeature", "feature" ]
},
- "paint_debug": {
- "label": "Painting Debug Utilities",
- "purpose": "Enabled debugging painting with the environment variables QT_FLUSH_UPDATE and QT_FLUSH_PAINT.",
- "section": "Painting",
- "output": [ "publicFeature", "feature" ]
- },
"completer": {
"label": "QCompleter",
"purpose": "Provides completions based on an item model.",
diff --git a/src/widgets/dialogs/qcolordialog.cpp b/src/widgets/dialogs/qcolordialog.cpp
index 197d1d940b..d00a600424 100644
--- a/src/widgets/dialogs/qcolordialog.cpp
+++ b/src/widgets/dialogs/qcolordialog.cpp
@@ -57,6 +57,11 @@
#include "qpainter.h"
#include "qpixmap.h"
#include "qpushbutton.h"
+#if QT_CONFIG(regularexpression)
+#include <qregularexpression.h>
+#else
+#include <qregexp.h>
+#endif
#if QT_CONFIG(settings)
#include "qsettings.h"
#endif
@@ -1616,7 +1621,7 @@ void QColorDialogPrivate::_q_pickScreenColor()
q->grabMouse();
#endif
-#ifdef Q_OS_WIN32 // excludes WinCE and WinRT
+#ifdef Q_OS_WIN32 // excludes WinRT
// On Windows mouse tracking doesn't work over other processes's windows
updateTimer->start(30);
diff --git a/src/widgets/dialogs/qdialog.cpp b/src/widgets/dialogs/qdialog.cpp
index caab6c16ba..3cdd9a5f04 100644
--- a/src/widgets/dialogs/qdialog.cpp
+++ b/src/widgets/dialogs/qdialog.cpp
@@ -270,12 +270,11 @@ void QDialogPrivate::deletePlatformHelper()
The most common way to display a modal dialog is to call its
exec() function. When the user closes the dialog, exec() will
- provide a useful \l{#return}{return value}. Typically,
- to get the dialog to close and return the appropriate value, we
- connect a default button, e.g. \uicontrol OK, to the accept() slot and a
- \uicontrol Cancel button to the reject() slot.
- Alternatively you can call the done() slot with \c Accepted or
- \c Rejected.
+ provide a useful \l{#return}{return value}. To close the dialog
+ and return the appropriate value, you must connect a default button,
+ e.g. an \uicontrol OK button to the accept() slot and a
+ \uicontrol Cancel button to the reject() slot. Alternatively, you
+ can call the done() slot with \c Accepted or \c Rejected.
An alternative is to call setModal(true) or setWindowModality(),
then show(). Unlike exec(), show() returns control to the caller
@@ -283,7 +282,7 @@ void QDialogPrivate::deletePlatformHelper()
progress dialogs, where the user must have the ability to interact
with the dialog, e.g. to cancel a long running operation. If you
use show() and setModal(true) together to perform a long operation,
- you must call QApplication::processEvents() periodically during
+ you must call QCoreApplication::processEvents() periodically during
processing to enable the user to interact with the dialog. (See
QProgressDialog.)
@@ -692,7 +691,7 @@ void QDialog::contextMenuEvent(QContextMenuEvent *e)
if (p.data()->exec(e->globalPos()) == wt) {
QHelpEvent e(QEvent::WhatsThis, w->rect().center(),
w->mapToGlobal(w->rect().center()));
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
delete p.data();
}
@@ -827,7 +826,7 @@ QT_WARNING_POP
#endif
if (fw && !fw->hasFocus()) {
QFocusEvent e(QEvent::FocusIn, Qt::TabFocusReason);
- QApplication::sendEvent(fw, &e);
+ QCoreApplication::sendEvent(fw, &e);
}
#ifndef QT_NO_ACCESSIBILITY
diff --git a/src/widgets/dialogs/qdialog_p.h b/src/widgets/dialogs/qdialog_p.h
index 92634f6793..74f775a0bd 100644
--- a/src/widgets/dialogs/qdialog_p.h
+++ b/src/widgets/dialogs/qdialog_p.h
@@ -75,15 +75,15 @@ public:
QDialogPrivate()
:
#if QT_CONFIG(pushbutton)
- mainDef(0),
+ mainDef(nullptr),
#endif
- orientation(Qt::Horizontal),extension(0), doShowExtension(false),
+ orientation(Qt::Horizontal),extension(nullptr), doShowExtension(false),
#if QT_CONFIG(sizegrip)
- resizer(0),
+ resizer(nullptr),
sizeGripEnabled(false),
#endif
- rescode(0), resetModalityTo(-1), wasModalitySet(true), eventLoop(0),
- nativeDialogInUse(false), m_platformHelper(0), m_platformHelperCreated(false)
+ rescode(0), resetModalityTo(-1), wasModalitySet(true), eventLoop(nullptr),
+ nativeDialogInUse(false), m_platformHelper(nullptr), m_platformHelperCreated(false)
{}
~QDialogPrivate();
@@ -140,14 +140,14 @@ class QAutoPointer {
struct internal { void func() {} };
typedef void (internal::*RestrictedBool)();
public:
- explicit QAutoPointer(T *t) Q_DECL_NOTHROW : o(t) {}
+ explicit QAutoPointer(T *t) noexcept : o(t) {}
~QAutoPointer() { delete o; }
- T *operator->() const Q_DECL_NOTHROW { return get(); }
- T *get() const Q_DECL_NOTHROW { return o; }
+ T *operator->() const noexcept { return get(); }
+ T *get() const noexcept { return o; }
T &operator*() const { return *get(); }
- operator RestrictedBool() const Q_DECL_NOTHROW { return o ? &internal::func : nullptr; }
- bool operator!() const Q_DECL_NOTHROW { return !o; }
+ operator RestrictedBool() const noexcept { return o ? &internal::func : nullptr; }
+ bool operator!() const noexcept { return !o; }
private:
Q_DISABLE_COPY(QAutoPointer);
};
diff --git a/src/widgets/dialogs/qerrormessage.cpp b/src/widgets/dialogs/qerrormessage.cpp
index fd68f19680..f0ec2c0102 100644
--- a/src/widgets/dialogs/qerrormessage.cpp
+++ b/src/widgets/dialogs/qerrormessage.cpp
@@ -295,7 +295,7 @@ QErrorMessage * QErrorMessage::qtHandler()
if (!qtMessageHandler) {
qtMessageHandler = new QErrorMessage(0);
qAddPostRoutine(deleteStaticcQErrorMessage); // clean up
- qtMessageHandler->setWindowTitle(QApplication::applicationName());
+ qtMessageHandler->setWindowTitle(QCoreApplication::applicationName());
qInstallMessageHandler(jump);
}
return qtMessageHandler;
@@ -322,8 +322,8 @@ bool QErrorMessagePrivate::nextPending()
#else
errors->setPlainText(message);
#endif
- currentMessage = qMove(message);
- currentType = qMove(type);
+ currentMessage = std::move(message);
+ currentType = std::move(type);
return true;
}
}
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index 2c2d209226..a1b9003c1c 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -44,6 +44,7 @@
#include "qfiledialog.h"
#include "qfiledialog_p.h"
+#include <private/qapplication_p.h>
#include <private/qguiapplication_p.h>
#include <qfontmetrics.h>
#include <qaction.h>
@@ -77,6 +78,8 @@
#include <private/qwasmlocalfileaccess_p.h>
#endif
+#include <algorithm>
+
QT_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QUrl, lastVisitedDir)
@@ -2445,6 +2448,51 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct
}
/*!
+ This is a convenience static function that saves \a fileContent to a file, using
+ a file name and location chosen by the user. \a fileNameHint can be provided to
+ suggest a file name to the user.
+
+ This function is used to save files to the local file system on Qt for WebAssembly, where
+ the web sandbox places restrictions on how such access may happen. Its implementation will
+ make the browser display a native file dialog, where the user makes the file selection.
+
+ It can also be used on other platforms, where it will fall back to using QFileDialog.
+
+ The function is asynchronous and returns immediately.
+
+ \snippet code/src_gui_dialogs_qfiledialog.cpp 16
+ \since 5.14
+*/
+void QFileDialog::saveFileContent(const QByteArray &fileContent, const QString &fileNameHint)
+{
+#ifdef Q_OS_WASM
+ QWasmLocalFileAccess::saveFile(fileContent.constData(), fileContent.size(), fileNameHint.toStdString());
+#else
+ QFileDialog *dialog = new QFileDialog();
+ dialog->setAcceptMode(QFileDialog::AcceptSave);
+ dialog->setFileMode(QFileDialog::AnyFile);
+ dialog->selectFile(fileNameHint);
+
+ auto fileSelected = [=](const QString &fileName) {
+ if (!fileName.isNull()) {
+ QFile selectedFile(fileName);
+ if (selectedFile.open(QIODevice::WriteOnly))
+ selectedFile.write(fileContent);
+ }
+ };
+
+ auto dialogClosed = [=](int code) {
+ Q_UNUSED(code);
+ delete dialog;
+ };
+
+ connect(dialog, &QFileDialog::fileSelected, fileSelected);
+ connect(dialog, &QFileDialog::finished, dialogClosed);
+ dialog->show();
+#endif
+}
+
+/*!
This is a convenience static function that will return a file name selected
by the user. The file does not have to exist.
@@ -3372,6 +3420,18 @@ void QFileDialogPrivate::_q_goHome()
q->setDirectory(QDir::homePath());
}
+
+void QFileDialogPrivate::saveHistorySelection()
+{
+ if (qFileDialogUi.isNull() || currentHistoryLocation < 0 || currentHistoryLocation >= currentHistory.size())
+ return;
+ auto &item = currentHistory[currentHistoryLocation];
+ item.selection.clear();
+ const auto selectedIndexes = qFileDialogUi->listView->selectionModel()->selectedRows();
+ for (const auto &index : selectedIndexes)
+ item.selection.append(QPersistentModelIndex(index));
+}
+
/*!
\internal
@@ -3385,17 +3445,49 @@ void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
qFileDialogUi->sidebar->selectUrl(QUrl::fromLocalFile(newPath));
q->setHistory(qFileDialogUi->lookInCombo->history());
- if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation) != QDir::toNativeSeparators(newPath)) {
+ const QString newNativePath = QDir::toNativeSeparators(newPath);
+
+ // equal paths indicate this was invoked by _q_navigateBack/Forward()
+ if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation).path != newNativePath) {
+ if (currentHistoryLocation >= 0)
+ saveHistorySelection();
while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.count()) {
currentHistory.removeLast();
}
- currentHistory.append(QDir::toNativeSeparators(newPath));
+ currentHistory.append({newNativePath, PersistentModelIndexList()});
++currentHistoryLocation;
}
qFileDialogUi->forwardButton->setEnabled(currentHistory.size() - currentHistoryLocation > 1);
qFileDialogUi->backButton->setEnabled(currentHistoryLocation > 0);
}
+void QFileDialogPrivate::navigate(HistoryItem &historyItem)
+{
+ Q_Q(QFileDialog);
+ q->setDirectory(historyItem.path);
+ // Restore selection unless something has changed in the file system
+ if (qFileDialogUi.isNull() || historyItem.selection.isEmpty())
+ return;
+ if (std::any_of(historyItem.selection.cbegin(), historyItem.selection.cend(),
+ [](const QPersistentModelIndex &i) { return !i.isValid(); })) {
+ historyItem.selection.clear();
+ return;
+ }
+
+ QAbstractItemView *view = q->viewMode() == QFileDialog::List
+ ? static_cast<QAbstractItemView *>(qFileDialogUi->listView)
+ : static_cast<QAbstractItemView *>(qFileDialogUi->treeView);
+ auto selectionModel = view->selectionModel();
+ const QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Select
+ | QItemSelectionModel::Rows;
+ selectionModel->select(historyItem.selection.constFirst(),
+ flags | QItemSelectionModel::Clear | QItemSelectionModel::Current);
+ for (int i = 1, size = historyItem.selection.size(); i < size; ++i)
+ selectionModel->select(historyItem.selection.at(i), flags);
+
+ view->scrollTo(historyItem.selection.constFirst());
+}
+
/*!
\internal
@@ -3403,11 +3495,9 @@ void QFileDialogPrivate::_q_pathChanged(const QString &newPath)
*/
void QFileDialogPrivate::_q_navigateBackward()
{
- Q_Q(QFileDialog);
if (!currentHistory.isEmpty() && currentHistoryLocation > 0) {
- --currentHistoryLocation;
- QString previousHistory = currentHistory.at(currentHistoryLocation);
- q->setDirectory(previousHistory);
+ saveHistorySelection();
+ navigate(currentHistory[--currentHistoryLocation]);
}
}
@@ -3418,11 +3508,9 @@ void QFileDialogPrivate::_q_navigateBackward()
*/
void QFileDialogPrivate::_q_navigateForward()
{
- Q_Q(QFileDialog);
if (!currentHistory.isEmpty() && currentHistoryLocation < currentHistory.size() - 1) {
- ++currentHistoryLocation;
- QString nextHistory = currentHistory.at(currentHistoryLocation);
- q->setDirectory(nextHistory);
+ saveHistorySelection();
+ navigate(currentHistory[++currentHistoryLocation]);
}
}
@@ -3633,12 +3721,13 @@ void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
if (oldFiles.removeAll(idx) == 0)
newFiles.append(idx);
}
- for (int i = 0; i < newFiles.count(); ++i)
- select(newFiles.at(i));
- if (lineEdit()->hasFocus())
- for (int i = 0; i < oldFiles.count(); ++i)
- qFileDialogUi->listView->selectionModel()->select(oldFiles.at(i),
- QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
+ for (const auto &newFile : qAsConst(newFiles))
+ select(newFile);
+ if (lineEdit()->hasFocus()) {
+ auto *sm = qFileDialogUi->listView->selectionModel();
+ for (const auto &oldFile : qAsConst(oldFiles))
+ sm->select(oldFile, QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
+ }
}
}
@@ -3992,7 +4081,7 @@ bool QFileDialogPrivate::itemViewKeyboardEvent(QKeyEvent *event) {
return true;
case Qt::Key_Back:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
return false;
#endif
case Qt::Key_Left:
diff --git a/src/widgets/dialogs/qfiledialog.h b/src/widgets/dialogs/qfiledialog.h
index 95e03618ac..790f52f2e7 100644
--- a/src/widgets/dialogs/qfiledialog.h
+++ b/src/widgets/dialogs/qfiledialog.h
@@ -92,7 +92,9 @@ public:
ShowDirsOnly = 0x00000001,
DontResolveSymlinks = 0x00000002,
DontConfirmOverwrite = 0x00000004,
- DontUseSheet = 0x00000008,
+#if QT_DEPRECATED_SINCE(5, 14)
+ DontUseSheet Q_DECL_ENUMERATOR_DEPRECATED = 0x00000008,
+#endif
DontUseNativeDialog = 0x00000010,
ReadOnly = 0x00000020,
HideNameFilterDetails = 0x00000040,
@@ -282,6 +284,7 @@ public:
static void getOpenFileContent(const QString &nameFilter,
const std::function<void(const QString &, const QByteArray &)> &fileContentsReady);
+ static void saveFileContent(const QByteArray &fileContent, const QString &fileNameHint = QString());
protected:
QFileDialog(const QFileDialogArgs &args);
diff --git a/src/widgets/dialogs/qfiledialog_p.h b/src/widgets/dialogs/qfiledialog_p.h
index 463c77aa23..dcf147348f 100644
--- a/src/widgets/dialogs/qfiledialog_p.h
+++ b/src/widgets/dialogs/qfiledialog_p.h
@@ -98,7 +98,7 @@ class QPlatformDialogHelper;
struct QFileDialogArgs
{
- QFileDialogArgs() : parent(0), mode(QFileDialog::AnyFile) {}
+ QFileDialogArgs() : parent(nullptr), mode(QFileDialog::AnyFile) {}
QWidget *parent;
QString caption;
@@ -116,6 +116,14 @@ class Q_WIDGETS_EXPORT QFileDialogPrivate : public QDialogPrivate
Q_DECLARE_PUBLIC(QFileDialog)
public:
+ using PersistentModelIndexList = QVector<QPersistentModelIndex>;
+
+ struct HistoryItem
+ {
+ QString path;
+ PersistentModelIndexList selection;
+ };
+
QFileDialogPrivate();
QPlatformFileDialogHelper *platformFileDialogHelper() const
@@ -193,9 +201,11 @@ public:
void retranslateWindowTitle();
void retranslateStrings();
void emitFilesSelected(const QStringList &files);
+ void saveHistorySelection();
void _q_goHome();
void _q_pathChanged(const QString &);
+ void navigate(HistoryItem &);
void _q_navigateBackward();
void _q_navigateForward();
void _q_navigateToParent();
@@ -237,7 +247,7 @@ public:
QString setWindowTitle;
- QStringList currentHistory;
+ QList<HistoryItem> currentHistory;
int currentHistoryLocation;
QAction *renameAction;
@@ -292,7 +302,7 @@ private:
class QFileDialogLineEdit : public QLineEdit
{
public:
- QFileDialogLineEdit(QWidget *parent = 0) : QLineEdit(parent), d_ptr(0){}
+ QFileDialogLineEdit(QWidget *parent = nullptr) : QLineEdit(parent), d_ptr(nullptr){}
void setFileDialogPrivate(QFileDialogPrivate *d_pointer) {d_ptr = d_pointer; }
void keyPressEvent(QKeyEvent *e) override;
bool hideOnEsc;
@@ -303,7 +313,7 @@ private:
class QFileDialogComboBox : public QComboBox
{
public:
- QFileDialogComboBox(QWidget *parent = 0) : QComboBox(parent), urlModel(0) {}
+ QFileDialogComboBox(QWidget *parent = nullptr) : QComboBox(parent), urlModel(nullptr) {}
void setFileDialogPrivate(QFileDialogPrivate *d_pointer);
void showPopup() override;
void setHistory(const QStringList &paths);
@@ -319,7 +329,7 @@ private:
class QFileDialogListView : public QListView
{
public:
- QFileDialogListView(QWidget *parent = 0);
+ QFileDialogListView(QWidget *parent = nullptr);
void setFileDialogPrivate(QFileDialogPrivate *d_pointer);
QSize sizeHint() const override;
protected:
diff --git a/src/widgets/dialogs/qfileinfogatherer.cpp b/src/widgets/dialogs/qfileinfogatherer.cpp
index 1e03ad8b06..0beca82f28 100644
--- a/src/widgets/dialogs/qfileinfogatherer.cpp
+++ b/src/widgets/dialogs/qfileinfogatherer.cpp
@@ -54,12 +54,12 @@ QT_BEGIN_NAMESPACE
static QBasicAtomicInt fetchedRoot = Q_BASIC_ATOMIC_INITIALIZER(false);
Q_AUTOTEST_EXPORT void qt_test_resetFetchedRoot()
{
- fetchedRoot.store(false);
+ fetchedRoot.storeRelaxed(false);
}
Q_AUTOTEST_EXPORT bool qt_test_isFetchedRoot()
{
- return fetchedRoot.load();
+ return fetchedRoot.loadRelaxed();
}
#endif
@@ -79,30 +79,9 @@ static QString translateDriveName(const QFileInfo &drive)
Creates thread
*/
QFileInfoGatherer::QFileInfoGatherer(QObject *parent)
- : QThread(parent), abort(false),
-#if QT_CONFIG(filesystemwatcher)
- watcher(0),
-#endif
-#ifdef Q_OS_WIN
- m_resolveSymlinks(true),
-#endif
- m_iconProvider(&defaultProvider)
+ : QThread(parent)
+ , m_iconProvider(&defaultProvider)
{
-#if QT_CONFIG(filesystemwatcher)
- watcher = new QFileSystemWatcher(this);
- connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(list(QString)));
- connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFile(QString)));
-
-# if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- const QVariant listener = watcher->property("_q_driveListener");
- if (listener.canConvert<QObject *>()) {
- if (QObject *driveListener = listener.value<QObject *>()) {
- connect(driveListener, SIGNAL(driveAdded()), this, SLOT(driveAdded()));
- connect(driveListener, SIGNAL(driveRemoved()), this, SLOT(driveRemoved()));
- }
- }
-# endif // Q_OS_WIN && !Q_OS_WINRT
-#endif
start(LowPriority);
}
@@ -111,7 +90,7 @@ QFileInfoGatherer::QFileInfoGatherer(QObject *parent)
*/
QFileInfoGatherer::~QFileInfoGatherer()
{
- abort.store(true);
+ abort.storeRelaxed(true);
QMutexLocker locker(&mutex);
condition.wakeAll();
locker.unlock();
@@ -183,8 +162,8 @@ void QFileInfoGatherer::fetchExtendedInformation(const QString &path, const QStr
if (files.isEmpty()
&& !path.isEmpty()
&& !path.startsWith(QLatin1String("//")) /*don't watch UNC path*/) {
- if (!watcher->directories().contains(path))
- watcher->addPath(path);
+ if (!watchedDirectories().contains(path))
+ watchPaths(QStringList(path));
}
#endif
}
@@ -201,6 +180,91 @@ void QFileInfoGatherer::updateFile(const QString &filePath)
fetchExtendedInformation(dir, QStringList(fileName));
}
+QStringList QFileInfoGatherer::watchedFiles() const
+{
+#if QT_CONFIG(filesystemwatcher)
+ if (m_watcher)
+ return m_watcher->files();
+#endif
+ return {};
+}
+
+QStringList QFileInfoGatherer::watchedDirectories() const
+{
+#if QT_CONFIG(filesystemwatcher)
+ if (m_watcher)
+ return m_watcher->directories();
+#endif
+ return {};
+}
+
+void QFileInfoGatherer::createWatcher()
+{
+#if QT_CONFIG(filesystemwatcher)
+ m_watcher = new QFileSystemWatcher(this);
+ connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &QFileInfoGatherer::list);
+ connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &QFileInfoGatherer::updateFile);
+# if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+ const QVariant listener = m_watcher->property("_q_driveListener");
+ if (listener.canConvert<QObject *>()) {
+ if (QObject *driveListener = listener.value<QObject *>()) {
+ connect(driveListener, SIGNAL(driveAdded()), this, SLOT(driveAdded()));
+ connect(driveListener, SIGNAL(driveRemoved()), this, SLOT(driveRemoved()));
+ }
+ }
+# endif // Q_OS_WIN && !Q_OS_WINRT
+#endif
+}
+
+void QFileInfoGatherer::watchPaths(const QStringList &paths)
+{
+#if QT_CONFIG(filesystemwatcher)
+ if (m_watching) {
+ if (m_watcher == nullptr)
+ createWatcher();
+ m_watcher->addPaths(paths);
+ }
+#else
+ Q_UNUSED(paths);
+#endif
+}
+
+void QFileInfoGatherer::unwatchPaths(const QStringList &paths)
+{
+#if QT_CONFIG(filesystemwatcher)
+ if (m_watcher)
+ m_watcher->removePaths(paths);
+#else
+ Q_UNUSED(paths);
+#endif
+}
+
+bool QFileInfoGatherer::isWatching() const
+{
+ bool result = false;
+#if QT_CONFIG(filesystemwatcher)
+ QMutexLocker locker(&mutex);
+ result = m_watching;
+#endif
+ return result;
+}
+
+void QFileInfoGatherer::setWatching(bool v)
+{
+#if QT_CONFIG(filesystemwatcher)
+ QMutexLocker locker(&mutex);
+ if (v != m_watching) {
+ if (!v) {
+ delete m_watcher;
+ m_watcher = nullptr;
+ }
+ m_watching = v;
+ }
+#else
+ Q_UNUSED(v);
+#endif
+}
+
/*
List all files in \a directoryPath
@@ -210,8 +274,8 @@ void QFileInfoGatherer::clear()
{
#if QT_CONFIG(filesystemwatcher)
QMutexLocker locker(&mutex);
- watcher->removePaths(watcher->files());
- watcher->removePaths(watcher->directories());
+ unwatchPaths(watchedFiles());
+ unwatchPaths(watchedDirectories());
#endif
}
@@ -224,7 +288,7 @@ void QFileInfoGatherer::removePath(const QString &path)
{
#if QT_CONFIG(filesystemwatcher)
QMutexLocker locker(&mutex);
- watcher->removePath(path);
+ unwatchPaths(QStringList(path));
#else
Q_UNUSED(path);
#endif
@@ -247,9 +311,9 @@ void QFileInfoGatherer::run()
{
forever {
QMutexLocker locker(&mutex);
- while (!abort.load() && path.isEmpty())
+ while (!abort.loadRelaxed() && path.isEmpty())
condition.wait(&mutex);
- if (abort.load())
+ if (abort.loadRelaxed())
return;
const QString thisPath = qAsConst(path).front();
path.pop_front();
@@ -271,12 +335,13 @@ QExtendedInformation QFileInfoGatherer::getInfo(const QFileInfo &fileInfo) const
static const bool watchFiles = qEnvironmentVariableIsSet("QT_FILESYSTEMMODEL_WATCH_FILES");
if (watchFiles) {
if (!fileInfo.exists() && !fileInfo.isSymLink()) {
- watcher->removePath(fileInfo.absoluteFilePath());
+ const_cast<QFileInfoGatherer *>(this)->
+ unwatchPaths(QStringList(fileInfo.absoluteFilePath()));
} else {
const QString path = fileInfo.absoluteFilePath();
if (!path.isEmpty() && fileInfo.exists() && fileInfo.isFile() && fileInfo.isReadable()
- && !watcher->files().contains(path)) {
- watcher->addPath(path);
+ && !watchedFiles().contains(path)) {
+ const_cast<QFileInfoGatherer *>(this)->watchPaths(QStringList(path));
}
}
}
@@ -303,7 +368,7 @@ void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &fil
// List drives
if (path.isEmpty()) {
#ifdef QT_BUILD_INTERNAL
- fetchedRoot.store(true);
+ fetchedRoot.storeRelaxed(true);
#endif
QFileInfoList infoList;
if (files.isEmpty()) {
@@ -332,7 +397,7 @@ void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &fil
QStringList allFiles;
if (files.isEmpty()) {
QDirIterator dirIt(path, QDir::AllEntries | QDir::System | QDir::Hidden);
- while (!abort.load() && dirIt.hasNext()) {
+ while (!abort.loadRelaxed() && dirIt.hasNext()) {
dirIt.next();
fileInfo = dirIt.fileInfo();
allFiles.append(fileInfo.fileName());
@@ -343,7 +408,7 @@ void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &fil
emit newListOfFiles(path, allFiles);
QStringList::const_iterator filesIt = filesToCheck.constBegin();
- while (!abort.load() && filesIt != filesToCheck.constEnd()) {
+ while (!abort.loadRelaxed() && filesIt != filesToCheck.constEnd()) {
fileInfo.setFile(path + QDir::separator() + *filesIt);
++filesIt;
fetch(fileInfo, base, firstTime, updatedFiles, path);
diff --git a/src/widgets/dialogs/qfileinfogatherer_p.h b/src/widgets/dialogs/qfileinfogatherer_p.h
index 134a14b7ce..3d30a98d04 100644
--- a/src/widgets/dialogs/qfileinfogatherer_p.h
+++ b/src/widgets/dialogs/qfileinfogatherer_p.h
@@ -166,15 +166,16 @@ Q_SIGNALS:
void directoryLoaded(const QString &path);
public:
- explicit QFileInfoGatherer(QObject *parent = 0);
+ explicit QFileInfoGatherer(QObject *parent = nullptr);
~QFileInfoGatherer();
-#if QT_CONFIG(filesystemwatcher) && defined(Q_OS_WIN)
- QStringList watchedFiles() const { return watcher->files(); }
- QStringList watchedDirectories() const { return watcher->directories(); }
- void watchPaths(const QStringList &paths) { watcher->addPaths(paths); }
- void unwatchPaths(const QStringList &paths) { watcher->removePaths(paths); }
-#endif // filesystemwatcher && Q_OS_WIN
+ QStringList watchedFiles() const;
+ QStringList watchedDirectories() const;
+ void watchPaths(const QStringList &paths);
+ void unwatchPaths(const QStringList &paths);
+
+ bool isWatching() const;
+ void setWatching(bool v);
// only callable from this->thread():
void clear();
@@ -201,6 +202,8 @@ private:
void fetch(const QFileInfo &info, QElapsedTimer &base, bool &firstTime, QVector<QPair<QString, QFileInfo> > &updatedFiles, const QString &path);
private:
+ void createWatcher();
+
mutable QMutex mutex;
// begin protected by mutex
QWaitCondition condition;
@@ -210,13 +213,16 @@ private:
QAtomicInt abort;
#if QT_CONFIG(filesystemwatcher)
- QFileSystemWatcher *watcher;
-#endif
-#ifdef Q_OS_WIN
- bool m_resolveSymlinks; // not accessed by run()
+ QFileSystemWatcher *m_watcher = nullptr;
#endif
QFileIconProvider *m_iconProvider; // not accessed by run()
QFileIconProvider defaultProvider;
+#ifdef Q_OS_WIN
+ bool m_resolveSymlinks = true; // not accessed by run()
+#endif
+#if QT_CONFIG(filesystemwatcher)
+ bool m_watching = true;
+#endif
};
QT_END_NAMESPACE
diff --git a/src/widgets/dialogs/qfilesystemmodel.cpp b/src/widgets/dialogs/qfilesystemmodel.cpp
index e486037e08..a04189513a 100644
--- a/src/widgets/dialogs/qfilesystemmodel.cpp
+++ b/src/widgets/dialogs/qfilesystemmodel.cpp
@@ -57,6 +57,9 @@
#ifdef Q_OS_WIN
# include <QtCore/QVarLengthArray>
# include <qt_windows.h>
+# ifndef Q_OS_WINRT
+# include <shlobj.h>
+# endif
#endif
QT_BEGIN_NAMESPACE
@@ -227,11 +230,9 @@ bool QFileSystemModel::remove(const QModelIndex &aindex)
/*!
Constructs a file system model with the given \a parent.
*/
-QFileSystemModel::QFileSystemModel(QObject *parent)
- : QAbstractItemModel(*new QFileSystemModelPrivate, parent)
+QFileSystemModel::QFileSystemModel(QObject *parent) :
+ QFileSystemModel(*new QFileSystemModelPrivate, parent)
{
- Q_D(QFileSystemModel);
- d->init();
}
/*!
@@ -247,9 +248,7 @@ QFileSystemModel::QFileSystemModel(QFileSystemModelPrivate &dd, QObject *parent)
/*!
Destroys this file system model.
*/
-QFileSystemModel::~QFileSystemModel()
-{
-}
+QFileSystemModel::~QFileSystemModel() = default;
/*!
\reimp
@@ -841,8 +840,8 @@ QString QFileSystemModelPrivate::displayName(const QModelIndex &index) const
{
#if defined(Q_OS_WIN)
QFileSystemNode *dirNode = node(index);
- if (!dirNode->volumeName.isNull())
- return dirNode->volumeName + QLatin1String(" (") + name(index) + QLatin1Char(')');
+ if (!dirNode->volumeName.isEmpty())
+ return dirNode->volumeName;
#endif
return name(index);
}
@@ -1268,6 +1267,107 @@ Qt::DropActions QFileSystemModel::supportedDropActions() const
}
/*!
+ \enum QFileSystemModel::Option
+ \since 5.14
+
+ \value DontWatchForChanges Do not add file watchers to the paths.
+ This reduces overhead when using the model for simple tasks
+ like line edit completion.
+
+ \value DontResolveSymlinks Don't resolve symlinks in the file
+ system model. By default, symlinks are resolved.
+
+ \value DontUseCustomDirectoryIcons Always use the default directory icon.
+ Some platforms allow the user to set a different icon. Custom icon lookup
+ causes a big performance impact over network or removable drives.
+ This sets the QFileIconProvider::DontUseCustomDirectoryIcons
+ option in the icon provider accordingly.
+
+ \sa resolveSymlinks
+*/
+
+/*!
+ \since 5.14
+ Sets the given \a option to be enabled if \a on is true; otherwise,
+ clears the given \a option.
+
+ Options should be set before changing properties.
+
+ \sa options, testOption()
+*/
+void QFileSystemModel::setOption(Option option, bool on)
+{
+ QFileSystemModel::Options previousOptions = options();
+ setOptions(previousOptions.setFlag(option, on));
+}
+
+/*!
+ \since 5.14
+
+ Returns \c true if the given \a option is enabled; otherwise, returns
+ false.
+
+ \sa options, setOption()
+*/
+bool QFileSystemModel::testOption(Option option) const
+{
+ return options().testFlag(option);
+}
+
+/*!
+ \property QFileSystemModel::options
+ \brief the various options that affect the model
+ \since 5.14
+
+ By default, all options are disabled.
+
+ Options should be set before changing properties.
+
+ \sa setOption(), testOption()
+*/
+void QFileSystemModel::setOptions(Options options)
+{
+ const Options changed = (options ^ QFileSystemModel::options());
+
+ if (changed.testFlag(DontResolveSymlinks))
+ setResolveSymlinks(!options.testFlag(DontResolveSymlinks));
+
+#if QT_CONFIG(filesystemwatcher)
+ Q_D(QFileSystemModel);
+ if (changed.testFlag(DontWatchForChanges))
+ d->fileInfoGatherer.setWatching(!options.testFlag(DontWatchForChanges));
+#endif
+
+ if (changed.testFlag(DontUseCustomDirectoryIcons)) {
+ if (auto provider = iconProvider()) {
+ QFileIconProvider::Options providerOptions = provider->options();
+ providerOptions.setFlag(QFileIconProvider::DontUseCustomDirectoryIcons,
+ options.testFlag(QFileSystemModel::DontUseCustomDirectoryIcons));
+ provider->setOptions(providerOptions);
+ } else {
+ qWarning("Setting QFileSystemModel::DontUseCustomDirectoryIcons has no effect when no provider is used");
+ }
+ }
+}
+
+QFileSystemModel::Options QFileSystemModel::options() const
+{
+ QFileSystemModel::Options result;
+ result.setFlag(DontResolveSymlinks, !resolveSymlinks());
+#if QT_CONFIG(filesystemwatcher)
+ Q_D(const QFileSystemModel);
+ result.setFlag(DontWatchForChanges, !d->fileInfoGatherer.isWatching());
+#else
+ result.setFlag(DontWatchForChanges);
+#endif
+ if (auto provider = iconProvider()) {
+ result.setFlag(DontUseCustomDirectoryIcons,
+ provider->options().testFlag(QFileIconProvider::DontUseCustomDirectoryIcons));
+ }
+ return result;
+}
+
+/*!
Returns the path of the item stored in the model under the
\a index given.
*/
@@ -1390,7 +1490,7 @@ QModelIndex QFileSystemModel::setRootPath(const QString &newPath)
if (d->rootDir.path() == longNewPath)
return d->index(rootPath());
- bool showDrives = (longNewPath.isEmpty() || longNewPath == d->myComputer());
+ bool showDrives = (longNewPath.isEmpty() || longNewPath == QFileSystemModelPrivate::myComputer());
if (!showDrives && !newPathDir.exists())
return d->index(rootPath());
@@ -1513,6 +1613,8 @@ QDir::Filters QFileSystemModel::filter() const
This is only relevant on Windows.
By default, this property is \c true.
+
+ \sa QFileSystemModel::Options
*/
void QFileSystemModel::setResolveSymlinks(bool enable)
{
@@ -1674,6 +1776,27 @@ void QFileSystemModelPrivate::_q_directoryChanged(const QString &directory, cons
removeNode(parentNode, toRemove[i]);
}
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
+static QString volumeName(const QString &path)
+{
+ IShellItem *item = nullptr;
+ const QString native = QDir::toNativeSeparators(path);
+ HRESULT hr = SHCreateItemFromParsingName(reinterpret_cast<const wchar_t *>(native.utf16()),
+ nullptr, IID_IShellItem,
+ reinterpret_cast<void **>(&item));
+ if (FAILED(hr))
+ return QString();
+ LPWSTR name = nullptr;
+ hr = item->GetDisplayName(SIGDN_NORMALDISPLAY, &name);
+ if (FAILED(hr))
+ return QString();
+ QString result = QString::fromWCharArray(name);
+ CoTaskMemFree(name);
+ item->Release();
+ return result;
+}
+#endif // Q_OS_WIN && !Q_OS_WINRT
+
/*!
\internal
@@ -1692,15 +1815,8 @@ QFileSystemModelPrivate::QFileSystemNode* QFileSystemModelPrivate::addNode(QFile
#endif
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
//The parentNode is "" so we are listing the drives
- if (parentNode->fileName.isEmpty()) {
- wchar_t name[MAX_PATH + 1];
- //GetVolumeInformation requires to add trailing backslash
- const QString nodeName = fileName + QLatin1String("\\");
- BOOL success = ::GetVolumeInformation((wchar_t *)(nodeName.utf16()),
- name, MAX_PATH + 1, NULL, 0, NULL, NULL, 0);
- if (success && name[0])
- node->volumeName = QString::fromWCharArray(name);
- }
+ if (parentNode->fileName.isEmpty())
+ node->volumeName = volumeName(fileName);
#endif
Q_ASSERT(!parentNode->children.contains(fileName));
parentNode->children.insert(fileName, node);
@@ -1847,8 +1963,7 @@ void QFileSystemModelPrivate::_q_fileSystemChanged(const QString &path, const QV
std::sort(rowsToUpdate.begin(), rowsToUpdate.end());
QString min;
QString max;
- for (int i = 0; i < rowsToUpdate.count(); ++i) {
- QString value = rowsToUpdate.at(i);
+ for (const QString &value : qAsConst(rowsToUpdate)) {
//##TODO is there a way to bundle signals with QString as the content of the list?
/*if (min.isEmpty()) {
min = value;
@@ -1946,6 +2061,9 @@ QStringList QFileSystemModelPrivate::unwatchPathsAt(const QModelIndex &index)
void QFileSystemModelPrivate::init()
{
Q_Q(QFileSystemModel);
+
+ delayedSortTimer.setSingleShot(true);
+
qRegisterMetaType<QVector<QPair<QString,QFileInfo> > >();
#if QT_CONFIG(filesystemwatcher)
q->connect(&fileInfoGatherer, SIGNAL(newListOfFiles(QString,QStringList)),
diff --git a/src/widgets/dialogs/qfilesystemmodel.h b/src/widgets/dialogs/qfilesystemmodel.h
index c2c8b8818e..b0f289dfcd 100644
--- a/src/widgets/dialogs/qfilesystemmodel.h
+++ b/src/widgets/dialogs/qfilesystemmodel.h
@@ -61,6 +61,7 @@ class Q_WIDGETS_EXPORT QFileSystemModel : public QAbstractItemModel
Q_PROPERTY(bool resolveSymlinks READ resolveSymlinks WRITE setResolveSymlinks)
Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
Q_PROPERTY(bool nameFilterDisables READ nameFilterDisables WRITE setNameFilterDisables)
+ Q_PROPERTY(Options options READ options WRITE setOptions)
Q_SIGNALS:
void rootPathChanged(const QString &newPath);
@@ -75,6 +76,15 @@ public:
FilePermissions = Qt::UserRole + 3
};
+ enum Option
+ {
+ DontWatchForChanges = 0x00000001,
+ DontResolveSymlinks = 0x00000002,
+ DontUseCustomDirectoryIcons = 0x00000004
+ };
+ Q_ENUM(Option)
+ Q_DECLARE_FLAGS(Options, Option)
+
explicit QFileSystemModel(QObject *parent = nullptr);
~QFileSystemModel();
@@ -129,6 +139,11 @@ public:
void setNameFilters(const QStringList &filters);
QStringList nameFilters() const;
+ void setOption(Option option, bool on = true);
+ bool testOption(Option option) const;
+ void setOptions(Options options);
+ Options options() const;
+
QString filePath(const QModelIndex &index) const;
bool isDir(const QModelIndex &index) const;
qint64 size(const QModelIndex &index) const;
@@ -165,6 +180,8 @@ inline QString QFileSystemModel::fileName(const QModelIndex &aindex) const
inline QIcon QFileSystemModel::fileIcon(const QModelIndex &aindex) const
{ return qvariant_cast<QIcon>(aindex.data(Qt::DecorationRole)); }
+Q_DECLARE_OPERATORS_FOR_FLAGS(QFileSystemModel::Options)
+
QT_END_NAMESPACE
#endif // QFILESYSTEMMODEL_H
diff --git a/src/widgets/dialogs/qfilesystemmodel_p.h b/src/widgets/dialogs/qfilesystemmodel_p.h
index 9c432e1ae6..844e417e2d 100644
--- a/src/widgets/dialogs/qfilesystemmodel_p.h
+++ b/src/widgets/dialogs/qfilesystemmodel_p.h
@@ -99,13 +99,13 @@ public:
class QFileSystemNode
{
public:
- explicit QFileSystemNode(const QString &filename = QString(), QFileSystemNode *p = 0)
- : fileName(filename), populatedChildren(false), isVisible(false), dirtyChildrenIndex(-1), parent(p), info(0) {}
+ Q_DISABLE_COPY_MOVE(QFileSystemNode)
+
+ explicit QFileSystemNode(const QString &filename = QString(), QFileSystemNode *p = nullptr)
+ : fileName(filename), parent(p) {}
~QFileSystemNode() {
qDeleteAll(children);
delete info;
- info = 0;
- parent = 0;
}
QString fileName;
@@ -116,7 +116,7 @@ public:
inline qint64 size() const { if (info && !info->isDir()) return info->size(); return 0; }
inline QString type() const { if (info) return info->displayType; return QLatin1String(""); }
inline QDateTime lastModified() const { if (info) return info->lastModified(); return QDateTime(); }
- inline QFile::Permissions permissions() const { if (info) return info->permissions(); return 0; }
+ inline QFile::Permissions permissions() const { if (info) return info->permissions(); return nullptr; }
inline bool isReadable() const { return ((permissions() & QFile::ReadUser) != 0); }
inline bool isWritable() const { return ((permissions() & QFile::WriteUser) != 0); }
inline bool isExecutable() const { return ((permissions() & QFile::ExeUser) != 0); }
@@ -162,7 +162,7 @@ public:
return info && (*info == fileInfo);
}
- inline bool hasInformation() const { return info != 0; }
+ inline bool hasInformation() const { return info != nullptr; }
void populate(const QExtendedInformation &fileInfo) {
if (!info)
@@ -204,31 +204,16 @@ public:
}
}
- bool populatedChildren;
- bool isVisible;
QHash<QFileSystemModelNodePathKey, QFileSystemNode *> children;
QList<QString> visibleChildren;
- int dirtyChildrenIndex;
+ QExtendedInformation *info = nullptr;
QFileSystemNode *parent;
-
-
- QExtendedInformation *info;
-
+ int dirtyChildrenIndex = -1;
+ bool populatedChildren = false;
+ bool isVisible = false;
};
- QFileSystemModelPrivate() :
- forceSort(true),
- sortColumn(0),
- sortOrder(Qt::AscendingOrder),
- readOnly(true),
- setRootPath(false),
- filters(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs),
- nameFilterDisables(true), // false on windows, true on mac and unix
- disableRecursiveSort(false)
- {
- delayedSortTimer.setSingleShot(true);
- }
-
+ QFileSystemModelPrivate() = default;
void init();
/*
\internal
@@ -303,18 +288,7 @@ public:
QFileInfoGatherer fileInfoGatherer;
#endif // filesystemwatcher
QTimer delayedSortTimer;
- bool forceSort;
- int sortColumn;
- Qt::SortOrder sortOrder;
- bool readOnly;
- bool setRootPath;
- QDir::Filters filters;
QHash<const QFileSystemNode*, bool> bypassFilters;
- bool nameFilterDisables;
- //This flag is an optimization for the QFileDialog
- //It enable a sort which is not recursive, it means
- //we sort only what we see.
- bool disableRecursiveSort;
#if QT_CONFIG(regularexpression)
QStringList nameFilters;
#endif
@@ -322,7 +296,6 @@ public:
QFileSystemNode root;
- QBasicTimer fetchingTimer;
struct Fetching {
QString dir;
QString file;
@@ -330,6 +303,18 @@ public:
};
QVector<Fetching> toFetch;
+ QBasicTimer fetchingTimer;
+
+ QDir::Filters filters = QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs;
+ int sortColumn = 0;
+ Qt::SortOrder sortOrder = Qt::AscendingOrder;
+ bool forceSort = true;
+ bool readOnly = true;
+ bool setRootPath = false;
+ bool nameFilterDisables = true; // false on windows, true on mac and unix
+ // This flag is an optimization for QFileDialog. It enables a sort which is
+ // not recursive, meaning we sort only what we see.
+ bool disableRecursiveSort = false;
};
Q_DECLARE_TYPEINFO(QFileSystemModelPrivate::Fetching, Q_MOVABLE_TYPE);
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index d53d57db86..7e3592e034 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -432,7 +432,7 @@ bool QFontDialog::eventFilter(QObject *o , QEvent *e)
k->key() == Qt::Key_PageDown)) {
int ci = d->sizeList->currentItem();
- (void)QApplication::sendEvent(d->sizeList, k);
+ QCoreApplication::sendEvent(d->sizeList, k);
if (ci != d->sizeList->currentItem()
&& style()->styleHint(QStyle::SH_FontDialog_SelectAssociatedText, 0, this))
@@ -680,7 +680,7 @@ void QFontDialogPrivate::updateSampleFont(const QFont &newFont)
void QFontDialogPrivate::_q_writingSystemHighlighted(int index)
{
writingSystem = QFontDatabase::WritingSystem(index);
- sampleEdit->setText(fdb.writingSystemSample(writingSystem));
+ sampleEdit->setText(QFontDatabase::writingSystemSample(writingSystem));
updateFamilies();
}
diff --git a/src/widgets/dialogs/qfscompleter_p.h b/src/widgets/dialogs/qfscompleter_p.h
index 3b829d4a52..f5110a7622 100644
--- a/src/widgets/dialogs/qfscompleter_p.h
+++ b/src/widgets/dialogs/qfscompleter_p.h
@@ -64,8 +64,8 @@ QT_BEGIN_NAMESPACE
*/
class Q_WIDGETS_EXPORT QFSCompleter : public QCompleter {
public:
- explicit QFSCompleter(QFileSystemModel *model, QObject *parent = 0)
- : QCompleter(model, parent), proxyModel(0), sourceModel(model)
+ explicit QFSCompleter(QFileSystemModel *model, QObject *parent = nullptr)
+ : QCompleter(model, parent), proxyModel(nullptr), sourceModel(model)
{
#if defined(Q_OS_WIN)
setCaseSensitivity(Qt::CaseInsensitive);
diff --git a/src/widgets/dialogs/qmessagebox.cpp b/src/widgets/dialogs/qmessagebox.cpp
index f143e3b527..8dad212692 100644
--- a/src/widgets/dialogs/qmessagebox.cpp
+++ b/src/widgets/dialogs/qmessagebox.cpp
@@ -1508,7 +1508,7 @@ void QMessageBox::keyPressEvent(QKeyEvent *e)
if (d->detailsText)
textToCopy += d->detailsText->text() + QLatin1Char('\n') + separator;
#endif
- QApplication::clipboard()->setText(textToCopy);
+ QGuiApplication::clipboard()->setText(textToCopy);
return;
}
#endif // Q_OS_WIN
@@ -2662,14 +2662,9 @@ QPixmap QMessageBoxPrivate::standardIcon(QMessageBox::Icon icon, QMessageBox *mb
break;
}
if (!tmpIcon.isNull()) {
- QWindow *window = nullptr;
- if (mb) {
- window = mb->windowHandle();
- if (!window) {
- if (const QWidget *nativeParent = mb->nativeParentWidget())
- window = nativeParent->windowHandle();
- }
- }
+ QWindow *window = mb
+ ? qt_widget_private(mb)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest)
+ : nullptr;
return tmpIcon.pixmap(window, QSize(iconSize, iconSize));
}
return QPixmap();
diff --git a/src/widgets/dialogs/qprogressdialog.cpp b/src/widgets/dialogs/qprogressdialog.cpp
index 078dd6463b..e1a6bce5b1 100644
--- a/src/widgets/dialogs/qprogressdialog.cpp
+++ b/src/widgets/dialogs/qprogressdialog.cpp
@@ -643,7 +643,7 @@ int QProgressDialog::value() const
\warning If the progress dialog is modal
(see QProgressDialog::QProgressDialog()),
- setValue() calls QApplication::processEvents(), so take care that
+ setValue() calls QCoreApplication::processEvents(), so take care that
this does not cause undesirable re-entrancy in your code. For example,
don't use a QProgressDialog inside a paintEvent()!
@@ -659,7 +659,7 @@ void QProgressDialog::setValue(int progress)
if (d->shown_once) {
if (isModal())
- QApplication::processEvents();
+ QCoreApplication::processEvents();
} else {
if ((!d->setValue_called && progress == 0 /* for compat with Qt < 5.4 */) || progress == minimum()) {
d->starttime.start();
diff --git a/src/widgets/dialogs/qsidebar_p.h b/src/widgets/dialogs/qsidebar_p.h
index 4a82f88878..6056f19452 100644
--- a/src/widgets/dialogs/qsidebar_p.h
+++ b/src/widgets/dialogs/qsidebar_p.h
@@ -67,7 +67,7 @@ class QFileSystemModel;
class QSideBarDelegate : public QStyledItemDelegate
{
public:
- QSideBarDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {}
+ QSideBarDelegate(QWidget *parent = nullptr) : QStyledItemDelegate(parent) {}
void initStyleOption(QStyleOptionViewItem *option,
const QModelIndex &index) const override;
};
@@ -82,7 +82,7 @@ public:
EnabledRole = Qt::UserRole + 2
};
- QUrlModel(QObject *parent = 0);
+ QUrlModel(QObject *parent = nullptr);
QStringList mimeTypes() const override;
QMimeData *mimeData(const QModelIndexList &indexes) const override;
@@ -127,7 +127,7 @@ Q_SIGNALS:
void goToUrl(const QUrl &url);
public:
- QSidebar(QWidget *parent = 0);
+ QSidebar(QWidget *parent = nullptr);
void setModelAndUrls(QFileSystemModel *model, const QList<QUrl> &newUrls);
~QSidebar();
diff --git a/src/widgets/dialogs/qwizard.cpp b/src/widgets/dialogs/qwizard.cpp
index 5ba48aeff3..0295241a74 100644
--- a/src/widgets/dialogs/qwizard.cpp
+++ b/src/widgets/dialogs/qwizard.cpp
@@ -1299,7 +1299,7 @@ void QWizardPrivate::updateMinMaxSizes(const QWizardLayoutInfo &info)
int extraHeight = 0;
#if QT_CONFIG(style_windowsvista)
if (isVistaThemeEnabled())
- extraHeight = vistaHelper->titleBarSize() + vistaHelper->topOffset();
+ extraHeight = vistaHelper->titleBarSize() + vistaHelper->topOffset(q);
#endif
QSize minimumSize = mainLayout->totalMinimumSize() + QSize(0, extraHeight);
QSize maximumSize = mainLayout->totalMaximumSize();
@@ -1565,23 +1565,25 @@ bool QWizardPrivate::handleAeroStyleChange()
bool vistaMargins = false;
if (isVistaThemeEnabled()) {
+ const int topOffset = vistaHelper->topOffset(q);
+ const int topPadding = vistaHelper->topPadding(q);
if (isVistaThemeEnabled(QVistaHelper::VistaAero)) {
if (isWindow) {
vistaHelper->setDWMTitleBar(QVistaHelper::ExtendedTitleBar);
q->installEventFilter(vistaHelper);
}
q->setMouseTracking(true);
- antiFlickerWidget->move(0, vistaHelper->titleBarSize() + vistaHelper->topOffset());
+ antiFlickerWidget->move(0, vistaHelper->titleBarSize() + topOffset);
vistaHelper->backButton()->move(
- 0, vistaHelper->topOffset() // ### should ideally work without the '+ 1'
- - qMin(vistaHelper->topOffset(), vistaHelper->topPadding() + 1));
+ 0, topOffset // ### should ideally work without the '+ 1'
+ - qMin(topOffset, topPadding + 1));
vistaMargins = true;
vistaHelper->backButton()->show();
} else {
if (isWindow)
vistaHelper->setDWMTitleBar(QVistaHelper::NormalTitleBar);
q->setMouseTracking(true);
- antiFlickerWidget->move(0, vistaHelper->topOffset());
+ antiFlickerWidget->move(0, topOffset);
vistaHelper->backButton()->move(0, -1); // ### should ideally work with (0, 0)
}
if (isWindow)
@@ -2545,7 +2547,7 @@ void QWizard::setWizardStyle(WizardStyle style)
//Send a resizeevent since the antiflicker widget probably needs a new size
//because of the backbutton in the window title
QResizeEvent ev(geometry().size(), geometry().size());
- QApplication::sendEvent(this, &ev);
+ QCoreApplication::sendEvent(this, &ev);
}
#endif
d->updateLayout();
@@ -3182,7 +3184,7 @@ void QWizard::resizeEvent(QResizeEvent *event)
int heightOffset = 0;
#if QT_CONFIG(style_windowsvista)
if (d->isVistaThemeEnabled()) {
- heightOffset = d->vistaHelper->topOffset();
+ heightOffset = d->vistaHelper->topOffset(this);
if (d->isVistaThemeEnabled(QVistaHelper::VistaAero))
heightOffset += d->vistaHelper->titleBarSize();
}
@@ -3214,7 +3216,7 @@ void QWizard::paintEvent(QPaintEvent * event)
if (d->isVistaThemeEnabled(QVistaHelper::VistaBasic)) {
QPainter painter(this);
QColor color = d->vistaHelper->basicWindowFrameColor();
- painter.fillRect(0, 0, width(), QVistaHelper::topOffset(), color);
+ painter.fillRect(0, 0, width(), QVistaHelper::topOffset(this), color);
}
d->vistaHelper->paintEvent(event);
}
@@ -3227,7 +3229,11 @@ void QWizard::paintEvent(QPaintEvent * event)
/*!
\reimp
*/
+# if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+bool QWizard::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
+# else
bool QWizard::nativeEvent(const QByteArray &eventType, void *message, long *result)
+# endif
{
#if QT_CONFIG(style_windowsvista)
Q_D(QWizard);
diff --git a/src/widgets/dialogs/qwizard.h b/src/widgets/dialogs/qwizard.h
index 0dd837b197..ef71efa0cb 100644
--- a/src/widgets/dialogs/qwizard.h
+++ b/src/widgets/dialogs/qwizard.h
@@ -188,7 +188,11 @@ protected:
void resizeEvent(QResizeEvent *event) override;
void paintEvent(QPaintEvent *event) override;
#if defined(Q_OS_WIN) || defined(Q_CLANG_QDOC)
+# if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
+# else
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
+# endif
#endif
void done(int result) override;
virtual void initializePage(int id);
diff --git a/src/widgets/dialogs/qwizard_win.cpp b/src/widgets/dialogs/qwizard_win.cpp
index aa9ad7f290..47ac41a791 100644
--- a/src/widgets/dialogs/qwizard_win.cpp
+++ b/src/widgets/dialogs/qwizard_win.cpp
@@ -87,7 +87,7 @@ QVistaBackButton::QVistaBackButton(QWidget *widget)
QSize QVistaBackButton::sizeHint() const
{
ensurePolished();
- int size = int(QStyleHelper::dpiScaled(32));
+ int size = int(QStyleHelper::dpiScaled(32, this));
int width = size, height = size;
return QSize(width, height);
}
@@ -156,7 +156,7 @@ QVistaHelper::QVistaHelper(QWizard *wizard)
backButton_ = new QVistaBackButton(wizard);
backButton_->hide();
- iconSpacing = QStyleHelper::dpiScaled(7);
+ iconSpacing = QStyleHelper::dpiScaled(7, wizard);
}
QVistaHelper::~QVistaHelper()
@@ -172,7 +172,7 @@ void QVistaHelper::updateCustomMargins(bool vistaMargins)
const QMargins customMarginsDp = vistaMargins
? QMargins(0, -titleBarSizeDp(), 0, 0)
: QMargins();
- const QVariant customMarginsV = qVariantFromValue(customMarginsDp);
+ const QVariant customMarginsV = QVariant::fromValue(customMarginsDp);
// The dynamic property takes effect when creating the platform window.
window->setProperty("_q_windowsCustomMargins", customMarginsV);
// If a platform window exists, change via native interface.
@@ -229,7 +229,7 @@ bool QVistaHelper::setDWMTitleBar(TitleBarChangeType type)
if (type == NormalTitleBar)
mar.cyTopHeight = 0;
else
- mar.cyTopHeight = (titleBarSize() + topOffset()) * QVistaHelper::m_devicePixelRatio;
+ mar.cyTopHeight = (titleBarSize() + topOffset(wizard)) * QVistaHelper::m_devicePixelRatio;
if (const HWND wizardHandle = wizardHWND())
if (SUCCEEDED(DwmExtendFrameIntoClientArea(wizardHandle, &mar)))
value = true;
@@ -275,7 +275,7 @@ void QVistaHelper::drawTitleBar(QPainter *painter)
if (vistaState() == VistaAero && isWindow)
drawBlackRect(QRect(0, 0, wizard->width(),
- titleBarSize() + topOffset()), hdc);
+ titleBarSize() + topOffset(wizard)), hdc);
// The button is positioned in QWizardPrivate::handleAeroStyleChange(),
// all calculation is relative to it.
const int btnTop = backButton_->mapToParent(QPoint()).y();
@@ -293,9 +293,9 @@ void QVistaHelper::drawTitleBar(QPainter *painter)
int glowOffset = 0;
if (vistaState() == VistaAero) {
- textHeight += 2 * glowSize();
- textWidth += 2 * glowSize();
- glowOffset = glowSize();
+ glowOffset = glowSize(wizard);
+ textHeight += 2 * glowOffset;
+ textWidth += 2 * glowOffset;
}
const int titleLeft = (wizard->layoutDirection() == Qt::LeftToRight
@@ -314,10 +314,10 @@ void QVistaHelper::drawTitleBar(QPainter *painter)
const QIcon windowIcon = wizard->windowIcon();
if (!windowIcon.isNull()) {
- const int size = QVistaHelper::iconSize();
+ const int size = QVistaHelper::iconSize(wizard);
const int iconLeft = (wizard->layoutDirection() == Qt::LeftToRight
- ? leftMargin()
- : wizard->width() - leftMargin() - size);
+ ? leftMargin(wizard)
+ : wizard->width() - leftMargin(wizard) - size);
const QPoint pos(origin.x() + iconLeft, origin.y() + verticalCenter - size / 2);
const QPoint posDp = pos * QVistaHelper::m_devicePixelRatio;
@@ -339,7 +339,11 @@ void QVistaHelper::setTitleBarIconAndCaptionVisible(bool visible)
SetWindowThemeAttribute(handle, WTA_NONCLIENT, &opt, sizeof(WTA_OPTIONS));
}
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+bool QVistaHelper::winEvent(MSG* msg, qintptr *result)
+#else
bool QVistaHelper::winEvent(MSG* msg, long* result)
+#endif
{
switch (msg->message) {
case WM_NCHITTEST: {
@@ -401,7 +405,11 @@ void QVistaHelper::mouseEvent(QEvent *event)
}
}
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+bool QVistaHelper::handleWinEvent(MSG *message, qintptr *result)
+#else
bool QVistaHelper::handleWinEvent(MSG *message, long *result)
+#endif
{
if (message->message == WM_THEMECHANGED || message->message == WM_DWMCOMPOSITIONCHANGED)
cachedVistaState = Dirty;
@@ -419,7 +427,7 @@ void QVistaHelper::resizeEvent(QResizeEvent * event)
{
Q_UNUSED(event);
rtTop = QRect (0, 0, wizard->width(), frameSize());
- int height = captionSize() + topOffset();
+ int height = captionSize() + topOffset(wizard);
if (vistaState() == VistaBasic)
height -= titleBarSize();
rtTitle = QRect (0, frameSize(), wizard->width(), height);
@@ -509,7 +517,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
if (event->type() == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ qintptr result;
+#else
long result;
+#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
@@ -523,7 +535,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ qintptr result;
+#else
long result;
+#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
@@ -538,7 +554,11 @@ bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ qintptr result;
+#else
long result;
+#endif
MSG msg;
msg.message = WM_NCHITTEST;
msg.wParam = 0;
@@ -617,7 +637,7 @@ bool QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const Q
RECT rctext ={0,0, rectDp.width(), rectDp.height()};
dto.dwFlags = DTT_COMPOSITED|DTT_GLOWSIZE;
- dto.iGlowSize = glowSize();
+ dto.iGlowSize = glowSize(wizard);
DrawThemeTextEx(hTheme, dcMem, 0, 0, reinterpret_cast<LPCWSTR>(text.utf16()), -1, uFormat, &rctext, &dto );
BitBlt(hdc, rectDp.left(), rectDp.top(), rectDp.width(), rectDp.height(), dcMem, 0, 0, SRCCOPY);
@@ -694,27 +714,27 @@ int QVistaHelper::captionSizeDp()
int QVistaHelper::titleOffset()
{
- int iconOffset = wizard ->windowIcon().isNull() ? 0 : iconSize() + iconSpacing;
- return leftMargin() + iconOffset;
+ int iconOffset = wizard ->windowIcon().isNull() ? 0 : iconSize(wizard) + iconSpacing;
+ return leftMargin(wizard) + iconOffset;
}
-int QVistaHelper::iconSize()
+int QVistaHelper::iconSize(const QPaintDevice *device)
{
- return QStyleHelper::dpiScaled(16); // Standard Aero
+ return QStyleHelper::dpiScaled(16, device); // Standard Aero
}
-int QVistaHelper::glowSize()
+int QVistaHelper::glowSize(const QPaintDevice *device)
{
- return QStyleHelper::dpiScaled(10);
+ return QStyleHelper::dpiScaled(10, device);
}
-int QVistaHelper::topOffset()
+int QVistaHelper::topOffset(const QPaintDevice *device)
{
if (vistaState() != VistaAero)
return titleBarSize() + 3;
static const int aeroOffset =
QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8 ?
- QStyleHelper::dpiScaled(4) : QStyleHelper::dpiScaled(13);
+ QStyleHelper::dpiScaled(4, device) : QStyleHelper::dpiScaled(13, device);
return aeroOffset + titleBarSize();
}
diff --git a/src/widgets/dialogs/qwizard_win_p.h b/src/widgets/dialogs/qwizard_win_p.h
index 02c5e52c2c..2469496b61 100644
--- a/src/widgets/dialogs/qwizard_win_p.h
+++ b/src/widgets/dialogs/qwizard_win_p.h
@@ -93,7 +93,11 @@ public:
bool setDWMTitleBar(TitleBarChangeType type);
void setTitleBarIconAndCaptionVisible(bool visible);
void mouseEvent(QEvent *event);
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ bool handleWinEvent(MSG *message, qintptr *result);
+#else
bool handleWinEvent(MSG *message, long *result);
+#endif
void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *event);
QVistaBackButton *backButton() const { return backButton_; }
@@ -104,10 +108,10 @@ public:
static VistaState vistaState();
static int titleBarSize() { return QVistaHelper::titleBarSizeDp() / QVistaHelper::m_devicePixelRatio; }
static int titleBarSizeDp() { return QVistaHelper::frameSizeDp() + QVistaHelper::captionSizeDp(); }
- static int topPadding() { // padding under text
- return int(QStyleHelper::dpiScaled(4));
+ static int topPadding(const QPaintDevice *device) { // padding under text
+ return int(QStyleHelper::dpiScaled(4, device));
}
- static int topOffset();
+ static int topOffset(const QPaintDevice *device);
static HDC backingStoreDC(const QWidget *wizard, QPoint *offset);
@@ -121,16 +125,22 @@ private:
static int captionSize() { return QVistaHelper::captionSizeDp() / QVistaHelper::m_devicePixelRatio; }
static int captionSizeDp();
- static int backButtonSize() { return int(QStyleHelper::dpiScaled(30)); }
- static int iconSize();
- static int glowSize();
- int leftMargin() { return backButton_->isVisible() ? backButtonSize() + iconSpacing : 0; }
+ static int backButtonSize(const QPaintDevice *device)
+ { return int(QStyleHelper::dpiScaled(30, device)); }
+ static int iconSize(const QPaintDevice *device);
+ static int glowSize(const QPaintDevice *device);
+ int leftMargin(const QPaintDevice *device)
+ { return backButton_->isVisible() ? backButtonSize(device) + iconSpacing : 0; }
int titleOffset();
void drawTitleBar(QPainter *painter);
void setMouseCursor(QPoint pos);
void collapseTopFrameStrut();
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ bool winEvent(MSG *message, qintptr *result);
+#else
bool winEvent(MSG *message, long *result);
+#endif
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
diff --git a/src/widgets/doc/snippets/code/doc_src_styles.cpp b/src/widgets/doc/snippets/code/doc_src_styles.cpp
index a70ed6b11d..3536be6e7b 100644
--- a/src/widgets/doc/snippets/code/doc_src_styles.cpp
+++ b/src/widgets/doc/snippets/code/doc_src_styles.cpp
@@ -81,11 +81,6 @@
state |= QStyle::State_MouseOver;
if (widget->window()->isActiveWindow())
state |= QStyle::State_Active;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QWidget *w); //qwidget_mac.cpp
- if (!(state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget))
- state &= ~QStyle::State_Enabled;
-#endif
#ifdef QT_KEYPAD_NAVIGATION
if (widget->hasEditFocus())
state |= QStyle::State_HasEditFocus;
diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
index 39aca459db..7ccd827a04 100644
--- a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
+++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp
@@ -155,3 +155,8 @@ auto fileOpenCompleted = [](const QString &fileName, const QByteArray &fileConte
}
QFileDialog::getOpenFileContent("Images (*.png *.xpm *.jpg)", fileContentReady);
//! [15]
+
+//! [16]
+QByteArray imageData; // obtained from e.g. QImage::save()
+QFileDialog::saveFile("myimage.png", imageData);
+//! [16]
diff --git a/src/widgets/doc/snippets/macmainwindow.mm b/src/widgets/doc/snippets/macmainwindow.mm
deleted file mode 100644
index c63796a3f2..0000000000
--- a/src/widgets/doc/snippets/macmainwindow.mm
+++ /dev/null
@@ -1,290 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "macmainwindow.h"
-#import <AppKit/AppKit.h>
-#include <QtGui>
-
-
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-
-//![0]
-SearchWidget::SearchWidget(QWidget *parent)
- : QMacCocoaViewContainer(0, parent)
-{
- // Many Cocoa objects create temporary autorelease objects,
- // so create a pool to catch them.
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
- // Create the NSSearchField, set it on the QCocoaViewContainer.
- NSSearchField *search = [[NSSearchField alloc] init];
- setCocoaView(search);
-
- // Use a Qt menu for the search field menu.
- QMenu *qtMenu = createMenu(this);
- NSMenu *nsMenu = qtMenu->macMenu(0);
- [[search cell] setSearchMenuTemplate:nsMenu];
-
- // Release our reference, since our super class takes ownership and we
- // don't need it anymore.
- [search release];
-
- // Clean up our pool as we no longer need it.
- [pool release];
-}
-//![0]
-
-SearchWidget::~SearchWidget()
-{
-}
-
-QSize SearchWidget::sizeHint() const
-{
- return QSize(150, 40);
-}
-
-QMenu *createMenu(QWidget *parent)
-{
- QMenu *searchMenu = new QMenu(parent);
-
- QAction * indexAction = searchMenu->addAction("Index Search");
- indexAction->setCheckable(true);
- indexAction->setChecked(true);
-
- QAction * fulltextAction = searchMenu->addAction("Full Text Search");
- fulltextAction->setCheckable(true);
-
- QActionGroup *searchActionGroup = new QActionGroup(parent);
- searchActionGroup->addAction(indexAction);
- searchActionGroup->addAction(fulltextAction);
- searchActionGroup->setExclusive(true);
-
- return searchMenu;
-}
-
-SearchWrapper::SearchWrapper(QWidget *parent)
-:QWidget(parent)
-{
- s = new SearchWidget(this);
- s->move(2,2);
- setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
-}
-
-QSize SearchWrapper::sizeHint() const
-{
- return s->sizeHint() + QSize(6, 2);
-}
-
-Spacer::Spacer(QWidget *parent)
-:QWidget(parent)
-{
- QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- setSizePolicy(sizePolicy);
-}
-
-QSize Spacer::sizeHint() const
-{
- return QSize(1, 1);
-}
-
-MacSplitterHandle::MacSplitterHandle(Qt::Orientation orientation, QSplitter *parent)
-: QSplitterHandle(orientation, parent) { }
-
-// Paint the horizontal handle as a gradient, paint
-// the vertical handle as a line.
-void MacSplitterHandle::paintEvent(QPaintEvent *)
-{
- QPainter painter(this);
-
- QColor topColor(145, 145, 145);
- QColor bottomColor(142, 142, 142);
- QColor gradientStart(252, 252, 252);
- QColor gradientStop(223, 223, 223);
-
- if (orientation() == Qt::Vertical) {
- painter.setPen(topColor);
- painter.drawLine(0, 0, width(), 0);
- painter.setPen(bottomColor);
- painter.drawLine(0, height() - 1, width(), height() - 1);
-
- QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, height() -3));
- linearGrad.setColorAt(0, gradientStart);
- linearGrad.setColorAt(1, gradientStop);
- painter.fillRect(QRect(QPoint(0,1), size() - QSize(0, 2)), QBrush(linearGrad));
- } else {
- painter.setPen(topColor);
- painter.drawLine(0, 0, 0, height());
- }
-}
-
-QSize MacSplitterHandle::sizeHint() const
-{
- QSize parent = QSplitterHandle::sizeHint();
- if (orientation() == Qt::Vertical) {
- return parent + QSize(0, 3);
- } else {
- return QSize(1, parent.height());
- }
-}
-
-QSplitterHandle *MacSplitter::createHandle()
-{
- return new MacSplitterHandle(orientation(), this);
-}
-
-MacMainWindow::MacMainWindow()
-{
- QSettings settings;
- restoreGeometry(settings.value("Geometry").toByteArray());
-
- setWindowTitle("Mac Main Window");
-
- splitter = new MacSplitter();
-
- // Set up the left-hand side blue side bar.
- sidebar = new QTreeView();
- sidebar->setFrameStyle(QFrame::NoFrame);
- sidebar->setAttribute(Qt::WA_MacShowFocusRect, false);
- sidebar->setAutoFillBackground(true);
-
- // Set the palette.
- QPalette palette = sidebar->palette();
- QColor macSidebarColor(231, 237, 246);
- QColor macSidebarHighlightColor(168, 183, 205);
- palette.setColor(QPalette::Base, macSidebarColor);
- palette.setColor(QPalette::Highlight, macSidebarHighlightColor);
- sidebar->setPalette(palette);
-
- sidebar->setModel(createItemModel());
- sidebar->header()->hide();
- sidebar->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- sidebar->setTextElideMode(Qt::ElideMiddle);
-
- splitter->addWidget(sidebar);
-
- horizontalSplitter = new MacSplitter();
- horizontalSplitter->setOrientation(Qt::Vertical);
- splitter->addWidget(horizontalSplitter);
-
- splitter->setStretchFactor(0, 0);
- splitter->setStretchFactor(1, 1);
-
- // Set up the top document list view.
- documents = new QListView();
- documents->setFrameStyle(QFrame::NoFrame);
- documents->setAttribute(Qt::WA_MacShowFocusRect, false);
- documents->setModel(createDocumentModel());
- documents->setAlternatingRowColors(true);
- documents->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- horizontalSplitter->addWidget(documents);
- horizontalSplitter->setStretchFactor(0, 0);
-
- // Set up the text view.
- textedit = new QTextEdit();
- textedit->setFrameStyle(QFrame::NoFrame);
- textedit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
- textedit->setText("<br><br><br><br><br><br><center><b>This demo shows how to create a \
- Qt main window application that has the same appearance as other \
- OS X applications such as Mail or iTunes. This includes \
- customizing the item views and QSplitter and wrapping native widgets \
- such as the search field.</b></center>");
-
- horizontalSplitter->addWidget(textedit);
-
- setCentralWidget(splitter);
-
- toolBar = addToolBar(tr("Search"));
- toolBar->addWidget(new Spacer());
- toolBar->addWidget(new SearchWrapper());
-
- setUnifiedTitleAndToolBarOnMac(true);
-}
-
-MacMainWindow::~MacMainWindow()
-{
- QSettings settings;
- settings.setValue("Geometry", saveGeometry());
-}
-
-QAbstractItemModel *MacMainWindow::createItemModel()
-{
- QStandardItemModel *model = new QStandardItemModel();
- QStandardItem *parentItem = model->invisibleRootItem();
-
- QStandardItem *documentationItem = new QStandardItem("Documentation");
- parentItem->appendRow(documentationItem);
-
- QStandardItem *assistantItem = new QStandardItem("Qt MainWindow Manual");
- documentationItem->appendRow(assistantItem);
-
- QStandardItem *designerItem = new QStandardItem("Qt Designer Manual");
- documentationItem->appendRow(designerItem);
-
- QStandardItem *qtItem = new QStandardItem("Qt Reference Documentation");
- qtItem->appendRow(new QStandardItem("Classes"));
- qtItem->appendRow(new QStandardItem("Overviews"));
- qtItem->appendRow(new QStandardItem("Tutorial & Examples"));
- documentationItem->appendRow(qtItem);
-
- QStandardItem *bookmarksItem = new QStandardItem("Bookmarks");
- parentItem->appendRow(bookmarksItem);
- bookmarksItem->appendRow(new QStandardItem("QWidget"));
- bookmarksItem->appendRow(new QStandardItem("QObject"));
- bookmarksItem->appendRow(new QStandardItem("QWizard"));
-
- return model;
-}
-
-void MacMainWindow::resizeEvent(QResizeEvent *)
-{
- if (toolBar)
- toolBar->updateGeometry();
-}
-
-QAbstractItemModel *MacMainWindow::createDocumentModel()
-{
- QStandardItemModel *model = new QStandardItemModel();
- QStandardItem *parentItem = model->invisibleRootItem();
- parentItem->appendRow(new QStandardItem("QWidget Class Reference"));
- parentItem->appendRow(new QStandardItem("QObject Class Reference"));
- parentItem->appendRow(new QStandardItem("QListView Class Reference"));
-
- return model;
-}
-
-#endif
diff --git a/src/widgets/doc/snippets/timeline/main.cpp b/src/widgets/doc/snippets/timeline/main.cpp
index 74aa749254..4dfa2400d0 100644
--- a/src/widgets/doc/snippets/timeline/main.cpp
+++ b/src/widgets/doc/snippets/timeline/main.cpp
@@ -48,7 +48,7 @@
**
****************************************************************************/
-#include <QtGui>
+#include <QtWidgets>
#include <math.h>
int main(int argv, char *args[])
@@ -68,7 +68,7 @@ int main(int argv, char *args[])
for (int i = 0; i < 200; ++i)
animation->setPosAt(i / 200.0, QPointF(i, i));
- QGraphicsScene *scene = new QGraphicsScene();
+ QGraphicsScene *scene = new QGraphicsScene;
scene->setSceneRect(0, 0, 250, 250);
scene->addItem(ball);
diff --git a/src/widgets/doc/src/model-view-programming.qdoc b/src/widgets/doc/src/model-view-programming.qdoc
index 9335ff78c9..236582ef3f 100644
--- a/src/widgets/doc/src/model-view-programming.qdoc
+++ b/src/widgets/doc/src/model-view-programming.qdoc
@@ -1912,7 +1912,7 @@
\section3 Custom sorting models
- QSortFilterProxyModel instances use Qt's built-in qStableSort() function to set up
+ QSortFilterProxyModel instances use std::stable_sort() function to set up
mappings between items in the source model and those in the proxy model, allowing a
sorted hierarchy of items to be exposed to views without modifying the structure of the
source model. To provide custom sorting behavior, reimplement the
diff --git a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
index 12e27a71ad..c8f374a1b1 100644
--- a/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
+++ b/src/widgets/doc/src/widgets-and-layouts/stylesheet.qdoc
@@ -554,6 +554,10 @@
If the property references an enum declared with Q_ENUMS, you should
reference its constants by name, i.e., not their numeric value.
+ \note Use the qproperty syntax with care, as it modifies the
+ widget that is being painted. Also, the qproperty syntax is evaluated only
+ once, which is when the widget is polished by the style. This means that any
+ attempt to use them in pseudo-states such as QPushButton:hover, will not work.
*/
/*!
diff --git a/src/widgets/effects/qgraphicseffect_p.h b/src/widgets/effects/qgraphicseffect_p.h
index 2f3bd2f7fd..7e342a9f3c 100644
--- a/src/widgets/effects/qgraphicseffect_p.h
+++ b/src/widgets/effects/qgraphicseffect_p.h
@@ -80,11 +80,11 @@ public:
QRectF boundingRect(Qt::CoordinateSystem coordinateSystem = Qt::LogicalCoordinates) const;
QRect deviceRect() const;
QPixmap pixmap(Qt::CoordinateSystem system = Qt::LogicalCoordinates,
- QPoint *offset = 0,
+ QPoint *offset = nullptr,
QGraphicsEffect::PixmapPadMode mode = QGraphicsEffect::PadToEffectiveBoundingRect) const;
protected:
- QGraphicsEffectSource(QGraphicsEffectSourcePrivate &dd, QObject *parent = 0);
+ QGraphicsEffectSource(QGraphicsEffectSourcePrivate &dd, QObject *parent = nullptr);
private:
Q_DECLARE_PRIVATE(QGraphicsEffectSource)
@@ -125,7 +125,7 @@ public:
virtual void draw(QPainter *p) = 0;
virtual void update() = 0;
virtual bool isPixmap() const = 0;
- virtual QPixmap pixmap(Qt::CoordinateSystem system, QPoint *offset = 0,
+ virtual QPixmap pixmap(Qt::CoordinateSystem system, QPoint *offset = nullptr,
QGraphicsEffect::PixmapPadMode mode = QGraphicsEffect::PadToTransparentBorder) const = 0;
virtual void effectBoundingRectChanged() = 0;
@@ -149,7 +149,7 @@ class Q_WIDGETS_EXPORT QGraphicsEffectPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QGraphicsEffect)
public:
- QGraphicsEffectPrivate() : source(0), isEnabled(1) {}
+ QGraphicsEffectPrivate() : source(nullptr), isEnabled(1) {}
~QGraphicsEffectPrivate();
inline void setGraphicsEffectSource(QGraphicsEffectSource *newSource)
diff --git a/src/widgets/effects/qpixmapfilter_p.h b/src/widgets/effects/qpixmapfilter_p.h
index 0f582bde60..c56acb8a24 100644
--- a/src/widgets/effects/qpixmapfilter_p.h
+++ b/src/widgets/effects/qpixmapfilter_p.h
@@ -100,7 +100,7 @@ class Q_WIDGETS_EXPORT QPixmapConvolutionFilter : public QPixmapFilter
Q_DECLARE_PRIVATE(QPixmapConvolutionFilter)
public:
- QPixmapConvolutionFilter(QObject *parent = 0);
+ QPixmapConvolutionFilter(QObject *parent = nullptr);
~QPixmapConvolutionFilter();
void setConvolutionKernel(const qreal *matrix, int rows, int columns);
@@ -124,7 +124,7 @@ class Q_WIDGETS_EXPORT QPixmapBlurFilter : public QPixmapFilter
Q_DECLARE_PRIVATE(QPixmapBlurFilter)
public:
- QPixmapBlurFilter(QObject *parent = 0);
+ QPixmapBlurFilter(QObject *parent = nullptr);
~QPixmapBlurFilter();
void setRadius(qreal radius);
@@ -148,7 +148,7 @@ class Q_WIDGETS_EXPORT QPixmapColorizeFilter : public QPixmapFilter
Q_DECLARE_PRIVATE(QPixmapColorizeFilter)
public:
- QPixmapColorizeFilter(QObject *parent = 0);
+ QPixmapColorizeFilter(QObject *parent = nullptr);
~QPixmapColorizeFilter();
void setColor(const QColor& color);
@@ -168,7 +168,7 @@ class Q_WIDGETS_EXPORT QPixmapDropShadowFilter : public QPixmapFilter
Q_DECLARE_PRIVATE(QPixmapDropShadowFilter)
public:
- QPixmapDropShadowFilter(QObject *parent = 0);
+ QPixmapDropShadowFilter(QObject *parent = nullptr);
~QPixmapDropShadowFilter();
QRectF boundingRectFor(const QRectF &rect) const override;
diff --git a/src/widgets/graphicsview/graphicsview.pri b/src/widgets/graphicsview/graphicsview.pri
index 7d10244634..d69a6f5c3f 100644
--- a/src/widgets/graphicsview/graphicsview.pri
+++ b/src/widgets/graphicsview/graphicsview.pri
@@ -4,7 +4,6 @@ qtConfig(graphicsview) {
HEADERS += graphicsview/qgraphicsgridlayout.h \
graphicsview/qgraphicsitem.h \
graphicsview/qgraphicsitem_p.h \
- graphicsview/qgraphicsitemanimation.h \
graphicsview/qgraphicslayout.h \
graphicsview/qgraphicslayout_p.h \
graphicsview/qgraphicslayoutitem.h \
@@ -34,7 +33,6 @@ HEADERS += graphicsview/qgraphicsgridlayout.h \
SOURCES += graphicsview/qgraphicsgridlayout.cpp \
graphicsview/qgraphicsitem.cpp \
- graphicsview/qgraphicsitemanimation.cpp \
graphicsview/qgraphicslayout.cpp \
graphicsview/qgraphicslayout_p.cpp \
graphicsview/qgraphicslayoutitem.cpp \
@@ -55,4 +53,9 @@ SOURCES += graphicsview/qgraphicsgridlayout.cpp \
graphicsview/qsimplex_p.cpp \
graphicsview/qgraphicsanchorlayout_p.cpp \
graphicsview/qgraphicsanchorlayout.cpp
+
+ qtConfig(easingcurve) {
+ HEADERS += graphicsview/qgraphicsitemanimation.h
+ SOURCES += graphicsview/qgraphicsitemanimation.cpp
+ }
}
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
index 008560d856..4f44373cad 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp
@@ -2066,7 +2066,7 @@ QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints)
for (auto it = c->variables.cbegin(), end = c->variables.cend(); it != end; ++it)
variableSet.insert(static_cast<AnchorData *>(it.key()));
}
- return variableSet.toList();
+ return variableSet.values();
}
/*!
diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
index 699ca32bfe..b5f14948ac 100644
--- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
+++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.h
@@ -89,7 +89,7 @@ struct AnchorVertex {
: m_item(item), m_edge(edge), m_type(Normal) {}
AnchorVertex()
- : m_item(0), m_edge(Qt::AnchorPoint(0)), m_type(Normal) {}
+ : m_item(nullptr), m_edge(Qt::AnchorPoint(0)), m_type(Normal) {}
#ifdef QT_DEBUG
inline QString toString() const;
@@ -123,18 +123,18 @@ struct AnchorData : public QSimplexVariable {
};
AnchorData()
- : QSimplexVariable(), from(0), to(0),
+ : QSimplexVariable(), from(nullptr), to(nullptr),
minSize(0), prefSize(0), maxSize(0),
minPrefSize(0), maxPrefSize(0),
sizeAtMinimum(0), sizeAtPreferred(0),
- sizeAtMaximum(0), item(0), graphicsAnchor(0),
+ sizeAtMaximum(0), item(nullptr), graphicsAnchor(nullptr),
type(Normal), isLayoutAnchor(false),
isCenterAnchor(false), orientation(0),
dependency(Independent) {}
virtual ~AnchorData();
virtual void updateChildrenSizes() {}
- void refreshSizeHints(const QLayoutStyleInfo *styleInfo = 0);
+ void refreshSizeHints(const QLayoutStyleInfo *styleInfo = nullptr);
#ifdef QT_DEBUG
void dump(int indent = 2);
@@ -402,7 +402,7 @@ public:
static QGraphicsAnchorLayoutPrivate *get(QGraphicsAnchorLayout *q)
{
- return q ? q->d_func() : 0;
+ return q ? q->d_func() : nullptr;
}
static Qt::AnchorPoint oppositeEdge(
@@ -443,7 +443,7 @@ public:
Qt::AnchorPoint firstEdge,
QGraphicsLayoutItem *secondItem,
Qt::AnchorPoint secondEdge,
- qreal *spacing = 0);
+ qreal *spacing = nullptr);
// Helper for Anchor Manipulation methods
void addAnchor_helper(QGraphicsLayoutItem *firstItem,
diff --git a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
index 370df9eed7..e98160e40f 100644
--- a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
+++ b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h
@@ -68,7 +68,7 @@ class QGraphicsLayoutPrivate;
class QGraphicsGridLayoutEngineItem : public QGridLayoutItem {
public:
QGraphicsGridLayoutEngineItem(QGraphicsLayoutItem *item, int row, int columns, int rowSpan = 1, int columnSpan = 1,
- Qt::Alignment alignment = 0)
+ Qt::Alignment alignment = nullptr)
: QGridLayoutItem(row, columns, rowSpan, columnSpan, alignment), q_layoutItem(item) {}
virtual QLayoutPolicy::Policy sizePolicy(Qt::Orientation orientation) const override
@@ -115,7 +115,7 @@ public:
{
const int index = indexOf(layoutItem);
if (index < 0)
- return 0;
+ return nullptr;
return static_cast<QGraphicsGridLayoutEngineItem*>(q_items.at(index));
}
diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp
index 65708fa1ca..7c0f836156 100644
--- a/src/widgets/graphicsview/qgraphicsitem.cpp
+++ b/src/widgets/graphicsview/qgraphicsitem.cpp
@@ -449,8 +449,8 @@
\value ItemSendsGeometryChanges The item enables itemChange()
notifications for ItemPositionChange, ItemPositionHasChanged,
- ItemMatrixChange, ItemTransformChange, ItemTransformHasChanged,
- ItemRotationChange, ItemRotationHasChanged, ItemScaleChange, ItemScaleHasChanged,
+ ItemTransformChange, ItemTransformHasChanged, ItemRotationChange,
+ ItemRotationHasChanged, ItemScaleChange, ItemScaleHasChanged,
ItemTransformOriginPointChange, and ItemTransformOriginPointHasChanged. For
performance reasons, these notifications are disabled by default. You must
enable this flag to receive notifications for position and transform
@@ -4550,6 +4550,8 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co
}
#if QT_DEPRECATED_SINCE(5, 13)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
/*!
\obsolete
@@ -4588,6 +4590,7 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine)
// Send post-notification.
itemChange(ItemTransformHasChanged, QVariant::fromValue<QTransform>(newTransform));
}
+QT_WARNING_POP
#endif
/*!
@@ -7566,19 +7569,6 @@ void QGraphicsItem::setInputMethodHints(Qt::InputMethodHints hints)
*/
void QGraphicsItem::updateMicroFocus()
{
-#if !defined(QT_NO_IM) && 0 /* Used to be included in Qt4 for Q_WS_X11 */
- if (QWidget *fw = QApplication::focusWidget()) {
- if (scene()) {
- for (int i = 0 ; i < scene()->views().count() ; ++i) {
- if (scene()->views().at(i) == fw) {
- if (qApp)
- QGuiApplication::inputMethod()->update(Qt::ImQueryAll);
- break;
- }
- }
- }
- }
-#endif
}
/*!
@@ -11536,9 +11526,14 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change)
case QGraphicsItem::ItemFlagsHaveChanged:
str = "ItemFlagsHaveChanged";
break;
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
case QGraphicsItem::ItemMatrixChange:
str = "ItemMatrixChange";
break;
+QT_WARNING_POP
+#endif
case QGraphicsItem::ItemParentChange:
str = "ItemParentChange";
break;
diff --git a/src/widgets/graphicsview/qgraphicsitem.h b/src/widgets/graphicsview/qgraphicsitem.h
index 7dd4441ae9..d66a4917e5 100644
--- a/src/widgets/graphicsview/qgraphicsitem.h
+++ b/src/widgets/graphicsview/qgraphicsitem.h
@@ -110,8 +110,10 @@ public:
enum GraphicsItemChange {
ItemPositionChange,
- ItemMatrixChange,
- ItemVisibleChange,
+#if QT_DEPRECATED_SINCE(5, 14)
+ ItemMatrixChange Q_DECL_ENUMERATOR_DEPRECATED_X("Use ItemTransformChange instead"),
+#endif
+ ItemVisibleChange = 2,
ItemEnabledChange,
ItemSelectedChange,
ItemParentChange,
diff --git a/src/widgets/graphicsview/qgraphicsitem_p.h b/src/widgets/graphicsview/qgraphicsitem_p.h
index 54c25bf6e1..92d85f7125 100644
--- a/src/widgets/graphicsview/qgraphicsitem_p.h
+++ b/src/widgets/graphicsview/qgraphicsitem_p.h
@@ -78,13 +78,13 @@ public:
typedef void (*ClearFunction)(QDeclarativeListProperty<T> *);
QDeclarativeListProperty()
- : object(0), data(0), append(0), count(0), at(0), clear(0), dummy1(0), dummy2(0) {}
+ : object(nullptr), data(nullptr), append(nullptr), count(nullptr), at(nullptr), clear(nullptr), dummy1(nullptr), dummy2(nullptr) {}
QDeclarativeListProperty(QObject *o, QList<T *> &list)
: object(o), data(&list), append(qlist_append), count(qlist_count), at(qlist_at),
- clear(qlist_clear), dummy1(0), dummy2(0) {}
+ clear(qlist_clear), dummy1(nullptr), dummy2(nullptr) {}
QDeclarativeListProperty(QObject *o, void *d, AppendFunction a, CountFunction c = 0, AtFunction t = 0,
ClearFunction r = 0)
- : object(o), data(d), append(a), count(c), at(t), clear(r), dummy1(0), dummy2(0) {}
+ : object(o), data(d), append(a), count(c), at(t), clear(r), dummy1(nullptr), dummy2(nullptr) {}
bool operator==(const QDeclarativeListProperty &o) const {
return object == o.object &&
@@ -198,8 +198,8 @@ public:
|| (ancestorFlags & AncestorIgnoresTransformations);
}
- void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const;
- void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const;
+ void combineTransformToParent(QTransform *x, const QTransform *viewTransform = nullptr) const;
+ void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = nullptr) const;
virtual void updateSceneTransformFromParent();
static bool movableAncestorIsSelected(const QGraphicsItem *item);
@@ -232,7 +232,7 @@ public:
void childrenBoundingRectHelper(QTransform *x, QRectF *rect, QGraphicsItem *topMostEffectItem);
void initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform,
const QRegion &exposedRegion, bool allItems = false) const;
- QRectF effectiveBoundingRect(QGraphicsItem *topMostEffectItem = 0) const;
+ QRectF effectiveBoundingRect(QGraphicsItem *topMostEffectItem = nullptr) const;
QRectF sceneEffectiveBoundingRect() const;
QRectF effectiveBoundingRect(const QRectF &rect) const;
@@ -408,8 +408,8 @@ public:
void setFocusHelper(Qt::FocusReason focusReason, bool climb, bool focusFromHide);
void clearFocusHelper(bool giveFocusToParent, bool hiddenByParentPanel);
- void setSubFocus(QGraphicsItem *rootItem = 0, QGraphicsItem *stopItem = 0);
- void clearSubFocus(QGraphicsItem *rootItem = 0, QGraphicsItem *stopItem = 0);
+ void setSubFocus(QGraphicsItem *rootItem = nullptr, QGraphicsItem *stopItem = nullptr);
+ void clearSubFocus(QGraphicsItem *rootItem = nullptr, QGraphicsItem *stopItem = nullptr);
void resetFocusProxy();
virtual void subFocusItemChange();
virtual void focusScopeItemChange(bool isSubFocusItem);
@@ -541,7 +541,7 @@ struct QGraphicsItemPrivate::TransformData
onlyTransform(true)
{ }
- QTransform computedFullTransform(QTransform *postmultiplyTransform = 0) const
+ QTransform computedFullTransform(QTransform *postmultiplyTransform = nullptr) const
{
if (onlyTransform) {
if (!postmultiplyTransform || postmultiplyTransform->isIdentity())
@@ -595,12 +595,12 @@ class QGraphicsItemEffectSourcePrivate : public QGraphicsEffectSourcePrivate
{
public:
QGraphicsItemEffectSourcePrivate(QGraphicsItem *i)
- : QGraphicsEffectSourcePrivate(), item(i), info(0)
+ : QGraphicsEffectSourcePrivate(), item(i), info(nullptr)
{}
void detach() override
{
- item->d_ptr->graphicsEffect = 0;
+ item->d_ptr->graphicsEffect = nullptr;
item->prepareGeometryChange();
}
@@ -608,7 +608,7 @@ public:
{ return item; }
const QWidget *widget() const override
- { return 0; }
+ { return nullptr; }
void update() override {
item->d_ptr->updateDueToGraphicsEffect = true;
@@ -628,7 +628,7 @@ public:
}
const QStyleOption *styleOption() const override
- { return info ? info->option : 0; }
+ { return info ? info->option : nullptr; }
QRect deviceRect() const override
{
@@ -644,7 +644,7 @@ public:
QPixmap pixmap(Qt::CoordinateSystem system,
QPoint *offset,
QGraphicsEffect::PixmapPadMode mode) const override;
- QRectF paddedEffectRect(Qt::CoordinateSystem system, QGraphicsEffect::PixmapPadMode mode, const QRectF &sourceRect, bool *unpadded = 0) const;
+ QRectF paddedEffectRect(Qt::CoordinateSystem system, QGraphicsEffect::PixmapPadMode mode, const QRectF &sourceRect, bool *unpadded = nullptr) const;
QGraphicsItem *item;
QGraphicsItemPaintInfo *info;
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.cpp b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
index 78b91d5c39..ad77e2f260 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.cpp
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.cpp
@@ -115,7 +115,7 @@ public:
QGraphicsItem *item;
QPointF startPos;
- QMatrix startMatrix;
+ QTransform startTransform;
qreal step;
@@ -294,23 +294,38 @@ QList<QPair<qreal, QPointF> > QGraphicsItemAnimation::posList() const
return list;
}
+#if QT_DEPRECATED_SINCE(5, 14)
/*!
Returns the matrix used to transform the item at the specified \a step value.
+
+ \obsolete Use transformAt() instead
*/
QMatrix QGraphicsItemAnimation::matrixAt(qreal step) const
{
check_step_valid(step, "matrixAt");
+ return transformAt(step).toAffine();
+}
+#endif
+
+/*!
+ Returns the transform used for the item at the specified \a step value.
+
+ \since 5.14
+*/
+QTransform QGraphicsItemAnimation::transformAt(qreal step) const
+{
+ check_step_valid(step, "transformAt");
- QMatrix matrix;
+ QTransform transform;
if (!d->rotation.isEmpty())
- matrix.rotate(rotationAt(step));
+ transform.rotate(rotationAt(step));
if (!d->verticalScale.isEmpty())
- matrix.scale(horizontalScaleAt(step), verticalScaleAt(step));
+ transform.scale(horizontalScaleAt(step), verticalScaleAt(step));
if (!d->verticalShear.isEmpty())
- matrix.shear(horizontalShearAt(step), verticalShearAt(step));
+ transform.shear(horizontalShearAt(step), verticalShearAt(step));
if (!d->xTranslation.isEmpty())
- matrix.translate(xTranslationAt(step), yTranslationAt(step));
- return matrix;
+ transform.translate(xTranslationAt(step), yTranslationAt(step));
+ return transform;
}
/*!
@@ -542,7 +557,7 @@ void QGraphicsItemAnimation::setStep(qreal step)
|| !d->horizontalShear.isEmpty()
|| !d->xTranslation.isEmpty()
|| !d->yTranslation.isEmpty()) {
- d->item->setMatrix(d->startMatrix * matrixAt(step));
+ d->item->setTransform(d->startTransform * transformAt(step));
}
}
@@ -562,7 +577,7 @@ void QGraphicsItemAnimation::reset()
if (!d->item)
return;
d->startPos = d->item->pos();
- d->startMatrix = d->item->matrix();
+ d->startTransform = d->item->transform();
}
#endif
diff --git a/src/widgets/graphicsview/qgraphicsitemanimation.h b/src/widgets/graphicsview/qgraphicsitemanimation.h
index f983bd8026..3051fb2e2b 100644
--- a/src/widgets/graphicsview/qgraphicsitemanimation.h
+++ b/src/widgets/graphicsview/qgraphicsitemanimation.h
@@ -51,6 +51,7 @@ class QGraphicsItem;
class QMatrix;
class QPointF;
class QTimeLine;
+class QTransform;
template <class T1, class T2> struct QPair;
class QGraphicsItemAnimationPrivate;
@@ -71,7 +72,11 @@ public:
QList<QPair<qreal, QPointF> > posList() const;
void setPosAt(qreal step, const QPointF &pos);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("Use transformAt() instead")
QMatrix matrixAt(qreal step) const;
+#endif
+ QTransform transformAt(qreal step) const;
qreal rotationAt(qreal step) const;
QList<QPair<qreal, qreal> > rotationList() const;
diff --git a/src/widgets/graphicsview/qgraphicslayout.cpp b/src/widgets/graphicsview/qgraphicslayout.cpp
index ca0aef9e27..8b52b57580 100644
--- a/src/widgets/graphicsview/qgraphicslayout.cpp
+++ b/src/widgets/graphicsview/qgraphicslayout.cpp
@@ -338,7 +338,7 @@ void QGraphicsLayout::invalidate()
}
if (layoutItem && !layoutItem->isLayout()) {
// If a layout has a parent that is not a layout it must be a QGraphicsWidget.
- QApplication::postEvent(static_cast<QGraphicsWidget *>(layoutItem), new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(static_cast<QGraphicsWidget *>(layoutItem), new QEvent(QEvent::LayoutRequest));
}
}
}
diff --git a/src/widgets/graphicsview/qgraphicslayout_p.cpp b/src/widgets/graphicsview/qgraphicslayout_p.cpp
index ae1eeffa2b..59ed7acd72 100644
--- a/src/widgets/graphicsview/qgraphicslayout_p.cpp
+++ b/src/widgets/graphicsview/qgraphicslayout_p.cpp
@@ -108,7 +108,7 @@ Qt::LayoutDirection QGraphicsLayoutPrivate::visualDirection() const
if (maybeWidget->isWidget())
return static_cast<QGraphicsWidget*>(maybeWidget)->layoutDirection();
}
- return QApplication::layoutDirection();
+ return QGuiApplication::layoutDirection();
}
static bool removeLayoutItemFromLayout(QGraphicsLayout *lay, QGraphicsLayoutItem *layoutItem)
diff --git a/src/widgets/graphicsview/qgraphicslayout_p.h b/src/widgets/graphicsview/qgraphicslayout_p.h
index 302ad1e116..0d91151e22 100644
--- a/src/widgets/graphicsview/qgraphicslayout_p.h
+++ b/src/widgets/graphicsview/qgraphicslayout_p.h
@@ -91,7 +91,7 @@ public:
m_defaultSpacing[1] = style->pixelMetric(QStyle::PM_LayoutVerticalSpacing);
}
- inline void invalidate() { m_valid = false; m_style = 0; m_widget = 0; }
+ inline void invalidate() { m_valid = false; m_style = nullptr; m_widget = nullptr; }
inline QStyle *style() const { return m_style; }
inline QWidget *widget() const { return m_widget; }
@@ -130,7 +130,7 @@ class Q_AUTOTEST_EXPORT QGraphicsLayoutPrivate : public QGraphicsLayoutItemPriva
Q_DECLARE_PUBLIC(QGraphicsLayout)
public:
- QGraphicsLayoutPrivate() : QGraphicsLayoutItemPrivate(0, true), left(-1.0), top(-1.0), right(-1.0), bottom(-1.0),
+ QGraphicsLayoutPrivate() : QGraphicsLayoutItemPrivate(nullptr, true), left(-1.0), top(-1.0), right(-1.0), bottom(-1.0),
activated(true) { }
void reparentChildItems(QGraphicsItem *newParent);
diff --git a/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h b/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
index c3af9f4554..9807efb26e 100644
--- a/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
+++ b/src/widgets/graphicsview/qgraphicslayoutstyleinfo_p.h
@@ -84,7 +84,7 @@ public:
virtual void invalidate() override
{
- m_style = 0;
+ m_style = nullptr;
QAbstractLayoutStyleInfo::invalidate();
}
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.cpp b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
index e9f092020f..7413a26261 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget.cpp
+++ b/src/widgets/graphicsview/qgraphicsproxywidget.cpp
@@ -342,7 +342,7 @@ void QGraphicsProxyWidgetPrivate::sendWidgetKeyEvent(QKeyEvent *event)
Q_ASSERT(receiver);
do {
- bool res = QApplication::sendEvent(receiver, event);
+ bool res = QCoreApplication::sendEvent(receiver, event);
if ((res && event->isAccepted()) || (q->isWindow() && receiver == widget))
break;
receiver = receiver->parentWidget();
@@ -356,9 +356,9 @@ void QGraphicsProxyWidgetPrivate::removeSubFocusHelper(QWidget *widget, Qt::Focu
{
QFocusEvent event(QEvent::FocusOut, reason);
QPointer<QWidget> widgetGuard = widget;
- QApplication::sendEvent(widget, &event);
+ QCoreApplication::sendEvent(widget, &event);
if (widgetGuard && event.isAccepted())
- QApplication::sendEvent(widget->style(), &event);
+ QCoreApplication::sendEvent(widget->style(), &event);
}
/*!
@@ -404,7 +404,7 @@ void QGraphicsProxyWidgetPrivate::_q_removeWidgetSlot()
{
Q_Q(QGraphicsProxyWidget);
if (!widget.isNull()) {
- if (QWExtra *extra = widget->d_func()->extra)
+ if (const auto &extra = widget->d_func()->extra)
extra->proxyWidget = 0;
}
widget = 0;
@@ -477,8 +477,8 @@ void QGraphicsProxyWidgetPrivate::updateProxyInputMethodAcceptanceFromWidget()
*/
void QGraphicsProxyWidgetPrivate::embedSubWindow(QWidget *subWin)
{
- QWExtra *extra;
- if (!((extra = subWin->d_func()->extra) && extra->proxyWidget)) {
+ const auto &extra = subWin->d_func()->extra;
+ if (!extra || !extra->proxyWidget) {
QGraphicsProxyWidget *subProxy = new QGraphicsProxyWidget(q_func(), subWin->windowFlags());
subProxy->d_func()->setWidget_helper(subWin, false);
}
@@ -631,7 +631,7 @@ void QGraphicsProxyWidgetPrivate::setWidget_helper(QWidget *newWidget, bool auto
if (!newWidget)
return;
if (!newWidget->isWindow()) {
- QWExtra *extra = newWidget->parentWidget()->d_func()->extra;
+ const auto &extra = newWidget->parentWidget()->d_func()->extra;
if (!extra || !extra->proxyWidget) {
qWarning("QGraphicsProxyWidget::setWidget: cannot embed widget %p "
"which is not a toplevel widget, and is not a child of an embedded widget", newWidget);
@@ -641,10 +641,10 @@ void QGraphicsProxyWidgetPrivate::setWidget_helper(QWidget *newWidget, bool auto
// Register this proxy within the widget's private.
// ### This is a bit backdoorish
- QWExtra *extra = newWidget->d_func()->extra;
+ QWExtra *extra = newWidget->d_func()->extra.get();
if (!extra) {
newWidget->d_func()->createExtra();
- extra = newWidget->d_func()->extra;
+ extra = newWidget->d_func()->extra.get();
}
QGraphicsProxyWidget **proxyWidget = &extra->proxyWidget;
if (*proxyWidget) {
@@ -697,9 +697,7 @@ void QGraphicsProxyWidgetPrivate::setWidget_helper(QWidget *newWidget, bool auto
if (!newWidget->testAttribute(Qt::WA_Resized))
newWidget->adjustSize();
- int left, top, right, bottom;
- newWidget->getContentsMargins(&left, &top, &right, &bottom);
- q->setContentsMargins(left, top, right, bottom);
+ q->setContentsMargins(newWidget->contentsMargins());
q->setWindowTitle(newWidget->windowTitle());
// size policies and constraints..
@@ -865,7 +863,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
case QEvent::ShortcutOverride: {
QWidget *focusWidget = d->widget->focusWidget();
while (focusWidget) {
- QApplication::sendEvent(focusWidget, event);
+ QCoreApplication::sendEvent(focusWidget, event);
if (event->isAccepted())
return true;
focusWidget = focusWidget->parentWidget();
@@ -878,7 +876,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
QWidget *focusWidget = d->widget->focusWidget();
while (focusWidget) {
- bool res = QApplication::sendEvent(focusWidget, event);
+ const bool res = QCoreApplication::sendEvent(focusWidget, event);
if ((res && event->isAccepted()) || (isWindow() && focusWidget == d->widget)) {
event->accept();
break;
@@ -897,7 +895,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
QGraphicsSceneHelpEvent *he = static_cast<QGraphicsSceneHelpEvent *>(event);
QPoint pos = d->mapToReceiver(mapFromScene(he->scenePos()), d->lastWidgetUnderMouse).toPoint();
QHelpEvent e(QEvent::ToolTip, pos, he->screenPos());
- QApplication::sendEvent(d->lastWidgetUnderMouse, &e);
+ QCoreApplication::sendEvent(d->lastWidgetUnderMouse, &e);
event->setAccepted(e.isAccepted());
return e.isAccepted();
}
@@ -919,7 +917,7 @@ bool QGraphicsProxyWidget::event(QEvent *event)
if (event->spontaneous())
qt_sendSpontaneousEvent(d->widget, event);
else
- QApplication::sendEvent(d->widget, event);
+ QCoreApplication::sendEvent(d->widget, event);
if (event->isAccepted())
return true;
@@ -1044,7 +1042,7 @@ void QGraphicsProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *even
// Send mouse event. ### Doesn't propagate the event.
QContextMenuEvent contextMenuEvent(QContextMenuEvent::Reason(event->reason()),
pos.toPoint(), globalPos, event->modifiers());
- QApplication::sendEvent(receiver, &contextMenuEvent);
+ QCoreApplication::sendEvent(receiver, &contextMenuEvent);
event->setAccepted(contextMenuEvent.isAccepted());
}
@@ -1065,7 +1063,7 @@ void QGraphicsProxyWidget::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
QDragEnterEvent proxyDragEnter(event->pos().toPoint(), event->dropAction(), event->mimeData(), event->buttons(), event->modifiers());
proxyDragEnter.setAccepted(event->isAccepted());
- QApplication::sendEvent(d->widget, &proxyDragEnter);
+ QCoreApplication::sendEvent(d->widget, &proxyDragEnter);
event->setAccepted(proxyDragEnter.isAccepted());
if (proxyDragEnter.isAccepted()) // we discard answerRect
event->setDropAction(proxyDragEnter.dropAction());
@@ -1082,7 +1080,7 @@ void QGraphicsProxyWidget::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
if (!d->widget || !d->dragDropWidget)
return;
QDragLeaveEvent proxyDragLeave;
- QApplication::sendEvent(d->dragDropWidget, &proxyDragLeave);
+ QCoreApplication::sendEvent(d->dragDropWidget, &proxyDragLeave);
d->dragDropWidget = 0;
#endif
}
@@ -1112,7 +1110,7 @@ void QGraphicsProxyWidget::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
// Try to enter before we leave
QDragEnterEvent dragEnter(receiverPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
dragEnter.setDropAction(event->proposedAction());
- QApplication::sendEvent(receiver, &dragEnter);
+ QCoreApplication::sendEvent(receiver, &dragEnter);
event->setAccepted(dragEnter.isAccepted());
event->setDropAction(dragEnter.dropAction());
if (!event->isAccepted()) {
@@ -1124,14 +1122,14 @@ void QGraphicsProxyWidget::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
if (d->dragDropWidget) {
QDragLeaveEvent dragLeave;
- QApplication::sendEvent(d->dragDropWidget, &dragLeave);
+ QCoreApplication::sendEvent(d->dragDropWidget, &dragLeave);
}
d->dragDropWidget = receiver;
}
QDragMoveEvent dragMove(receiverPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
event->setDropAction(d->lastDropAction);
- QApplication::sendEvent(receiver, &dragMove);
+ QCoreApplication::sendEvent(receiver, &dragMove);
event->setAccepted(dragMove.isAccepted());
event->setDropAction(dragMove.dropAction());
if (event->isAccepted())
@@ -1144,7 +1142,7 @@ void QGraphicsProxyWidget::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
if (d->dragDropWidget) {
// Leave the last drag drop item
QDragLeaveEvent dragLeave;
- QApplication::sendEvent(d->dragDropWidget, &dragLeave);
+ QCoreApplication::sendEvent(d->dragDropWidget, &dragLeave);
d->dragDropWidget = 0;
}
// Propagate
@@ -1165,7 +1163,7 @@ void QGraphicsProxyWidget::dropEvent(QGraphicsSceneDragDropEvent *event)
if (d->widget && d->dragDropWidget) {
QPoint widgetPos = d->mapToReceiver(event->pos(), d->dragDropWidget).toPoint();
QDropEvent dropEvent(widgetPos, event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
- QApplication::sendEvent(d->dragDropWidget, &dropEvent);
+ QCoreApplication::sendEvent(d->dragDropWidget, &dropEvent);
event->setAccepted(dropEvent.isAccepted());
d->dragDropWidget = 0;
}
@@ -1293,8 +1291,15 @@ void QGraphicsProxyWidget::wheelEvent(QGraphicsSceneWheelEvent *event)
pos = d->mapToReceiver(pos, receiver);
// Send mouse event.
- QWheelEvent wheelEvent(pos.toPoint(), event->screenPos(), event->delta(),
- event->buttons(), event->modifiers(), event->orientation());
+ QPoint angleDelta;
+ if (event->orientation() == Qt::Horizontal)
+ angleDelta.setX(event->delta());
+ else
+ angleDelta.setY(event->delta());
+ // pixelDelta, inverted, scrollPhase and source from the original QWheelEvent
+ // were not preserved in the QGraphicsSceneWheelEvent unfortunately
+ QWheelEvent wheelEvent(pos, event->screenPos(), QPoint(), angleDelta,
+ event->buttons(), event->modifiers(), Qt::NoScrollPhase, false);
QPointer<QWidget> focusWidget = d->widget->focusWidget();
extern bool qt_sendSpontaneousEvent(QObject *, QEvent *);
qt_sendSpontaneousEvent(receiver, &wheelEvent);
@@ -1464,7 +1469,7 @@ void QGraphicsProxyWidget::inputMethodEvent(QInputMethodEvent *event)
Q_D(const QGraphicsProxyWidget);
QWidget *focusWidget = d->widget->focusWidget();
if (focusWidget && focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
- QApplication::sendEvent(focusWidget, event);
+ QCoreApplication::sendEvent(focusWidget, event);
}
/*!
diff --git a/src/widgets/graphicsview/qgraphicsscene.cpp b/src/widgets/graphicsview/qgraphicsscene.cpp
index 03717d5d1a..a47d0d879d 100644
--- a/src/widgets/graphicsview/qgraphicsscene.cpp
+++ b/src/widgets/graphicsview/qgraphicsscene.cpp
@@ -114,7 +114,7 @@
Another responsibility that QGraphicsScene has, is to propagate events
from QGraphicsView. To send an event to a scene, you construct an event
that inherits QEvent, and then send it using, for example,
- QApplication::sendEvent(). event() is responsible for dispatching
+ QCoreApplication::sendEvent(). event() is responsible for dispatching
the event to the individual items. Some common events are handled by
convenience event handlers. For example, key press events are handled by
keyPressEvent(), and mouse press events are handled by mousePressEvent().
@@ -459,7 +459,7 @@ void QGraphicsScenePrivate::_q_polishItems()
}
if (itemd->isWidget) {
QEvent event(QEvent::Polish);
- QApplication::sendEvent((QGraphicsWidget *)item, &event);
+ QCoreApplication::sendEvent((QGraphicsWidget *)item, &event);
}
}
@@ -782,7 +782,7 @@ void QGraphicsScenePrivate::setActivePanelHelper(QGraphicsItem *item, bool durin
// Update activate state.
activePanel = panel;
QEvent event(QEvent::ActivationChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
// Activate
if (panel) {
@@ -1251,7 +1251,7 @@ bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
return false;
if (QGraphicsObject *o = item->toGraphicsObject()) {
bool spont = event->spontaneous();
- if (spont ? qt_sendSpontaneousEvent(o, event) : QApplication::sendEvent(o, event))
+ if (spont ? qt_sendSpontaneousEvent(o, event) : QCoreApplication::sendEvent(o, event))
return true;
event->spont = spont;
}
@@ -1577,7 +1577,7 @@ void QGraphicsScenePrivate::updateFont(const QFont &font)
// Send the scene a FontChange event.
QEvent event(QEvent::FontChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
}
/*!
@@ -1601,7 +1601,7 @@ void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
*/
void QGraphicsScenePrivate::resolvePalette()
{
- QPalette naturalPalette = QApplication::palette();
+ QPalette naturalPalette = QGuiApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
updatePalette(resolvedPalette);
@@ -1634,7 +1634,7 @@ void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
// Send the scene a PaletteChange event.
QEvent event(QEvent::PaletteChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
}
/*!
@@ -3555,10 +3555,10 @@ bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
switch (event->type()) {
case QEvent::ApplicationPaletteChange:
- QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
+ QCoreApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
break;
case QEvent::ApplicationFontChange:
- QApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
+ QCoreApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
break;
default:
break;
@@ -4177,14 +4177,6 @@ void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
wheelEvent->scenePos(),
wheelEvent->widget());
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // On Mac, ignore the event if the first item under the mouse is not the last opened
- // popup (or one of its descendant)
- if (!d->popupWidgets.isEmpty() && !wheelCandidates.isEmpty() && wheelCandidates.first() != d->popupWidgets.back() && !d->popupWidgets.back()->isAncestorOf(wheelCandidates.first())) {
- wheelEvent->accept();
- return;
- }
-#else
// Find the first popup under the mouse (including the popup's descendants) starting from the last.
// Remove all popups after the one found, or all or them if no popup is under the mouse.
// Then continue with the event.
@@ -4194,7 +4186,6 @@ void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
break;
d->removePopup(*iter);
}
-#endif
bool hasSetFocus = false;
for (QGraphicsItem *item : wheelCandidates) {
@@ -4416,11 +4407,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte
QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
// Render directly, using no cache.
- if (cacheMode == QGraphicsItem::NoCache
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- || !X11->use_xrender
-#endif
- ) {
+ if (cacheMode == QGraphicsItem::NoCache) {
_q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
return;
}
@@ -5612,7 +5599,7 @@ void QGraphicsScene::setStyle(QStyle *style)
// Notify the scene.
QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
// Notify all widgets that don't have a style explicitly set.
const auto items_ = items();
@@ -5620,7 +5607,7 @@ void QGraphicsScene::setStyle(QStyle *style)
if (item->isWidget()) {
QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
if (!widget->testAttribute(Qt::WA_SetStyle))
- QApplication::sendEvent(widget, &event);
+ QCoreApplication::sendEvent(widget, &event);
}
}
}
@@ -5693,7 +5680,7 @@ QPalette QGraphicsScene::palette() const
void QGraphicsScene::setPalette(const QPalette &palette)
{
Q_D(QGraphicsScene);
- QPalette naturalPalette = QApplication::palette();
+ QPalette naturalPalette = QGuiApplication::palette();
naturalPalette.resolve(0);
QPalette resolvedPalette = palette.resolve(naturalPalette);
d->setPalette_helper(resolvedPalette);
@@ -6359,7 +6346,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
<< "delivering override to"
<< item.data() << gestures;
// send gesture override
- QGestureEvent ev(gestures.toList());
+ QGestureEvent ev(gestures.values());
ev.t = QEvent::GestureOverride;
ev.setWidget(event->widget());
// mark event and individual gestures as ignored
@@ -6449,7 +6436,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
<< "delivering to"
<< receiver.data() << gestures;
- QGestureEvent ev(gestures.toList());
+ QGestureEvent ev(gestures.values());
ev.setWidget(event->widget());
sendEvent(receiver.data(), &ev);
QSet<QGesture *> ignoredGestures;
@@ -6480,7 +6467,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
// look for new potential targets for gestures that were ignored
// and should be propagated.
- QSet<QGraphicsObject *> targetsSet = cachedTargetItems.toSet();
+ QSet<QGraphicsObject *> targetsSet(cachedTargetItems.constBegin(), cachedTargetItems.constEnd());
if (receiver) {
// first if the gesture should be propagated to parents only
@@ -6512,7 +6499,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
gestureTargetsAtHotSpots(ignoredGestures, Qt::ReceivePartialGestures,
&cachedItemGestures, &targetsSet, 0, 0);
- cachedTargetItems = targetsSet.toList();
+ cachedTargetItems = targetsSet.values();
std::sort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
<< "new targets:" << cachedTargetItems;
@@ -6590,7 +6577,7 @@ void QGraphicsScenePrivate::cancelGesturesForChildren(QGesture *original)
}
Q_ASSERT(target);
- const QList<QGesture *> list = gestures.toList();
+ const QList<QGesture *> list = gestures.values();
QGestureEvent ev(list);
sendEvent(target, &ev);
diff --git a/src/widgets/graphicsview/qgraphicsscene.h b/src/widgets/graphicsview/qgraphicsscene.h
index 3cc00ead08..d36a871533 100644
--- a/src/widgets/graphicsview/qgraphicsscene.h
+++ b/src/widgets/graphicsview/qgraphicsscene.h
@@ -115,7 +115,7 @@ public:
BspTreeIndex,
NoIndex = -1
};
-
+ Q_ENUM(ItemIndexMethod)
enum SceneLayer {
ItemLayer = 0x1,
BackgroundLayer = 0x2,
diff --git a/src/widgets/graphicsview/qgraphicsscene_p.h b/src/widgets/graphicsview/qgraphicsscene_p.h
index 14bafe6678..9ecfca8ebf 100644
--- a/src/widgets/graphicsview/qgraphicsscene_p.h
+++ b/src/widgets/graphicsview/qgraphicsscene_p.h
@@ -241,7 +241,7 @@ public:
void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform *const,
QRegion *exposedRegion, QWidget *widget, qreal parentOpacity = qreal(1.0),
- const QTransform *const effectTransform = 0);
+ const QTransform *const effectTransform = nullptr);
void draw(QGraphicsItem *, QPainter *, const QTransform *const, const QTransform *const,
QRegion *, QWidget *, qreal, const QTransform *const, bool, bool);
@@ -327,9 +327,9 @@ public:
void gestureTargetsAtHotSpots(const QSet<QGesture *> &gestures,
Qt::GestureFlag flag,
QHash<QGraphicsObject *, QSet<QGesture *> > *targets,
- QSet<QGraphicsObject *> *itemsSet = 0,
- QSet<QGesture *> *normal = 0,
- QSet<QGesture *> *conflicts = 0);
+ QSet<QGraphicsObject *> *itemsSet = nullptr,
+ QSet<QGesture *> *normal = nullptr,
+ QSet<QGesture *> *conflicts = nullptr);
void cancelGesturesForChildren(QGesture *original);
void grabGesture(QGraphicsItem *, Qt::GestureType gesture);
void ungrabGesture(QGraphicsItem *, Qt::GestureType gesture);
diff --git a/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h b/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
index eb6bbbf49b..7e0e525a6b 100644
--- a/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
+++ b/src/widgets/graphicsview/qgraphicsscenebsptreeindex_p.h
@@ -74,7 +74,7 @@ class Q_AUTOTEST_EXPORT QGraphicsSceneBspTreeIndex : public QGraphicsSceneIndex
Q_OBJECT
Q_PROPERTY(int bspTreeDepth READ bspTreeDepth WRITE setBspTreeDepth)
public:
- QGraphicsSceneBspTreeIndex(QGraphicsScene *scene = 0);
+ QGraphicsSceneBspTreeIndex(QGraphicsScene *scene = nullptr);
~QGraphicsSceneBspTreeIndex();
QList<QGraphicsItem *> estimateItems(const QRectF &rect, Qt::SortOrder order) const override;
diff --git a/src/widgets/graphicsview/qgraphicssceneindex_p.h b/src/widgets/graphicsview/qgraphicssceneindex_p.h
index 86637e836b..b494c52671 100644
--- a/src/widgets/graphicsview/qgraphicssceneindex_p.h
+++ b/src/widgets/graphicsview/qgraphicssceneindex_p.h
@@ -77,7 +77,7 @@ class Q_AUTOTEST_EXPORT QGraphicsSceneIndex : public QObject
Q_OBJECT
public:
- QGraphicsSceneIndex(QGraphicsScene *scene = 0);
+ QGraphicsSceneIndex(QGraphicsScene *scene = nullptr);
virtual ~QGraphicsSceneIndex();
QGraphicsScene *scene() const;
diff --git a/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h b/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
index 07d5d80ef1..ead52c1fb0 100644
--- a/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
+++ b/src/widgets/graphicsview/qgraphicsscenelinearindex_p.h
@@ -67,7 +67,7 @@ class Q_AUTOTEST_EXPORT QGraphicsSceneLinearIndex : public QGraphicsSceneIndex
Q_OBJECT
public:
- QGraphicsSceneLinearIndex(QGraphicsScene *scene = 0) : QGraphicsSceneIndex(scene), m_numSortedElements(0)
+ QGraphicsSceneLinearIndex(QGraphicsScene *scene = nullptr) : QGraphicsSceneIndex(scene), m_numSortedElements(0)
{ }
QList<QGraphicsItem *> items(Qt::SortOrder order = Qt::DescendingOrder) const override
diff --git a/src/widgets/graphicsview/qgraphicstransform_p.h b/src/widgets/graphicsview/qgraphicstransform_p.h
index e54ee9fb3c..05e12c3e64 100644
--- a/src/widgets/graphicsview/qgraphicstransform_p.h
+++ b/src/widgets/graphicsview/qgraphicstransform_p.h
@@ -66,7 +66,7 @@ public:
Q_DECLARE_PUBLIC(QGraphicsTransform)
QGraphicsTransformPrivate()
- : QObjectPrivate(), item(0) {}
+ : QObjectPrivate(), item(nullptr) {}
~QGraphicsTransformPrivate();
QGraphicsItem *item;
diff --git a/src/widgets/graphicsview/qgraphicsview.cpp b/src/widgets/graphicsview/qgraphicsview.cpp
index 6079e41bfc..57be850829 100644
--- a/src/widgets/graphicsview/qgraphicsview.cpp
+++ b/src/widgets/graphicsview/qgraphicsview.cpp
@@ -667,7 +667,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
if (event->spontaneous())
qt_sendSpontaneousEvent(scene, &mouseEvent);
else
- QApplication::sendEvent(scene, &mouseEvent);
+ QCoreApplication::sendEvent(scene, &mouseEvent);
// Remember whether the last event was accepted or not.
lastMouseEvent.setAccepted(mouseEvent.isAccepted());
@@ -1716,7 +1716,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene)
if (isActiveWindow() && isVisible()) {
QEvent windowDeactivate(QEvent::WindowDeactivate);
- QApplication::sendEvent(d->scene, &windowDeactivate);
+ QCoreApplication::sendEvent(d->scene, &windowDeactivate);
}
if(hasFocus())
d->scene->clearFocus();
@@ -1744,7 +1744,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene)
if (isActiveWindow() && isVisible()) {
QEvent windowActivate(QEvent::WindowActivate);
- QApplication::sendEvent(d->scene, &windowActivate);
+ QCoreApplication::sendEvent(d->scene, &windowActivate);
}
} else {
d->recalculateContentSize();
@@ -2809,7 +2809,7 @@ bool QGraphicsView::event(QEvent *event)
switch (event->type()) {
case QEvent::ShortcutOverride:
if (d->scene)
- return QApplication::sendEvent(d->scene, event);
+ return QCoreApplication::sendEvent(d->scene, event);
break;
case QEvent::KeyPress:
if (d->scene) {
@@ -2821,7 +2821,7 @@ bool QGraphicsView::event(QEvent *event)
// and the base implementation will call QGraphicsView's
// focusNextPrevChild() function. If the event is ignored,
// we fall back to standard tab focus handling.
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
if (event->isAccepted())
return true;
// Ensure the event doesn't propagate just because the
@@ -2850,10 +2850,10 @@ bool QGraphicsView::viewportEvent(QEvent *event)
switch (event->type()) {
case QEvent::Enter:
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
break;
case QEvent::WindowActivate:
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
break;
case QEvent::WindowDeactivate:
// ### This is a temporary fix for until we get proper mouse
@@ -2862,19 +2862,19 @@ bool QGraphicsView::viewportEvent(QEvent *event)
// Remove all popups when the scene loses focus.
if (!d->scene->d_func()->popupWidgets.isEmpty())
d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.constFirst());
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
break;
case QEvent::Show:
if (d->scene && isActiveWindow()) {
QEvent windowActivate(QEvent::WindowActivate);
- QApplication::sendEvent(d->scene, &windowActivate);
+ QCoreApplication::sendEvent(d->scene, &windowActivate);
}
break;
case QEvent::Hide:
// spontaneous event will generate a WindowDeactivate.
if (!event->spontaneous() && d->scene && isActiveWindow()) {
QEvent windowDeactivate(QEvent::WindowDeactivate);
- QApplication::sendEvent(d->scene, &windowDeactivate);
+ QCoreApplication::sendEvent(d->scene, &windowDeactivate);
}
break;
case QEvent::Leave: {
@@ -2892,7 +2892,7 @@ bool QGraphicsView::viewportEvent(QEvent *event)
Q_ASSERT(event->d == 0);
QScopedValueRollback<QEventPrivate *> rb(event->d);
event->d = reinterpret_cast<QEventPrivate *>(viewport());
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
break;
}
#ifndef QT_NO_TOOLTIP
@@ -2902,7 +2902,7 @@ bool QGraphicsView::viewportEvent(QEvent *event)
helpEvent.setWidget(viewport());
helpEvent.setScreenPos(toolTip->globalPos());
helpEvent.setScenePos(mapToScene(toolTip->pos()));
- QApplication::sendEvent(d->scene, &helpEvent);
+ QCoreApplication::sendEvent(d->scene, &helpEvent);
toolTip->setAccepted(helpEvent.isAccepted());
return true;
}
@@ -2940,7 +2940,7 @@ bool QGraphicsView::viewportEvent(QEvent *event)
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
touchEvent->setTarget(viewport());
QGraphicsViewPrivate::translateTouchEvent(d, touchEvent);
- (void) QApplication::sendEvent(d->scene, touchEvent);
+ QCoreApplication::sendEvent(d->scene, touchEvent);
} else {
event->ignore();
}
@@ -2957,7 +2957,7 @@ bool QGraphicsView::viewportEvent(QEvent *event)
if (d->scene && d->sceneInteractionAllowed) {
QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event);
gestureEvent->setWidget(viewport());
- (void) QApplication::sendEvent(d->scene, gestureEvent);
+ QCoreApplication::sendEvent(d->scene, gestureEvent);
}
return true;
}
@@ -2992,7 +2992,7 @@ void QGraphicsView::contextMenuEvent(QContextMenuEvent *event)
contextEvent.setModifiers(event->modifiers());
contextEvent.setReason((QGraphicsSceneContextMenuEvent::Reason)(event->reason()));
contextEvent.setAccepted(event->isAccepted());
- QApplication::sendEvent(d->scene, &contextEvent);
+ QCoreApplication::sendEvent(d->scene, &contextEvent);
event->setAccepted(contextEvent.isAccepted());
}
#endif // QT_NO_CONTEXTMENU
@@ -3012,7 +3012,7 @@ void QGraphicsView::dropEvent(QDropEvent *event)
d->populateSceneDragDropEvent(&sceneEvent, event);
// Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
+ QCoreApplication::sendEvent(d->scene, &sceneEvent);
// Accept the originating event if the scene accepted the scene event.
event->setAccepted(sceneEvent.isAccepted());
@@ -3043,7 +3043,7 @@ void QGraphicsView::dragEnterEvent(QDragEnterEvent *event)
d->storeDragDropEvent(&sceneEvent);
// Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
+ QCoreApplication::sendEvent(d->scene, &sceneEvent);
// Accept the originating event if the scene accepted the scene event.
if (sceneEvent.isAccepted()) {
@@ -3081,7 +3081,7 @@ void QGraphicsView::dragLeaveEvent(QDragLeaveEvent *event)
d->lastDragDropEvent = 0;
// Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
+ QCoreApplication::sendEvent(d->scene, &sceneEvent);
// Accept the originating event if the scene accepted the scene event.
if (sceneEvent.isAccepted())
@@ -3105,7 +3105,7 @@ void QGraphicsView::dragMoveEvent(QDragMoveEvent *event)
d->storeDragDropEvent(&sceneEvent);
// Send it to the scene.
- QApplication::sendEvent(d->scene, &sceneEvent);
+ QCoreApplication::sendEvent(d->scene, &sceneEvent);
// Ignore the originating event if the scene ignored the scene event.
event->setAccepted(sceneEvent.isAccepted());
@@ -3123,7 +3123,7 @@ void QGraphicsView::focusInEvent(QFocusEvent *event)
d->updateInputMethodSensitivity();
QAbstractScrollArea::focusInEvent(event);
if (d->scene)
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
// Pass focus on if the scene cannot accept focus.
if (!d->scene || !event->isAccepted())
QAbstractScrollArea::focusInEvent(event);
@@ -3145,7 +3145,7 @@ void QGraphicsView::focusOutEvent(QFocusEvent *event)
Q_D(QGraphicsView);
QAbstractScrollArea::focusOutEvent(event);
if (d->scene)
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
}
/*!
@@ -3158,7 +3158,7 @@ void QGraphicsView::keyPressEvent(QKeyEvent *event)
QAbstractScrollArea::keyPressEvent(event);
return;
}
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
if (!event->isAccepted())
QAbstractScrollArea::keyPressEvent(event);
}
@@ -3171,7 +3171,7 @@ void QGraphicsView::keyReleaseEvent(QKeyEvent *event)
Q_D(QGraphicsView);
if (!d->scene || !d->sceneInteractionAllowed)
return;
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
if (!event->isAccepted())
QAbstractScrollArea::keyReleaseEvent(event);
}
@@ -3210,7 +3210,7 @@ void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
- QApplication::sendEvent(d->scene, &mouseEvent);
+ QCoreApplication::sendEvent(d->scene, &mouseEvent);
// Update the original mouse event accepted state.
const bool isAccepted = mouseEvent.isAccepted();
@@ -3261,7 +3261,7 @@ void QGraphicsView::mousePressEvent(QMouseEvent *event)
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
- QApplication::sendEvent(d->scene, &mouseEvent);
+ QCoreApplication::sendEvent(d->scene, &mouseEvent);
// Update the original mouse event accepted state.
bool isAccepted = mouseEvent.isAccepted();
@@ -3397,7 +3397,7 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
if (event->spontaneous())
qt_sendSpontaneousEvent(d->scene, &mouseEvent);
else
- QApplication::sendEvent(d->scene, &mouseEvent);
+ QCoreApplication::sendEvent(d->scene, &mouseEvent);
// Update the last mouse event selected state.
d->lastMouseEvent.setAccepted(mouseEvent.isAccepted());
@@ -3426,14 +3426,15 @@ void QGraphicsView::wheelEvent(QWheelEvent *event)
QGraphicsSceneWheelEvent wheelEvent(QEvent::GraphicsSceneWheel);
wheelEvent.setWidget(viewport());
- wheelEvent.setScenePos(mapToScene(event->pos()));
- wheelEvent.setScreenPos(event->globalPos());
+ wheelEvent.setScenePos(mapToScene(event->position().toPoint()));
+ wheelEvent.setScreenPos(event->globalPosition().toPoint());
wheelEvent.setButtons(event->buttons());
wheelEvent.setModifiers(event->modifiers());
- wheelEvent.setDelta(event->delta());
- wheelEvent.setOrientation(event->orientation());
+ const bool horizontal = qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y());
+ wheelEvent.setDelta(horizontal ? event->angleDelta().x() : event->angleDelta().y());
+ wheelEvent.setOrientation(horizontal ? Qt::Horizontal : Qt::Vertical);
wheelEvent.setAccepted(false);
- QApplication::sendEvent(d->scene, &wheelEvent);
+ QCoreApplication::sendEvent(d->scene, &wheelEvent);
event->setAccepted(wheelEvent.isAccepted());
if (!event->isAccepted())
QAbstractScrollArea::wheelEvent(event);
@@ -3475,11 +3476,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event)
const QTransform viewTransform = painter.worldTransform();
// Draw background
- if ((d->cacheMode & CacheBackground)
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- && X11->use_xrender
-#endif
- ) {
+ if (d->cacheMode & CacheBackground) {
// Recreate the background pixmap, and flag the whole background as
// exposed.
if (d->mustResizeBackgroundPixmap) {
@@ -3676,11 +3673,7 @@ void QGraphicsView::scrollContentsBy(int dx, int dy)
d->updateLastCenterPoint();
- if ((d->cacheMode & CacheBackground)
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- && X11->use_xrender
-#endif
- ) {
+ if (d->cacheMode & CacheBackground) {
// Below, QPixmap::scroll() works in device pixels, while the delta values
// and backgroundPixmapExposed are in device independent pixels.
const qreal dpr = d->backgroundPixmap.devicePixelRatio();
@@ -3720,7 +3713,7 @@ void QGraphicsView::inputMethodEvent(QInputMethodEvent *event)
{
Q_D(QGraphicsView);
if (d->scene)
- QApplication::sendEvent(d->scene, event);
+ QCoreApplication::sendEvent(d->scene, event);
}
/*!
diff --git a/src/widgets/graphicsview/qgraphicsview.h b/src/widgets/graphicsview/qgraphicsview.h
index e02fba69c9..1389796c3f 100644
--- a/src/widgets/graphicsview/qgraphicsview.h
+++ b/src/widgets/graphicsview/qgraphicsview.h
@@ -107,7 +107,9 @@ public:
Q_ENUM(ViewportUpdateMode)
enum OptimizationFlag {
- DontClipPainter = 0x1, // obsolete
+#if QT_DEPRECATED_SINCE(5, 14)
+ DontClipPainter Q_DECL_ENUMERATOR_DEPRECATED_X("This flag is unused") = 0x1, // obsolete
+#endif
DontSavePainterState = 0x2,
DontAdjustForAntialiasing = 0x4,
IndirectPainting = 0x8
diff --git a/src/widgets/graphicsview/qgraphicsview_p.h b/src/widgets/graphicsview/qgraphicsview_p.h
index 0428b9ce70..01af61d6ba 100644
--- a/src/widgets/graphicsview/qgraphicsview_p.h
+++ b/src/widgets/graphicsview/qgraphicsview_p.h
@@ -184,24 +184,10 @@ public:
inline void dispatchPendingUpdateRequests()
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // QWidget::update() works slightly different on the Mac without the raster engine;
- // it's not part of our backing store so it needs special threatment.
- if (QApplicationPrivate::graphics_system_name != QLatin1String("raster")) {
- // At this point either HIViewSetNeedsDisplay (Carbon) or setNeedsDisplay: YES (Cocoa)
- // is called, which means there's a pending update request. We want to dispatch it
- // now because otherwise graphics view updates would require two
- // round-trips in the event loop before the item is painted.
- extern void qt_mac_dispatchPendingUpdateRequests(QWidget *);
- qt_mac_dispatchPendingUpdateRequests(viewport->window());
- } else
-#endif
- {
- if (qt_widget_private(viewport)->paintOnScreen())
- QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest);
- else
- QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest);
- }
+ if (qt_widget_private(viewport)->shouldPaintOnScreen())
+ QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest);
+ else
+ QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest);
}
void setUpdateClip(QGraphicsItem *);
diff --git a/src/widgets/graphicsview/qgraphicswidget.cpp b/src/widgets/graphicsview/qgraphicswidget.cpp
index ad3be5766d..cf041b9817 100644
--- a/src/widgets/graphicsview/qgraphicswidget.cpp
+++ b/src/widgets/graphicsview/qgraphicswidget.cpp
@@ -390,7 +390,7 @@ void QGraphicsWidget::setGeometry(const QRectF &rect)
QGraphicsSceneMoveEvent event;
event.setOldPos(oldPos);
event.setNewPos(pos());
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
if (wd->inSetPos) {
//set the new pos
d->geom.moveTopLeft(pos());
@@ -413,10 +413,10 @@ void QGraphicsWidget::setGeometry(const QRectF &rect)
QGraphicsLayout *lay = wd->layout;
if (QGraphicsLayout::instantInvalidatePropagation()) {
if (!lay || lay->isActivated()) {
- QApplication::sendEvent(this, &re);
+ QCoreApplication::sendEvent(this, &re);
}
} else {
- QApplication::sendEvent(this, &re);
+ QCoreApplication::sendEvent(this, &re);
}
}
}
@@ -427,7 +427,7 @@ relayoutChildrenAndReturn:
if (QGraphicsLayout *lay = wd->layout) {
if (!lay->isActivated()) {
QEvent layoutRequest(QEvent::LayoutRequest);
- QApplication::sendEvent(this, &layoutRequest);
+ QCoreApplication::sendEvent(this, &layoutRequest);
}
}
}
@@ -473,8 +473,9 @@ relayoutChildrenAndReturn:
*/
/*!
- Sets the widget's contents margins to \a left, \a top, \a right and \a
- bottom.
+ \since 5.14
+
+ Sets the widget's contents margins to \a margins.
Contents margins are used by the assigned layout to define the placement
of subwidgets and layouts. Margins are particularly useful for widgets
@@ -488,23 +489,17 @@ relayoutChildrenAndReturn:
\sa getContentsMargins(), setGeometry()
*/
-void QGraphicsWidget::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom)
+void QGraphicsWidget::setContentsMargins(QMarginsF margins)
{
Q_D(QGraphicsWidget);
- if (!d->margins && left == 0 && top == 0 && right == 0 && bottom == 0)
+ if (!d->margins && margins.isNull())
return;
d->ensureMargins();
- if (left == d->margins[d->Left]
- && top == d->margins[d->Top]
- && right == d->margins[d->Right]
- && bottom == d->margins[d->Bottom])
+ if (*d->margins == margins)
return;
- d->margins[d->Left] = left;
- d->margins[d->Top] = top;
- d->margins[d->Right] = right;
- d->margins[d->Bottom] = bottom;
+ *d->margins = margins;
if (QGraphicsLayout *l = d->layout)
l->invalidate();
@@ -512,7 +507,18 @@ void QGraphicsWidget::setContentsMargins(qreal left, qreal top, qreal right, qre
updateGeometry();
QEvent e(QEvent::ContentsRectChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
+}
+
+/*!
+ \overload
+
+ Sets the widget's contents margins to \a left, \a top, \a right and \a
+ bottom.
+*/
+void QGraphicsWidget::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom)
+{
+ setContentsMargins({left, top, right, bottom});
}
/*!
@@ -528,18 +534,19 @@ void QGraphicsWidget::getContentsMargins(qreal *left, qreal *top, qreal *right,
if (left || top || right || bottom)
d->ensureMargins();
if (left)
- *left = d->margins[d->Left];
+ *left = d->margins->left();
if (top)
- *top = d->margins[d->Top];
+ *top = d->margins->top();
if (right)
- *right = d->margins[d->Right];
+ *right = d->margins->right();
if (bottom)
- *bottom = d->margins[d->Bottom];
+ *bottom = d->margins->bottom();
}
/*!
- Sets the widget's window frame margins to \a left, \a top, \a right and
- \a bottom. The default frame margins are provided by the style, and they
+ \since 5.14
+ Sets the widget's window frame margins to \a margins.
+ The default frame margins are provided by the style, and they
depend on the current window flags.
If you would like to draw your own window decoration, you can set your
@@ -547,30 +554,33 @@ void QGraphicsWidget::getContentsMargins(qreal *left, qreal *top, qreal *right,
\sa unsetWindowFrameMargins(), getWindowFrameMargins(), windowFrameRect()
*/
-void QGraphicsWidget::setWindowFrameMargins(qreal left, qreal top, qreal right, qreal bottom)
+void QGraphicsWidget::setWindowFrameMargins(QMarginsF margins)
{
Q_D(QGraphicsWidget);
- if (!d->windowFrameMargins && left == 0 && top == 0 && right == 0 && bottom == 0)
+ if (!d->windowFrameMargins && margins.isNull())
return;
d->ensureWindowFrameMargins();
- bool unchanged =
- d->windowFrameMargins[d->Left] == left
- && d->windowFrameMargins[d->Top] == top
- && d->windowFrameMargins[d->Right] == right
- && d->windowFrameMargins[d->Bottom] == bottom;
+ const bool unchanged = *d->windowFrameMargins == margins;
if (d->setWindowFrameMargins && unchanged)
return;
if (!unchanged)
prepareGeometryChange();
- d->windowFrameMargins[d->Left] = left;
- d->windowFrameMargins[d->Top] = top;
- d->windowFrameMargins[d->Right] = right;
- d->windowFrameMargins[d->Bottom] = bottom;
+ *d->windowFrameMargins = margins;
d->setWindowFrameMargins = true;
}
/*!
+ \overload
+ Sets the widget's window frame margins to \a left, \a top, \a right and
+ \a bottom.
+*/
+void QGraphicsWidget::setWindowFrameMargins(qreal left, qreal top, qreal right, qreal bottom)
+{
+ setWindowFrameMargins({left, top, right, bottom});
+}
+
+/*!
Gets the widget's window frame margins. The margins are stored in \a left,
\a top, \a right and \a bottom as pointers to qreals. Each argument can
be \e {omitted} by passing \nullptr.
@@ -583,13 +593,13 @@ void QGraphicsWidget::getWindowFrameMargins(qreal *left, qreal *top, qreal *righ
if (left || top || right || bottom)
d->ensureWindowFrameMargins();
if (left)
- *left = d->windowFrameMargins[d->Left];
+ *left = d->windowFrameMargins->left();
if (top)
- *top = d->windowFrameMargins[d->Top];
+ *top = d->windowFrameMargins->top();
if (right)
- *right = d->windowFrameMargins[d->Right];
+ *right = d->windowFrameMargins->right();
if (bottom)
- *bottom = d->windowFrameMargins[d->Bottom];
+ *bottom = d->windowFrameMargins->bottom();
}
/*!
@@ -624,8 +634,8 @@ QRectF QGraphicsWidget::windowFrameGeometry() const
{
Q_D(const QGraphicsWidget);
return d->windowFrameMargins
- ? geometry().adjusted(-d->windowFrameMargins[d->Left], -d->windowFrameMargins[d->Top],
- d->windowFrameMargins[d->Right], d->windowFrameMargins[d->Bottom])
+ ? geometry().adjusted(-d->windowFrameMargins->left(), -d->windowFrameMargins->top(),
+ d->windowFrameMargins->right(), d->windowFrameMargins->bottom())
: geometry();
}
@@ -638,8 +648,8 @@ QRectF QGraphicsWidget::windowFrameRect() const
{
Q_D(const QGraphicsWidget);
return d->windowFrameMargins
- ? rect().adjusted(-d->windowFrameMargins[d->Left], -d->windowFrameMargins[d->Top],
- d->windowFrameMargins[d->Right], d->windowFrameMargins[d->Bottom])
+ ? rect().adjusted(-d->windowFrameMargins->left(), -d->windowFrameMargins->top(),
+ d->windowFrameMargins->right(), d->windowFrameMargins->bottom())
: rect();
}
@@ -706,22 +716,6 @@ void QGraphicsWidget::initStyleOption(QStyleOption *option) const
option->state |= QStyle::State_Window;
/*
###
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QGraphicsWidget *w); //qwidget_mac.cpp
- if (!(option->state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget))
- option->state &= ~QStyle::State_Enabled;
-
- switch (QMacStyle::widgetSizePolicy(widget)) {
- case QMacStyle::SizeSmall:
- option->state |= QStyle::State_Small;
- break;
- case QMacStyle::SizeMini:
- option->state |= QStyle::State_Mini;
- break;
- default:
- ;
- }
-#endif
#ifdef QT_KEYPAD_NAVIGATION
if (widget->hasEditFocus())
state |= QStyle::State_HasEditFocus;
@@ -751,8 +745,8 @@ QSizeF QGraphicsWidget::sizeHint(Qt::SizeHint which, const QSizeF &constraint) c
if (d->layout) {
QSizeF marginSize(0,0);
if (d->margins) {
- marginSize = QSizeF(d->margins[d->Left] + d->margins[d->Right],
- d->margins[d->Top] + d->margins[d->Bottom]);
+ marginSize = QSizeF(d->margins->left() + d->margins->right(),
+ d->margins->top() + d->margins->bottom());
}
sh = d->layout->effectiveSizeHint(which, constraint - marginSize);
sh += marginSize;
@@ -953,7 +947,7 @@ void QGraphicsWidget::setStyle(QStyle *style)
// Deliver StyleChange to the widget itself (doesn't propagate).
QEvent event(QEvent::StyleChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
/*!
@@ -1018,7 +1012,7 @@ void QGraphicsWidget::setFont(const QFont &font)
By default, this property contains the application's default palette.
- \sa QApplication::palette(), QGraphicsScene::palette, QPalette::resolve()
+ \sa QGuiApplication::palette(), QGraphicsScene::palette, QPalette::resolve()
*/
QPalette QGraphicsWidget::palette() const
{
@@ -1090,7 +1084,7 @@ void QGraphicsWidget::updateGeometry()
// This is for custom layouting
QGraphicsWidget *parentWid = parentWidget(); //###
if (parentWid->isVisible())
- QApplication::postEvent(parentWid, new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(parentWid, new QEvent(QEvent::LayoutRequest));
} else {
/**
* If this is the topmost widget, post a LayoutRequest event to the widget.
@@ -1098,7 +1092,7 @@ void QGraphicsWidget::updateGeometry()
* widgets in one go. This will make a relayout flicker-free.
*/
if (QGraphicsLayout::instantInvalidatePropagation())
- QApplication::postEvent(static_cast<QGraphicsWidget *>(this), new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(static_cast<QGraphicsWidget *>(this), new QEvent(QEvent::LayoutRequest));
}
if (!QGraphicsLayout::instantInvalidatePropagation()) {
bool wasResized = testAttribute(Qt::WA_Resized);
@@ -1135,14 +1129,14 @@ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &
case ItemEnabledHasChanged: {
// Send EnabledChange after the enabled state has changed.
QEvent event(QEvent::EnabledChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
break;
}
case ItemVisibleChange:
if (value.toBool()) {
// Send Show event before the item has been shown.
QShowEvent event;
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
bool resized = testAttribute(Qt::WA_Resized);
if (!resized) {
adjustSize();
@@ -1158,7 +1152,7 @@ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &
if (!value.toBool()) {
// Send Hide event after the item has been hidden.
QHideEvent event;
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
break;
case ItemPositionHasChanged:
@@ -1167,25 +1161,25 @@ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &
case ItemParentChange: {
// Deliver ParentAboutToChange.
QEvent event(QEvent::ParentAboutToChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
break;
}
case ItemParentHasChanged: {
// Deliver ParentChange.
QEvent event(QEvent::ParentChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
break;
}
case ItemCursorHasChanged: {
// Deliver CursorChange.
QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
break;
}
case ItemToolTipHasChanged: {
// Deliver ToolTipChange.
QEvent event(QEvent::ToolTipChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
break;
}
default:
@@ -1320,7 +1314,7 @@ Qt::WindowFrameSection QGraphicsWidget::windowFrameSectionAt(const QPointF &pos)
const qreal cornerMargin = 20;
//### Not sure of this one, it should be the same value for all edges.
const qreal windowFrameWidth = d->windowFrameMargins
- ? d->windowFrameMargins[d->Left] : 0;
+ ? d->windowFrameMargins->left() : 0;
Qt::WindowFrameSection s = Qt::NoSection;
if (x <= left + cornerMargin) {
@@ -1347,7 +1341,7 @@ Qt::WindowFrameSection QGraphicsWidget::windowFrameSectionAt(const QPointF &pos)
if (s == Qt::NoSection) {
QRectF r1 = r;
r1.setHeight(d->windowFrameMargins
- ? d->windowFrameMargins[d->Top] : 0);
+ ? d->windowFrameMargins->top() : 0);
if (r1.contains(pos))
s = Qt::TitleBarArea;
}
@@ -1920,7 +1914,7 @@ int QGraphicsWidget::grabShortcut(const QKeySequence &sequence, Qt::ShortcutCont
if (sequence.isEmpty())
return 0;
// ### setAttribute(Qt::WA_GrabbedShortcut);
- return qApp->d_func()->shortcutMap.addShortcut(this, sequence, context, qWidgetShortcutContextMatcher);
+ return QGuiApplicationPrivate::instance()->shortcutMap.addShortcut(this, sequence, context, qWidgetShortcutContextMatcher);
}
/*!
@@ -1944,7 +1938,7 @@ void QGraphicsWidget::releaseShortcut(int id)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(id, this, 0);
}
/*!
@@ -1965,7 +1959,7 @@ void QGraphicsWidget::setShortcutEnabled(int id, bool enabled)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.setShortcutEnabled(enabled, id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutEnabled(enabled, id, this, 0);
}
/*!
@@ -1980,7 +1974,7 @@ void QGraphicsWidget::setShortcutAutoRepeat(int id, bool enabled)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enabled, id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutAutoRepeat(enabled, id, this, 0);
}
#endif
@@ -2058,7 +2052,7 @@ void QGraphicsWidget::insertAction(QAction *before, QAction *action)
}
QActionEvent e(QEvent::ActionAdded, action, before);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
/*!
@@ -2101,7 +2095,7 @@ void QGraphicsWidget::removeAction(QAction *action)
if (d->actions.removeAll(action)) {
QActionEvent e(QEvent::ActionRemoved, action);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
}
@@ -2394,7 +2388,7 @@ QPainterPath QGraphicsWidget::shape() const
bool QGraphicsWidget::close()
{
QCloseEvent closeEvent;
- QApplication::sendEvent(this, &closeEvent);
+ QCoreApplication::sendEvent(this, &closeEvent);
if (!closeEvent.isAccepted()) {
return false;
}
diff --git a/src/widgets/graphicsview/qgraphicswidget.h b/src/widgets/graphicsview/qgraphicswidget.h
index 481fb55db3..8223b921c9 100644
--- a/src/widgets/graphicsview/qgraphicswidget.h
+++ b/src/widgets/graphicsview/qgraphicswidget.h
@@ -111,9 +111,11 @@ public:
inline QRectF rect() const { return QRectF(QPointF(), size()); }
void setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
+ void setContentsMargins(QMarginsF margins);
void getContentsMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const override;
void setWindowFrameMargins(qreal left, qreal top, qreal right, qreal bottom);
+ void setWindowFrameMargins(QMarginsF margins);
void getWindowFrameMargins(qreal *left, qreal *top, qreal *right, qreal *bottom) const;
void unsetWindowFrameMargins();
QRectF windowFrameGeometry() const;
diff --git a/src/widgets/graphicsview/qgraphicswidget_p.cpp b/src/widgets/graphicsview/qgraphicswidget_p.cpp
index 1514fca456..0156faf8e4 100644
--- a/src/widgets/graphicsview/qgraphicswidget_p.cpp
+++ b/src/widgets/graphicsview/qgraphicswidget_p.cpp
@@ -51,6 +51,8 @@
#include <QtWidgets/QStyleOptionTitleBar>
#include <QtWidgets/QGraphicsSceneMouseEvent>
+#include <private/qmemory_p.h>
+
QT_BEGIN_NAMESPACE
void QGraphicsWidgetPrivate::init(QGraphicsItem *parentItem, Qt::WindowFlags wFlags)
@@ -108,10 +110,6 @@ QGraphicsWidgetPrivate::QGraphicsWidgetPrivate()
QGraphicsWidgetPrivate::~QGraphicsWidgetPrivate()
{
- // Remove any lazily allocated data
- delete[] margins;
- delete[] windowFrameMargins;
- delete windowData;
}
/*!
@@ -122,11 +120,8 @@ QGraphicsWidgetPrivate::~QGraphicsWidgetPrivate()
*/
void QGraphicsWidgetPrivate::ensureMargins() const
{
- if (!margins) {
- margins = new qreal[4];
- for (int i = 0; i < 4; ++i)
- margins[i] = 0;
- }
+ if (!margins)
+ margins = qt_make_unique<QMarginsF>();
}
/*!
@@ -137,11 +132,8 @@ void QGraphicsWidgetPrivate::ensureMargins() const
*/
void QGraphicsWidgetPrivate::ensureWindowFrameMargins() const
{
- if (!windowFrameMargins) {
- windowFrameMargins = new qreal[4];
- for (int i = 0; i < 4; ++i)
- windowFrameMargins[i] = 0;
- }
+ if (!windowFrameMargins)
+ windowFrameMargins = qt_make_unique<QMarginsF>();
}
/*!
@@ -153,7 +145,7 @@ void QGraphicsWidgetPrivate::ensureWindowFrameMargins() const
void QGraphicsWidgetPrivate::ensureWindowData()
{
if (!windowData)
- windowData = new WindowData;
+ windowData = qt_make_unique<WindowData>();
}
void QGraphicsWidgetPrivate::setPalette_helper(const QPalette &palette)
@@ -196,7 +188,7 @@ void QGraphicsWidgetPrivate::updatePalette(const QPalette &palette)
// Notify change.
QEvent event(QEvent::PaletteChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
}
void QGraphicsWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
@@ -218,7 +210,7 @@ void QGraphicsWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direc
// Send the notification event to this widget item.
QEvent e(QEvent::LayoutDirectionChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
void QGraphicsWidgetPrivate::resolveLayoutDirection()
@@ -232,9 +224,9 @@ void QGraphicsWidgetPrivate::resolveLayoutDirection()
} else if (scene) {
// ### shouldn't the scene have a layoutdirection really? how does
// ### QGraphicsWidget get changes from QApplication::layoutDirection?
- setLayoutDirection_helper(QApplication::layoutDirection());
+ setLayoutDirection_helper(QGuiApplication::layoutDirection());
} else {
- setLayoutDirection_helper(QApplication::layoutDirection());
+ setLayoutDirection_helper(QGuiApplication::layoutDirection());
}
}
@@ -296,7 +288,7 @@ void QGraphicsWidgetPrivate::updateFont(const QFont &font)
return;
// Notify change.
QEvent event(QEvent::FontChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
}
QFont QGraphicsWidgetPrivate::naturalWidgetFont() const
@@ -372,8 +364,8 @@ void QGraphicsWidgetPrivate::windowFrameMouseReleaseEvent(QGraphicsSceneMouseEve
bar.rect.setHeight(q->style()->pixelMetric(QStyle::PM_TitleBarHeight, &bar));
QPointF pos = event->pos();
if (windowFrameMargins) {
- pos.rx() += windowFrameMargins[Left];
- pos.ry() += windowFrameMargins[Top];
+ pos.rx() += windowFrameMargins->left();
+ pos.ry() += windowFrameMargins->top();
}
bar.subControls = QStyle::SC_TitleBarCloseButton;
if (q->style()->subControlRect(QStyle::CC_TitleBar, &bar,
@@ -669,8 +661,8 @@ void QGraphicsWidgetPrivate::windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent
QStyleOptionTitleBar bar;
// make sure that the coordinates (rect and pos) we send to the style are positive.
if (windowFrameMargins) {
- pos.rx() += windowFrameMargins[Left];
- pos.ry() += windowFrameMargins[Top];
+ pos.rx() += windowFrameMargins->left();
+ pos.ry() += windowFrameMargins->top();
}
initStyleOptionTitleBar(&bar);
bar.rect = q->windowFrameRect().toRect();
@@ -699,13 +691,6 @@ void QGraphicsWidgetPrivate::windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent
case Qt::TitleBarArea:
windowData->buttonRect = q->style()->subControlRect(
QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarCloseButton, 0);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // On mac we should hover if we are in the 'area' of the buttons
- windowData->buttonRect |= q->style()->subControlRect(
- QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMinButton, 0);
- windowData->buttonRect |= q->style()->subControlRect(
- QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMaxButton, 0);
-#endif
if (windowData->buttonRect.contains(pos.toPoint()))
windowData->buttonMouseOver = true;
event->ignore();
diff --git a/src/widgets/graphicsview/qgraphicswidget_p.h b/src/widgets/graphicsview/qgraphicswidget_p.h
index 505a2a24c0..e4cc2c3016 100644
--- a/src/widgets/graphicsview/qgraphicswidget_p.h
+++ b/src/widgets/graphicsview/qgraphicswidget_p.h
@@ -60,6 +60,8 @@
#include <QtWidgets/qsizepolicy.h>
#include <QtWidgets/qstyle.h>
+#include <memory>
+
QT_REQUIRE_CONFIG(graphicsview);
QT_BEGIN_NAMESPACE
@@ -78,11 +80,10 @@ public:
qreal titleBarHeight(const QStyleOptionTitleBar &options) const;
// Margins
- enum {Left, Top, Right, Bottom};
- mutable qreal *margins;
+ mutable std::unique_ptr<QMarginsF> margins;
void ensureMargins() const;
- void fixFocusChainBeforeReparenting(QGraphicsWidget *newParent, QGraphicsScene *oldScene, QGraphicsScene *newScene = 0);
+ void fixFocusChainBeforeReparenting(QGraphicsWidget *newParent, QGraphicsScene *oldScene, QGraphicsScene *newScene = nullptr);
void setLayout_helper(QGraphicsLayout *l);
// Layouts
@@ -189,11 +190,12 @@ public:
, buttonMouseOver(false)
, buttonSunken(false)
{}
- } *windowData;
+ };
+ std::unique_ptr<WindowData> windowData;
void ensureWindowData();
bool setWindowFrameMargins;
- mutable qreal *windowFrameMargins;
+ mutable std::unique_ptr<QMarginsF> windowFrameMargins;
void ensureWindowFrameMargins() const;
#ifndef QT_NO_ACTION
diff --git a/src/widgets/graphicsview/qsimplex_p.cpp b/src/widgets/graphicsview/qsimplex_p.cpp
index e6ffa856f1..e18f1fa4c4 100644
--- a/src/widgets/graphicsview/qsimplex_p.cpp
+++ b/src/widgets/graphicsview/qsimplex_p.cpp
@@ -164,7 +164,7 @@ bool QSimplex::setConstraints(const QList<QSimplexConstraint *> &newConstraints)
for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
variablesSet.insert(it.key());
}
- variables = variablesSet.toList();
+ variables = variablesSet.values();
// Set Variables reverse mapping
// We also need to be able to find the index for a given variable, to do that
diff --git a/src/widgets/graphicsview/qsimplex_p.h b/src/widgets/graphicsview/qsimplex_p.h
index 369f2f5f82..a69cef6115 100644
--- a/src/widgets/graphicsview/qsimplex_p.h
+++ b/src/widgets/graphicsview/qsimplex_p.h
@@ -82,7 +82,7 @@ struct QSimplexVariable
*/
struct QSimplexConstraint
{
- QSimplexConstraint() : constant(0), ratio(Equal), artificial(0) {}
+ QSimplexConstraint() : constant(0), ratio(Equal), artificial(nullptr) {}
enum Ratio {
LessOrEqual = 0,
diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp
index 7d5e014dd5..c2afed775c 100644
--- a/src/widgets/itemviews/qabstractitemview.cpp
+++ b/src/widgets/itemviews/qabstractitemview.cpp
@@ -61,6 +61,7 @@
#include <qstyleditemdelegate.h>
#include <private/qabstractitemview_p.h>
#include <private/qabstractitemmodel_p.h>
+#include <private/qapplication_p.h>
#include <private/qguiapplication_p.h>
#include <private/qscrollbar_p.h>
#ifndef QT_NO_ACCESSIBILITY
@@ -180,7 +181,7 @@ void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index
QString statustip = model->data(index, Qt::StatusTipRole).toString();
if (parent && (shouldClearStatusTip || !statustip.isEmpty())) {
QStatusTipEvent tip(statustip);
- QApplication::sendEvent(parent, &tip);
+ QCoreApplication::sendEvent(parent, &tip);
shouldClearStatusTip = !statustip.isEmpty();
}
#endif
@@ -189,7 +190,7 @@ void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index
if (parent && shouldClearStatusTip) {
QString emptyString;
QStatusTipEvent tip( emptyString );
- QApplication::sendEvent(parent, &tip);
+ QCoreApplication::sendEvent(parent, &tip);
}
#endif
emit q->viewportEntered();
@@ -521,7 +522,7 @@ void QAbstractItemViewPrivate::_q_scrollerStateChanged()
the mouse was pressed on is specified by \a index. The signal is
only emitted when the index is valid.
- Use the QApplication::mouseButtons() function to get the state
+ Use the QGuiApplication::mouseButtons() function to get the state
of the mouse buttons.
\sa activated(), clicked(), doubleClicked(), entered()
@@ -1713,7 +1714,7 @@ bool QAbstractItemView::viewportEvent(QEvent *event)
if (d->shouldClearStatusTip && d->parent) {
QString empty;
QStatusTipEvent tip(empty);
- QApplication::sendEvent(d->parent, &tip);
+ QCoreApplication::sendEvent(d->parent, &tip);
d->shouldClearStatusTip = false;
}
#endif
@@ -1965,6 +1966,7 @@ void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
if ((event->button() == Qt::LeftButton) && !edit(persistent, DoubleClicked, event)
&& !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
emit activated(persistent);
+ d->pressedIndex = QModelIndex();
}
#if QT_CONFIG(draganddrop)
@@ -2290,7 +2292,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
#ifdef QT_KEYPAD_NAVIGATION
switch (event->key()) {
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus()) {
setEditFocus(true);
return;
@@ -2298,7 +2300,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
}
break;
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && hasEditFocus()) {
setEditFocus(false);
} else {
event->ignore();
@@ -2309,7 +2311,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
// Let's ignore vertical navigation events, only if there is no other widget
// what can take the focus in vertical direction. This means widget can handle navigation events
// even the widget don't have edit focus, and there is no other widget in requested direction.
- if(QApplication::keypadNavigationEnabled() && !hasEditFocus()
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()
&& QWidgetPrivate::canKeypadNavigate(Qt::Vertical)) {
event->ignore();
return;
@@ -2318,14 +2320,14 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
case Qt::Key_Left:
case Qt::Key_Right:
// Similar logic as in up and down events
- if(QApplication::keypadNavigationEnabled() && !hasEditFocus()
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()
&& (QWidgetPrivate::canKeypadNavigate(Qt::Horizontal) || QWidgetPrivate::inTabWidget(this))) {
event->ignore();
return;
}
break;
default:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
event->ignore();
return;
}
@@ -2338,7 +2340,7 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
if (d->model)
variant = d->model->data(currentIndex(), Qt::DisplayRole);
if (variant.type() == QVariant::String)
- QApplication::clipboard()->setText(variant.toString());
+ QGuiApplication::clipboard()->setText(variant.toString());
event->accept();
}
#endif
@@ -2413,7 +2415,8 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event)
case Qt::Key_Down:
case Qt::Key_Up:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical)) {
+ if (QApplicationPrivate::keypadNavigationEnabled()
+ && QWidgetPrivate::canKeypadNavigate(Qt::Vertical)) {
event->accept(); // don't change focus
break;
}
@@ -2845,7 +2848,7 @@ void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndE
}
QPointer<QWidget> ed = editor;
- QApplication::sendPostedEvents(editor, 0);
+ QCoreApplication::sendPostedEvents(editor, 0);
editor = ed;
if (!isPersistent && editor)
@@ -3725,12 +3728,10 @@ QStyleOptionViewItem QAbstractItemView::viewOptions() const
option.state &= ~QStyle::State_MouseOver;
option.font = font();
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
// On mac the focus appearance follows window activation
// not widget activation
if (!hasFocus())
option.state &= ~QStyle::State_Active;
-#endif
option.state &= ~QStyle::State_HasFocus;
if (d->iconSize.isValid()) {
@@ -3957,7 +3958,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QM
keyModifiers = (static_cast<const QInputEvent*>(event))->modifiers();
break;
default:
- keyModifiers = QApplication::keyboardModifiers();
+ keyModifiers = QGuiApplication::keyboardModifiers();
}
}
switch (d->selectionMode) {
@@ -4015,7 +4016,7 @@ QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionComm
QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionCommand(
const QModelIndex &index, const QEvent *event) const
{
- Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
+ Qt::KeyboardModifiers modifiers = QGuiApplication::keyboardModifiers();
if (event) {
switch (event->type()) {
case QEvent::MouseMove: {
@@ -4425,7 +4426,7 @@ bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *even
w->setFocus();
if (event)
- QApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);
+ QCoreApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);
return true;
}
@@ -4461,15 +4462,8 @@ QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes,
if (paintPairs.isEmpty())
return QPixmap();
- qreal scale = 1.0f;
-
- Q_Q(const QAbstractItemView);
- QWidget *window = q->window();
- if (window) {
- QWindow *windowHandle = window->windowHandle();
- if (windowHandle)
- scale = windowHandle->devicePixelRatio();
- }
+ QWindow *window = windowHandle(WindowHandleMode::Closest);
+ const qreal scale = window ? window->devicePixelRatio() : qreal(1);
QPixmap pixmap(r->size() * scale);
pixmap.setDevicePixelRatio(scale);
diff --git a/src/widgets/itemviews/qcolumnview_p.h b/src/widgets/itemviews/qcolumnview_p.h
index 7b36b1f3da..c60579255e 100644
--- a/src/widgets/itemviews/qcolumnview_p.h
+++ b/src/widgets/itemviews/qcolumnview_p.h
@@ -74,7 +74,7 @@ QT_BEGIN_NAMESPACE
class QColumnViewPreviewColumn : public QAbstractItemView {
public:
- explicit QColumnViewPreviewColumn(QWidget *parent) : QAbstractItemView(parent), previewWidget(0) {
+ explicit QColumnViewPreviewColumn(QWidget *parent) : QAbstractItemView(parent), previewWidget(nullptr) {
}
void setPreviewWidget(QWidget *widget) {
@@ -186,7 +186,7 @@ class QColumnViewDelegate : public QItemDelegate
{
public:
- explicit QColumnViewDelegate(QObject *parent = 0) : QItemDelegate(parent) {}
+ explicit QColumnViewDelegate(QObject *parent = nullptr) : QItemDelegate(parent) {}
~QColumnViewDelegate() {}
void paint(QPainter *painter,
diff --git a/src/widgets/itemviews/qcolumnviewgrip_p.h b/src/widgets/itemviews/qcolumnviewgrip_p.h
index 5eb8012204..4311edbeb4 100644
--- a/src/widgets/itemviews/qcolumnviewgrip_p.h
+++ b/src/widgets/itemviews/qcolumnviewgrip_p.h
@@ -68,12 +68,12 @@ Q_SIGNALS:
void gripMoved(int offset);
public:
- explicit QColumnViewGrip(QWidget *parent = 0);
+ explicit QColumnViewGrip(QWidget *parent = nullptr);
~QColumnViewGrip();
int moveGrip(int offset);
protected:
- QColumnViewGrip(QColumnViewGripPrivate &, QWidget *parent = 0, Qt::WindowFlags f = 0);
+ QColumnViewGrip(QColumnViewGripPrivate &, QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
void paintEvent(QPaintEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
diff --git a/src/widgets/itemviews/qdirmodel.cpp b/src/widgets/itemviews/qdirmodel.cpp
index b94c31fb42..13a1bbd8eb 100644
--- a/src/widgets/itemviews/qdirmodel.cpp
+++ b/src/widgets/itemviews/qdirmodel.cpp
@@ -1086,7 +1086,7 @@ QString QDirModel::filePath(const QModelIndex &index) const
if (d->indexValid(index)) {
QFileInfo fi = fileInfo(index);
if (d->resolveSymlinks && fi.isSymLink())
- fi = d->resolvedInfo(fi);
+ fi = QDirModelPrivate::resolvedInfo(fi);
return QDir::cleanPath(fi.absoluteFilePath());
}
return QString(); // root path
@@ -1108,7 +1108,7 @@ QString QDirModel::fileName(const QModelIndex &index) const
if (QFileSystemEntry::isRootPath(path))
return path;
if (d->resolveSymlinks && info.isSymLink())
- info = d->resolvedInfo(info);
+ info = QDirModelPrivate::resolvedInfo(info);
return info.fileName();
}
diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp
index 1fcd5bdef2..d7bdf6aa4c 100644
--- a/src/widgets/itemviews/qheaderview.cpp
+++ b/src/widgets/itemviews/qheaderview.cpp
@@ -189,7 +189,7 @@ static const int maxSizeSection = 1048575; // since section size is in a bitfiel
The following values are obsolete:
\value Custom Use Fixed instead.
- \sa setResizeMode(), setSectionResizeMode(), stretchLastSection, minimumSectionSize
+ \sa setSectionResizeMode(), stretchLastSection, minimumSectionSize
*/
/*!
@@ -880,7 +880,7 @@ void QHeaderView::swapSections(int first, int second)
size equal to zero is however not recommended. In that situation hideSection
should be used instead.
- \sa sectionResized(), resizeMode(), sectionSize(), hideSection()
+ \sa sectionResized(), sectionSize(), hideSection()
*/
void QHeaderView::resizeSection(int logical, int size)
@@ -960,7 +960,7 @@ void QHeaderView::resizeSection(int logical, int size)
Resizes the sections according to the given \a mode, ignoring the current
resize mode.
- \sa resizeMode(), sectionResized()
+ \sa sectionResized()
*/
void QHeaderView::resizeSections(QHeaderView::ResizeMode mode)
@@ -1139,16 +1139,6 @@ void QHeaderView::setSectionsMovable(bool movable)
d->movableSections = movable;
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \obsolete
- \fn void QHeaderView::setMovable(bool movable)
-
- Use setSectionsMovable instead.
-
- \sa setSectionsMovable()
-*/
-
/*!
\since 5.0
@@ -1167,16 +1157,6 @@ bool QHeaderView::sectionsMovable() const
return d->movableSections;
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \obsolete
- \fn bool QHeaderView::isMovable() const
-
- Use sectionsMovable instead.
-
- \sa sectionsMovable()
-*/
-
/*!
\property QHeaderView::firstSectionMovable
\brief Whether the first column can be moved by the user
@@ -1223,16 +1203,6 @@ void QHeaderView::setSectionsClickable(bool clickable)
d->clickableSections = clickable;
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \obsolete
- \fn void QHeaderView::setClickable(bool clickable)
-
- Use setSectionsClickable instead.
-
- \sa setSectionsClickable()
-*/
-
/*!
\since 5.0
@@ -1249,16 +1219,6 @@ bool QHeaderView::sectionsClickable() const
return d->clickableSections;
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \obsolete
- \fn bool QHeaderView::isClickable() const
-
- Use sectionsClickable instead.
-
- \sa sectionsClickable()
-*/
-
void QHeaderView::setHighlightSections(bool highlight)
{
Q_D(QHeaderView);
@@ -1277,7 +1237,7 @@ bool QHeaderView::highlightSections() const
Sets the constraints on how the header can be resized to those described
by the given \a mode.
- \sa resizeMode(), length(), sectionResized()
+ \sa length(), sectionResized()
*/
void QHeaderView::setSectionResizeMode(ResizeMode mode)
@@ -1327,26 +1287,6 @@ void QHeaderView::setSectionResizeMode(int logicalIndex, ResizeMode mode)
d->doDelayedResizeSections(); // section sizes may change as a result of the new mode
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \overload
- \obsolete
- \fn void QHeaderView::setResizeMode(int logicalIndex, ResizeMode mode)
-
- Use setSectionResizeMode instead.
-
- \sa setSectionResizeMode()
-*/
-
-/*!
- \obsolete
- \fn void QHeaderView::setResizeMode(ResizeMode mode)
-
- Use setSectionResizeMode instead.
-
- \sa setSectionResizeMode()
-*/
-
/*!
\since 5.0
@@ -1407,16 +1347,6 @@ int QHeaderView::resizeContentsPrecision() const
return d->resizeContentsPrecision;
}
-// ### Qt 6 - remove this obsolete function
-/*!
- \obsolete
- \fn QHeaderView::ResizeMode QHeaderView::resizeMode(int logicalIndex) const
-
- Use sectionResizeMode instead.
-
- \sa sectionResizeMode()
-*/
-
/*!
\since 4.1
@@ -1424,7 +1354,7 @@ int QHeaderView::resizeContentsPrecision() const
views, this can be used to see if the headerview needs to resize the
sections when the view's geometry changes.
- \sa stretchLastSection, resizeMode()
+ \sa stretchLastSection
*/
int QHeaderView::stretchSectionCount() const
@@ -2640,7 +2570,6 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
if (pos < 0 && d->state != QHeaderViewPrivate::SelectSections)
return;
if (e->buttons() == Qt::NoButton) {
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
// Under Cocoa, when the mouse button is released, may include an extra
// simulated mouse moved event. The state of the buttons when this event
// is generated is already "no button" and the code below gets executed
@@ -2648,7 +2577,6 @@ void QHeaderView::mouseMoveEvent(QMouseEvent *e)
// column dragging from working. So this code is disabled under Cocoa.
d->state = QHeaderViewPrivate::NoState;
d->pressed = -1;
-#endif
}
switch (d->state) {
case QHeaderViewPrivate::ResizeSection: {
@@ -2896,7 +2824,7 @@ bool QHeaderView::viewportEvent(QEvent *e)
case QEvent::Wheel: {
QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea *>(parentWidget());
if (asa)
- return QApplication::sendEvent(asa->viewport(), e);
+ return QCoreApplication::sendEvent(asa->viewport(), e);
break; }
default:
break;
diff --git a/src/widgets/itemviews/qheaderview_p.h b/src/widgets/itemviews/qheaderview_p.h
index d9fc1baec5..766adef36d 100644
--- a/src/widgets/itemviews/qheaderview_p.h
+++ b/src/widgets/itemviews/qheaderview_p.h
@@ -102,7 +102,7 @@ public:
lastSectionLogicalIdx(-1), // Only trust when we stretch last section
sectionIndicatorOffset(0),
#if QT_CONFIG(label)
- sectionIndicator(0),
+ sectionIndicator(nullptr),
#endif
globalResizeMode(QHeaderView::Interactive),
sectionStartposRecalc(true),
diff --git a/src/widgets/itemviews/qitemeditorfactory.cpp b/src/widgets/itemviews/qitemeditorfactory.cpp
index 2d49dd4421..8ed2ee5f28 100644
--- a/src/widgets/itemviews/qitemeditorfactory.cpp
+++ b/src/widgets/itemviews/qitemeditorfactory.cpp
@@ -570,11 +570,9 @@ void QExpandingLineEdit::changeEvent(QEvent *e)
void QExpandingLineEdit::updateMinimumWidth()
{
- int left, right;
- getTextMargins(&left, 0, &right, 0);
- int width = left + right + 4 /*horizontalMargin in qlineedit.cpp*/;
- getContentsMargins(&left, 0, &right, 0);
- width += left + right;
+ const QMargins tm = textMargins();
+ const QMargins cm = contentsMargins();
+ const int width = tm.left() + tm.right() + cm.left() + cm.right() + 4 /*horizontalMargin in qlineedit.cpp*/;
QStyleOptionFrame opt;
initStyleOption(&opt);
diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp
index 568084640a..04cddf2926 100644
--- a/src/widgets/itemviews/qlistview.cpp
+++ b/src/widgets/itemviews/qlistview.cpp
@@ -54,6 +54,7 @@
#if QT_CONFIG(rubberband)
#include <qrubberband.h>
#endif
+#include <private/qapplication_p.h>
#include <private/qlistview_p.h>
#include <private/qscrollbar_p.h>
#include <qdebug.h>
@@ -810,24 +811,24 @@ void QListView::mouseReleaseEvent(QMouseEvent *e)
void QListView::wheelEvent(QWheelEvent *e)
{
Q_D(QListView);
- if (e->orientation() == Qt::Vertical) {
+ if (qAbs(e->angleDelta().y()) > qAbs(e->angleDelta().x())) {
if (e->angleDelta().x() == 0
- && ((d->flow == TopToBottom && d->wrap) || (d->flow == LeftToRight && !d->wrap))
- && d->vbar->minimum() == 0 && d->vbar->maximum() == 0) {
+ && ((d->flow == TopToBottom && d->wrap) || (d->flow == LeftToRight && !d->wrap))
+ && d->vbar->minimum() == 0 && d->vbar->maximum() == 0) {
QPoint pixelDelta(e->pixelDelta().y(), e->pixelDelta().x());
QPoint angleDelta(e->angleDelta().y(), e->angleDelta().x());
- QWheelEvent hwe(e->pos(), e->globalPos(), pixelDelta, angleDelta, e->delta(),
- Qt::Horizontal, e->buttons(), e->modifiers(), e->phase(), e->source(), e->inverted());
+ QWheelEvent hwe(e->position(), e->globalPosition(), pixelDelta, angleDelta,
+ e->buttons(), e->modifiers(), e->phase(), e->inverted(), e->source());
if (e->spontaneous())
qt_sendSpontaneousEvent(d->hbar, &hwe);
else
- QApplication::sendEvent(d->hbar, &hwe);
+ QCoreApplication::sendEvent(d->hbar, &hwe);
e->setAccepted(hwe.isAccepted());
} else {
- QApplication::sendEvent(d->vbar, e);
+ QCoreApplication::sendEvent(d->vbar, e);
}
} else {
- QApplication::sendEvent(d->hbar, e);
+ QCoreApplication::sendEvent(d->hbar, e);
}
}
#endif // QT_CONFIG(wheelevent)
@@ -1185,7 +1186,7 @@ QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
rect.translate(0, -rect.height());
if (rect.bottom() <= 0) {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
int row = d->batchStartRow() - 1;
while (row >= 0 && d->isHiddenOrDisabled(row))
--row;
@@ -1214,7 +1215,7 @@ QModelIndex QListView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
rect.translate(0, rect.height());
if (rect.top() >= contents.height()) {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
int rowCount = d->model->rowCount(d->root);
int row = 0;
while (row < rowCount && d->isHiddenOrDisabled(row))
diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h
index c6810f8fdc..86331bb862 100644
--- a/src/widgets/itemviews/qlistview_p.h
+++ b/src/widgets/itemviews/qlistview_p.h
@@ -248,7 +248,7 @@ private:
class QIconModeViewBase : public QCommonListViewBase
{
public:
- QIconModeViewBase(QListView *q, QListViewPrivate *d) : QCommonListViewBase(q, d), interSectingVector(0) {}
+ QIconModeViewBase(QListView *q, QListViewPrivate *d) : QCommonListViewBase(q, d), interSectingVector(nullptr) {}
QBspTree tree;
QVector<QListViewItem> items;
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index 37bb370e73..e7dcfac403 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -930,12 +930,14 @@ QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
\sa Qt::AlignmentFlag
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QListWidgetItem::backgroundColor() const
\obsolete
This function is deprecated. Use background() instead.
*/
+#endif
/*!
\fn QBrush QListWidgetItem::background() const
@@ -946,6 +948,7 @@ QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
\sa setBackground(), foreground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QListWidgetItem::textColor() const
\obsolete
@@ -954,6 +957,7 @@ QDataStream &operator>>(QDataStream &in, QListWidgetItem &item)
This function is deprecated. Use foreground() instead.
*/
+#endif
/*!
\fn QBrush QListWidgetItem::foreground() const
@@ -1119,12 +1123,14 @@ void QListWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa background(), setForeground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn void QListWidgetItem::setTextColor(const QColor &color)
\obsolete
This function is deprecated. Use setForeground() instead.
*/
+#endif
/*!
\fn void QListWidgetItem::setForeground(const QBrush &brush)
diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp
index b05662f6bc..11c5be10fd 100644
--- a/src/widgets/itemviews/qtableview.cpp
+++ b/src/widgets/itemviews/qtableview.cpp
@@ -51,6 +51,7 @@
#if QT_CONFIG(abstractbutton)
#include <qabstractbutton.h>
#endif
+#include <private/qapplication_p.h>
#include <private/qtableview_p.h>
#include <private/qheaderview_p.h>
#include <private/qscrollbar_p.h>
@@ -58,6 +59,8 @@
#include <qaccessible.h>
#endif
+#include <algorithm>
+
QT_BEGIN_NAMESPACE
/** \internal
@@ -65,7 +68,7 @@ QT_BEGIN_NAMESPACE
*/
void QSpanCollection::addSpan(QSpanCollection::Span *span)
{
- spans.append(span);
+ spans.push_back(span);
Index::iterator it_y = index.lowerBound(-span->top());
if (it_y == index.end() || it_y.key() != -span->top()) {
//there is no spans that starts with the row in the index, so create a sublist for it.
@@ -132,7 +135,7 @@ void QSpanCollection::updateSpan(QSpanCollection::Span *span, int old_height)
}
if (span->width() == 0 && span->height() == 0) {
- spans.removeOne(span);
+ spans.remove(span);
delete span;
}
}
@@ -169,7 +172,7 @@ void QSpanCollection::clear()
/** \internal
* return a list to all the spans that spans over cells in the given rectangle
*/
-QList<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w, int h) const
+QSet<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w, int h) const
{
QSet<Span *> list;
Index::const_iterator it_y = index.lowerBound(-y);
@@ -191,7 +194,7 @@ QList<QSpanCollection::Span *> QSpanCollection::spansInRect(int x, int y, int w,
break;
--it_y;
}
- return list.toList();
+ return list;
}
#undef DEBUG_SPAN_UPDATE
@@ -210,17 +213,16 @@ QDebug operator<<(QDebug str, const QSpanCollection::Span &span)
void QSpanCollection::updateInsertedRows(int start, int end)
{
#ifdef DEBUG_SPAN_UPDATE
- qDebug() << start << end << endl << index;
+ qDebug() << start << end << Qt::endl << index;
#endif
- if (spans.isEmpty())
+ if (spans.empty())
return;
int delta = end - start + 1;
#ifdef DEBUG_SPAN_UPDATE
qDebug("Before");
#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ++it) {
- Span *span = *it;
+ for (Span *span : spans) {
#ifdef DEBUG_SPAN_UPDATE
qDebug() << span << *span;
#endif
@@ -258,17 +260,16 @@ void QSpanCollection::updateInsertedRows(int start, int end)
void QSpanCollection::updateInsertedColumns(int start, int end)
{
#ifdef DEBUG_SPAN_UPDATE
- qDebug() << start << end << endl << index;
+ qDebug() << start << end << Qt::endl << index;
#endif
- if (spans.isEmpty())
+ if (spans.empty())
return;
int delta = end - start + 1;
#ifdef DEBUG_SPAN_UPDATE
qDebug("Before");
#endif
- for (SpanList::iterator it = spans.begin(); it != spans.end(); ++it) {
- Span *span = *it;
+ for (Span *span : spans) {
#ifdef DEBUG_SPAN_UPDATE
qDebug() << span << *span;
#endif
@@ -339,9 +340,9 @@ bool QSpanCollection::cleanSpanSubIndex(QSpanCollection::SubIndex &subindex, int
void QSpanCollection::updateRemovedRows(int start, int end)
{
#ifdef DEBUG_SPAN_UPDATE
- qDebug() << start << end << endl << index;
+ qDebug() << start << end << Qt::endl << index;
#endif
- if (spans.isEmpty())
+ if (spans.empty())
return;
SpanList spansToBeDeleted;
@@ -377,7 +378,7 @@ void QSpanCollection::updateRemovedRows(int start, int end)
if (span->m_top == span->m_bottom && span->m_left == span->m_right)
span->will_be_deleted = true;
if (span->will_be_deleted) {
- spansToBeDeleted.append(span);
+ spansToBeDeleted.push_back(span);
it = spans.erase(it);
} else {
++it;
@@ -389,7 +390,7 @@ void QSpanCollection::updateRemovedRows(int start, int end)
foreach (QSpanCollection::Span *span, spans)
qDebug() << span << *span;
#endif
- if (spans.isEmpty()) {
+ if (spans.empty()) {
qDeleteAll(spansToBeDeleted);
index.clear();
return;
@@ -466,9 +467,9 @@ void QSpanCollection::updateRemovedRows(int start, int end)
void QSpanCollection::updateRemovedColumns(int start, int end)
{
#ifdef DEBUG_SPAN_UPDATE
- qDebug() << start << end << endl << index;
+ qDebug() << start << end << Qt::endl << index;
#endif
- if (spans.isEmpty())
+ if (spans.empty())
return;
SpanList toBeDeleted;
@@ -504,7 +505,7 @@ void QSpanCollection::updateRemovedColumns(int start, int end)
if (span->m_top == span->m_bottom && span->m_left == span->m_right)
span->will_be_deleted = true;
if (span->will_be_deleted) {
- toBeDeleted.append(span);
+ toBeDeleted.push_back(span);
it = spans.erase(it);
} else {
++it;
@@ -516,7 +517,7 @@ void QSpanCollection::updateRemovedColumns(int start, int end)
foreach (QSpanCollection::Span *span, spans)
qDebug() << span << *span;
#endif
- if (spans.isEmpty()) {
+ if (spans.empty()) {
qDeleteAll(toBeDeleted);
index.clear();
return;
@@ -552,13 +553,13 @@ bool QSpanCollection::checkConsistency() const
for (SubIndex::const_iterator it = subIndex.begin(); it != subIndex.end(); ++it) {
int x = -it.key();
Span *span = it.value();
- if (!spans.contains(span) || span->left() != x
- || y < span->top() || y > span->bottom())
+ const bool contains = std::find(spans.begin(), spans.end(), span) != spans.end();
+ if (!contains || span->left() != x || y < span->top() || y > span->bottom())
return false;
}
}
- foreach (const Span *span, spans) {
+ for (const Span *span : spans) {
if (span->width() < 1 || span->height() < 1
|| (span->width() == 1 && span->height() == 1))
return false;
@@ -863,19 +864,17 @@ void QTableViewPrivate::drawAndClipSpans(const QRegion &area, QPainter *painter,
bool alternateBase = false;
QRegion region = viewport->rect();
- QList<QSpanCollection::Span *> visibleSpans;
+ QSet<QSpanCollection::Span *> visibleSpans;
bool sectionMoved = verticalHeader->sectionsMoved() || horizontalHeader->sectionsMoved();
if (!sectionMoved) {
visibleSpans = spans.spansInRect(logicalColumn(firstVisualColumn), logicalRow(firstVisualRow),
lastVisualColumn - firstVisualColumn + 1, lastVisualRow - firstVisualRow + 1);
} else {
- QSet<QSpanCollection::Span *> set;
for(int x = firstVisualColumn; x <= lastVisualColumn; x++)
for(int y = firstVisualRow; y <= lastVisualRow; y++)
- set.insert(spans.spanAt(x,y));
- set.remove(0);
- visibleSpans = set.toList();
+ visibleSpans.insert(spans.spanAt(x,y));
+ visibleSpans.remove(nullptr);
}
for (QSpanCollection::Span *span : qAsConst(visibleSpans)) {
@@ -1712,7 +1711,7 @@ QModelIndex QTableView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifi
case MoveUp: {
int originalRow = visualRow;
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && visualRow == 0)
+ if (QApplicationPrivate::keypadNavigationEnabled() && visualRow == 0)
visualRow = d->visualRow(model()->rowCount() - 1) + 1;
// FIXME? visualRow = bottom + 1;
#endif
@@ -1741,7 +1740,7 @@ QModelIndex QTableView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifi
visualRow = d->visualRow(d->rowSpanEndLogical(span.top(), span.height()));
}
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && visualRow >= bottom)
+ if (QApplicationPrivate::keypadNavigationEnabled() && visualRow >= bottom)
visualRow = -1;
#endif
int r = d->logicalRow(visualRow);
@@ -1925,7 +1924,7 @@ void QTableView::setSelection(const QRect &rect, QItemSelectionModel::SelectionF
int right = qMax(d->visualColumn(tl.column()), d->visualColumn(br.column()));
do {
expanded = false;
- foreach (QSpanCollection::Span *it, d->spans.spans) {
+ for (QSpanCollection::Span *it : d->spans.spans) {
const QSpanCollection::Span &span = *it;
int t = d->visualRow(span.top());
int l = d->visualColumn(span.left());
@@ -3332,7 +3331,7 @@ void QTableViewPrivate::selectRow(int row, bool anchor)
if (q->selectionMode() != QTableView::SingleSelection
&& command.testFlag(QItemSelectionModel::Toggle)) {
if (anchor)
- ctrlDragSelectionFlag = verticalHeader->selectionModel()->selectedRows().contains(index)
+ ctrlDragSelectionFlag = verticalHeader->selectionModel()->selectedRows(column).contains(index)
? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
command &= ~QItemSelectionModel::Toggle;
command |= ctrlDragSelectionFlag;
diff --git a/src/widgets/itemviews/qtableview_p.h b/src/widgets/itemviews/qtableview_p.h
index d55462c28b..8f174351d2 100644
--- a/src/widgets/itemviews/qtableview_p.h
+++ b/src/widgets/itemviews/qtableview_p.h
@@ -53,12 +53,13 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/QList>
-#include <QtCore/QLinkedList>
#include <QtCore/QMap>
#include <QtCore/QSet>
#include <QtCore/QDebug>
#include "private/qabstractitemview_p.h"
+#include <list>
+
QT_REQUIRE_CONFIG(tableview);
QT_BEGIN_NAMESPACE
@@ -104,7 +105,7 @@ public:
void updateSpan(Span *span, int old_height);
Span *spanAt(int x, int y) const;
void clear();
- QList<Span *> spansInRect(int x, int y, int w, int h) const;
+ QSet<Span *> spansInRect(int x, int y, int w, int h) const;
void updateInsertedRows(int start, int end);
void updateInsertedColumns(int start, int end);
@@ -115,7 +116,7 @@ public:
bool checkConsistency() const;
#endif
- typedef QLinkedList<Span *> SpanList;
+ typedef std::list<Span *> SpanList;
SpanList spans; //lists of all spans
private:
//the indexes are negative so the QMap::lowerBound do what i need.
@@ -137,7 +138,7 @@ public:
: showGrid(true), gridStyle(Qt::SolidLine),
rowSectionAnchor(-1), columnSectionAnchor(-1),
columnResizeTimerID(0), rowResizeTimerID(0),
- horizontalHeader(0), verticalHeader(0),
+ horizontalHeader(nullptr), verticalHeader(nullptr),
sortingEnabled(false), geometryRecursionBlock(false),
visualCursor(QPoint())
{
@@ -210,7 +211,7 @@ public:
return span(row, column).width();
}
inline bool hasSpans() const {
- return !spans.spans.isEmpty();
+ return !spans.spans.empty();
}
inline int rowSpanHeight(int row, int span) const {
return sectionSpanSize(verticalHeader, row, span);
diff --git a/src/widgets/itemviews/qtablewidget.cpp b/src/widgets/itemviews/qtablewidget.cpp
index 0fb9e28385..a25a582881 100644
--- a/src/widgets/itemviews/qtablewidget.cpp
+++ b/src/widgets/itemviews/qtablewidget.cpp
@@ -1251,6 +1251,7 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa font(), setText(), setForeground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QTableWidgetItem::backgroundColor() const
\obsolete
@@ -1264,6 +1265,7 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
This function is deprecated. Use setBackground() instead.
*/
+#endif
/*!
\fn QBrush QTableWidgetItem::background() const
@@ -1283,6 +1285,7 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
\sa setForeground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QTableWidgetItem::textColor() const
\obsolete
@@ -1296,6 +1299,7 @@ void QTableWidgetItem::setFlags(Qt::ItemFlags aflags)
This function is deprecated. Use setForeground() instead.
*/
+#endif
/*!
\fn QBrush QTableWidgetItem::foreground() const
diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp
index e9228edcda..413cc2a9cd 100644
--- a/src/widgets/itemviews/qtreeview.cpp
+++ b/src/widgets/itemviews/qtreeview.cpp
@@ -55,6 +55,7 @@
#include <qaccessible.h>
#endif
+#include <private/qapplication_p.h>
#include <private/qtreeview_p.h>
#include <private/qheaderview_p.h>
@@ -1942,6 +1943,7 @@ void QTreeView::mouseDoubleClickEvent(QMouseEvent *event)
if (!style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, this))
emit activated(persistent);
+ d->pressedIndex = QModelIndex();
d->executePostedLayout(); // we need to make sure viewItems is updated
if (d->itemsExpandable
&& d->expandsOnDoubleClick
@@ -2172,35 +2174,6 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
return QModelIndex();
}
int vi = -1;
-#if 0 /* Used to be included in Qt4 for Q_WS_MAC */ && QT_CONFIG(style_mac)
- // Selection behavior is slightly different on the Mac.
- if (d->selectionMode == QAbstractItemView::ExtendedSelection
- && d->selectionModel
- && d->selectionModel->hasSelection()) {
-
- const bool moveUpDown = (cursorAction == MoveUp || cursorAction == MoveDown);
- const bool moveNextPrev = (cursorAction == MoveNext || cursorAction == MovePrevious);
- const bool contiguousSelection = moveUpDown && (modifiers & Qt::ShiftModifier);
-
- // Use the outermost index in the selection as the current index
- if (!contiguousSelection && (moveUpDown || moveNextPrev)) {
-
- // Find outermost index.
- const bool useTopIndex = (cursorAction == MoveUp || cursorAction == MovePrevious);
- int index = useTopIndex ? INT_MAX : INT_MIN;
- const QItemSelection selection = d->selectionModel->selection();
- for (int i = 0; i < selection.count(); ++i) {
- const QItemSelectionRange &range = selection.at(i);
- int candidate = d->viewIndex(useTopIndex ? range.topLeft() : range.bottomRight());
- if (candidate >= 0)
- index = useTopIndex ? qMin(index, candidate) : qMax(index, candidate);
- }
-
- if (index >= 0 && index < INT_MAX)
- vi = index;
- }
- }
-#endif
if (vi < 0)
vi = qMax(0, d->viewIndex(current));
@@ -2214,14 +2187,14 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie
case MoveNext:
case MoveDown:
#ifdef QT_KEYPAD_NAVIGATION
- if (vi == d->viewItems.count()-1 && QApplication::keypadNavigationEnabled())
+ if (vi == d->viewItems.count()-1 && QApplicationPrivate::keypadNavigationEnabled())
return d->model->index(0, current.column(), d->root);
#endif
return d->modelIndex(d->below(vi), current.column());
case MovePrevious:
case MoveUp:
#ifdef QT_KEYPAD_NAVIGATION
- if (vi == 0 && QApplication::keypadNavigationEnabled())
+ if (vi == 0 && QApplicationPrivate::keypadNavigationEnabled())
return d->modelIndex(d->viewItems.count() - 1, current.column());
#endif
return d->modelIndex(d->above(vi), current.column());
diff --git a/src/widgets/itemviews/qtreeview.h b/src/widgets/itemviews/qtreeview.h
index e9cc1beedb..bb00f1df07 100644
--- a/src/widgets/itemviews/qtreeview.h
+++ b/src/widgets/itemviews/qtreeview.h
@@ -158,7 +158,7 @@ public Q_SLOTS:
void collapse(const QModelIndex &index);
void resizeColumnToContents(int column);
#if QT_DEPRECATED_SINCE(5, 13)
- QT_DEPRECATED_X ("Use QTreeeView::sortByColumn(int column, Qt::SortOrder order) instead")
+ QT_DEPRECATED_X ("Use QTreeView::sortByColumn(int column, Qt::SortOrder order) instead")
void sortByColumn(int column);
#endif
void sortByColumn(int column, Qt::SortOrder order);
diff --git a/src/widgets/itemviews/qtreeview_p.h b/src/widgets/itemviews/qtreeview_p.h
index 9666a9f8c2..836d8f0c2d 100644
--- a/src/widgets/itemviews/qtreeview_p.h
+++ b/src/widgets/itemviews/qtreeview_p.h
@@ -87,7 +87,7 @@ public:
QTreeViewPrivate()
: QAbstractItemViewPrivate(),
- header(0), indent(20), lastViewedItem(0), defaultItemHeight(-1),
+ header(nullptr), indent(20), lastViewedItem(0), defaultItemHeight(-1),
uniformRowHeights(false), rootDecoration(true),
itemsExpandable(true), sortingEnabled(false),
expandsOnDoubleClick(true),
@@ -157,7 +157,7 @@ public:
bool checkViewItems() const;
#endif
- int firstVisibleItem(int *offset = 0) const;
+ int firstVisibleItem(int *offset = nullptr) const;
int lastVisibleItem(int firstVisual = -1, int offset = -1) const;
int columnAt(int x) const;
bool hasVisibleChildren( const QModelIndex& parent) const;
diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp
index 6da5ca0f4c..6d0909108b 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -1254,6 +1254,7 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
\sa font(), setText(), setForeground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QTreeWidgetItem::backgroundColor(int column) const
\obsolete
@@ -1267,6 +1268,7 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
This function is deprecated. Use setBackground() instead.
*/
+#endif
/*!
\fn QBrush QTreeWidgetItem::background(int column) const
@@ -1290,6 +1292,7 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
\sa setForeground()
*/
+#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn QColor QTreeWidgetItem::textColor(int column) const
\obsolete
@@ -1303,6 +1306,7 @@ bool QTreeWidgetItem::isFirstColumnSpanned() const
This function is deprecated. Use setForeground() instead.
*/
+#endif
/*!
\fn QBrush QTreeWidgetItem::foreground(int column) const
diff --git a/src/widgets/itemviews/qtreewidget_p.h b/src/widgets/itemviews/qtreewidget_p.h
index ee4a633468..81e7e86203 100644
--- a/src/widgets/itemviews/qtreewidget_p.h
+++ b/src/widgets/itemviews/qtreewidget_p.h
@@ -78,7 +78,7 @@ class QTreeModel : public QAbstractItemModel
friend class QTreeWidgetItemIteratorPrivate;
public:
- explicit QTreeModel(int columns = 0, QTreeWidget *parent = 0);
+ explicit QTreeModel(int columns = 0, QTreeWidget *parent = nullptr);
~QTreeModel();
inline QTreeWidget *view() const
@@ -140,7 +140,7 @@ public:
{ return createIndex(row, col, item); }
protected:
- QTreeModel(QTreeModelPrivate &, QTreeWidget *parent = 0);
+ QTreeModel(QTreeModelPrivate &, QTreeWidget *parent = nullptr);
void emitDataChanged(QTreeWidgetItem *item, int column, const QVector<int> &roles);
void beginInsertItems(QTreeWidgetItem *parent, int row, int count);
void endInsertItems();
diff --git a/src/widgets/kernel/kernel.pri b/src/widgets/kernel/kernel.pri
index c2f6e4ce75..693af7eb80 100644
--- a/src/widgets/kernel/kernel.pri
+++ b/src/widgets/kernel/kernel.pri
@@ -12,7 +12,7 @@ HEADERS += \
kernel/qactiongroup.h \
kernel/qapplication.h \
kernel/qapplication_p.h \
- kernel/qwidgetbackingstore_p.h \
+ kernel/qwidgetrepaintmanager_p.h \
kernel/qboxlayout.h \
kernel/qdesktopwidget.h \
kernel/qgridlayout.h \
@@ -23,7 +23,6 @@ HEADERS += \
kernel/qshortcut.h \
kernel/qsizepolicy.h \
kernel/qstackedlayout.h \
- kernel/qtooltip.h \
kernel/qwidget.h \
kernel/qwidget_p.h \
kernel/qwidgetaction.h \
@@ -42,7 +41,7 @@ SOURCES += \
kernel/qaction.cpp \
kernel/qactiongroup.cpp \
kernel/qapplication.cpp \
- kernel/qwidgetbackingstore.cpp \
+ kernel/qwidgetrepaintmanager.cpp \
kernel/qboxlayout.cpp \
kernel/qgridlayout.cpp \
kernel/qlayout.cpp \
@@ -51,7 +50,6 @@ SOURCES += \
kernel/qshortcut.cpp \
kernel/qsizepolicy.cpp \
kernel/qstackedlayout.cpp \
- kernel/qtooltip.cpp \
kernel/qwidget.cpp \
kernel/qwidgetaction.cpp \
kernel/qgesture.cpp \
@@ -79,6 +77,11 @@ qtConfig(formlayout) {
SOURCES += kernel/qformlayout.cpp
}
+qtConfig(tooltip) {
+ HEADERS += kernel/qtooltip.h
+ SOURCES += kernel/qtooltip.cpp
+}
+
qtConfig(whatsthis) {
HEADERS += kernel/qwhatsthis.h
SOURCES += kernel/qwhatsthis.cpp
diff --git a/src/widgets/kernel/mac.pri b/src/widgets/kernel/mac.pri
index f7e7aa869a..d21e5d4a74 100644
--- a/src/widgets/kernel/mac.pri
+++ b/src/widgets/kernel/mac.pri
@@ -1,4 +1 @@
-macos {
- LIBS_PRIVATE += -framework AppKit -lz
- *-mwerks:INCLUDEPATH += compat
-}
+macos: LIBS_PRIVATE += -framework AppKit -lz
diff --git a/src/widgets/kernel/qaction.cpp b/src/widgets/kernel/qaction.cpp
index 1ca5514655..19ad65692b 100644
--- a/src/widgets/kernel/qaction.cpp
+++ b/src/widgets/kernel/qaction.cpp
@@ -47,15 +47,15 @@
#include "qlist.h"
#include "qstylehints.h"
#include <private/qshortcutmap_p.h>
-#include <private/qapplication_p.h>
+#include <private/qguiapplication_p.h>
#if QT_CONFIG(menu)
#include <private/qmenu_p.h>
#endif
#include <private/qdebug_p.h>
#define QAPP_CHECK(functionName) \
- if (Q_UNLIKELY(!qApp)) { \
- qWarning("QAction: Initialize QApplication before calling '" functionName "'."); \
+ if (Q_UNLIKELY(!QCoreApplication::instance())) { \
+ qWarning("QAction: Initialize Q(Gui)Application before calling '" functionName "'."); \
return; \
}
@@ -75,24 +75,18 @@ static QString qt_strippedText(QString s)
}
-QActionPrivate::QActionPrivate() : group(0), enabled(1), forceDisabled(0),
- visible(1), forceInvisible(0), checkable(0), checked(0), separator(0), fontSet(false),
- iconVisibleInMenu(-1),
- shortcutVisibleInContextMenu(-1),
- menuRole(QAction::TextHeuristicRole),
- priority(QAction::NormalPriority)
-{
-#ifndef QT_NO_SHORTCUT
- shortcutId = 0;
- shortcutContext = Qt::WindowShortcut;
- autorepeat = true;
+QActionPrivate::QActionPrivate() :
+#if QT_CONFIG(shortcut)
+ autorepeat(1),
#endif
-}
-
-QActionPrivate::~QActionPrivate()
+ enabled(1), forceDisabled(0), visible(1), forceInvisible(0), checkable(0),
+ checked(0), separator(0), fontSet(false),
+ iconVisibleInMenu(-1), shortcutVisibleInContextMenu(-1)
{
}
+QActionPrivate::~QActionPrivate() = default;
+
bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
{
#if !QT_CONFIG(statustip)
@@ -101,7 +95,7 @@ bool QActionPrivate::showStatusText(QWidget *widget, const QString &str)
#else
if(QObject *object = widget ? widget : parent) {
QStatusTipEvent tip(str);
- QApplication::sendEvent(object, &tip);
+ QCoreApplication::sendEvent(object, &tip);
return true;
}
#endif
@@ -114,20 +108,20 @@ void QActionPrivate::sendDataChanged()
QActionEvent e(QEvent::ActionChanged, q);
for (int i = 0; i < widgets.size(); ++i) {
QWidget *w = widgets.at(i);
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
#if QT_CONFIG(graphicsview)
for (int i = 0; i < graphicsWidgets.size(); ++i) {
QGraphicsWidget *w = graphicsWidgets.at(i);
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
#endif
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
emit q->changed();
}
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
void QActionPrivate::redoGrab(QShortcutMap &map)
{
Q_Q(QAction);
@@ -345,7 +339,7 @@ QWidget *QAction::parentWidget() const
QObject *ret = parent();
while (ret && !ret->isWidgetType())
ret = ret->parent();
- return (QWidget*)ret;
+ return static_cast<QWidget*>(ret);
}
/*!
@@ -374,7 +368,7 @@ QList<QGraphicsWidget *> QAction::associatedGraphicsWidgets() const
}
#endif
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
/*!
\property QAction::shortcut
\brief the action's primary shortcut key
@@ -391,7 +385,7 @@ void QAction::setShortcut(const QKeySequence &shortcut)
return;
d->shortcut = shortcut;
- d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
d->sendDataChanged();
}
@@ -420,8 +414,8 @@ void QAction::setShortcuts(const QList<QKeySequence> &shortcuts)
d->shortcut = primary;
d->alternateShortcuts = listCopy;
- d->redoGrab(qApp->d_func()->shortcutMap);
- d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
d->sendDataChanged();
}
@@ -485,8 +479,8 @@ void QAction::setShortcutContext(Qt::ShortcutContext context)
return;
QAPP_CHECK("setShortcutContext");
d->shortcutContext = context;
- d->redoGrab(qApp->d_func()->shortcutMap);
- d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
d->sendDataChanged();
}
@@ -513,8 +507,8 @@ void QAction::setAutoRepeat(bool on)
return;
QAPP_CHECK("setAutoRepeat");
d->autorepeat = on;
- d->redoGrab(qApp->d_func()->shortcutMap);
- d->redoGrabAlternate(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
+ d->redoGrabAlternate(QGuiApplicationPrivate::instance()->shortcutMap);
d->sendDataChanged();
}
@@ -573,12 +567,12 @@ QAction::~QAction()
#endif
if (d->group)
d->group->removeAction(this);
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
if (d->shortcutId && qApp) {
- qApp->d_func()->shortcutMap.removeShortcut(d->shortcutId, this);
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->shortcutId, this);
for(int i = 0; i < d->alternateShortcutIds.count(); ++i) {
const int id = d->alternateShortcutIds.at(i);
- qApp->d_func()->shortcutMap.removeShortcut(id, this);
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(id, this);
}
}
#endif
@@ -1027,8 +1021,8 @@ void QAction::setEnabled(bool b)
return;
QAPP_CHECK("setEnabled");
d->enabled = b;
-#ifndef QT_NO_SHORTCUT
- d->setShortcutEnabled(b, qApp->d_func()->shortcutMap);
+#if QT_CONFIG(shortcut)
+ d->setShortcutEnabled(b, QGuiApplicationPrivate::instance()->shortcutMap);
#endif
d->sendDataChanged();
}
@@ -1061,8 +1055,8 @@ void QAction::setVisible(bool b)
d->forceInvisible = !b;
d->visible = b;
d->enabled = b && !d->forceDisabled && (!d->group || d->group->isEnabled()) ;
-#ifndef QT_NO_SHORTCUT
- d->setShortcutEnabled(d->enabled, qApp->d_func()->shortcutMap);
+#if QT_CONFIG(shortcut)
+ d->setShortcutEnabled(d->enabled, QGuiApplicationPrivate::instance()->shortcutMap);
#endif
d->sendDataChanged();
}
@@ -1080,7 +1074,7 @@ bool QAction::isVisible() const
bool
QAction::event(QEvent *e)
{
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
if (e->type() == QEvent::Shortcut) {
QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
Q_ASSERT_X(se->key() == d_func()->shortcut || d_func()->alternateShortcuts.contains(se->key()),
@@ -1153,8 +1147,9 @@ void QAction::activate(ActionEvent event)
if(event == Trigger) {
QPointer<QObject> guard = this;
if(d->checkable) {
- // the checked action of an exclusive group cannot be unchecked
- if (d->checked && (d->group && d->group->isExclusive()
+ // the checked action of an exclusive group may not be unchecked
+ if (d->checked && (d->group
+ && d->group->exclusionPolicy() == QActionGroup::ExclusionPolicy::Exclusive
&& d->group->checkedAction() == this)) {
if (!guard.isNull())
emit triggered(true);
@@ -1284,7 +1279,7 @@ void QAction::setIconVisibleInMenu(bool visible)
d->iconVisibleInMenu = visible;
// Only send data changed if we really need to.
if (oldValue != -1
- || visible == !QApplication::instance()->testAttribute(Qt::AA_DontShowIconsInMenus)) {
+ || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus)) {
d->sendDataChanged();
}
}
@@ -1294,7 +1289,7 @@ bool QAction::isIconVisibleInMenu() const
{
Q_D(const QAction);
if (d->iconVisibleInMenu == -1) {
- return !QApplication::instance()->testAttribute(Qt::AA_DontShowIconsInMenus);
+ return !QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus);
}
return d->iconVisibleInMenu;
}
@@ -1322,7 +1317,7 @@ void QAction::setShortcutVisibleInContextMenu(bool visible)
d->shortcutVisibleInContextMenu = visible;
// Only send data changed if we really need to.
if (oldValue != -1
- || visible == !QApplication::instance()->testAttribute(Qt::AA_DontShowShortcutsInContextMenus)) {
+ || visible == !QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)) {
d->sendDataChanged();
}
}
@@ -1350,7 +1345,7 @@ Q_WIDGETS_EXPORT QDebug operator<<(QDebug d, const QAction *action)
d << " toolTip=" << action->toolTip();
if (action->isCheckable())
d << " checked=" << action->isChecked();
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
if (!action->shortcut().isEmpty())
d << " shortcut=" << action->shortcut();
#endif
diff --git a/src/widgets/kernel/qaction.h b/src/widgets/kernel/qaction.h
index 84bf92d2ac..f7693f4dde 100644
--- a/src/widgets/kernel/qaction.h
+++ b/src/widgets/kernel/qaction.h
@@ -72,7 +72,7 @@ class Q_WIDGETS_EXPORT QAction : public QObject
Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip NOTIFY changed)
Q_PROPERTY(QString whatsThis READ whatsThis WRITE setWhatsThis NOTIFY changed)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY changed)
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut NOTIFY changed)
Q_PROPERTY(Qt::ShortcutContext shortcutContext READ shortcutContext WRITE setShortcutContext NOTIFY changed)
Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat NOTIFY changed)
@@ -129,7 +129,7 @@ public:
void setSeparator(bool b);
bool isSeparator() const;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
void setShortcut(const QKeySequence &shortcut);
QKeySequence shortcut() const;
diff --git a/src/widgets/kernel/qaction_p.h b/src/widgets/kernel/qaction_p.h
index 19ae47c7b9..6b6ca8076f 100644
--- a/src/widgets/kernel/qaction_p.h
+++ b/src/widgets/kernel/qaction_p.h
@@ -89,15 +89,15 @@ public:
QString tooltip;
QString statustip;
QString whatsthis;
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
QKeySequence shortcut;
QList<QKeySequence> alternateShortcuts;
#endif
QVariant userData;
-#ifndef QT_NO_SHORTCUT
- int shortcutId;
+#if QT_CONFIG(shortcut)
+ int shortcutId = 0;
QVector<int> alternateShortcutIds;
- Qt::ShortcutContext shortcutContext;
+ Qt::ShortcutContext shortcutContext = Qt::WindowShortcut;
uint autorepeat : 1;
#endif
QFont font;
@@ -112,19 +112,17 @@ public:
int iconVisibleInMenu : 2; // Only has values -1, 0, and 1
int shortcutVisibleInContextMenu : 2; // Only has values -1, 0, and 1
- QAction::MenuRole menuRole;
- QAction::Priority priority;
+ QAction::MenuRole menuRole = QAction::TextHeuristicRole;
+ QAction::Priority priority = QAction::NormalPriority;
- QList<QWidget *> widgets;
+ QWidgetList widgets;
#if QT_CONFIG(graphicsview)
QList<QGraphicsWidget *> graphicsWidgets;
#endif
-#ifndef QT_NO_SHORTCUT
+#if QT_CONFIG(shortcut)
void redoGrab(QShortcutMap &map);
void redoGrabAlternate(QShortcutMap &map);
void setShortcutEnabled(bool enable, QShortcutMap &map);
-
- static QShortcutMap *globalMap;
#endif // QT_NO_SHORTCUT
void sendDataChanged();
diff --git a/src/widgets/kernel/qactiongroup.cpp b/src/widgets/kernel/qactiongroup.cpp
index 4786437d7e..1d9213de0c 100644
--- a/src/widgets/kernel/qactiongroup.cpp
+++ b/src/widgets/kernel/qactiongroup.cpp
@@ -42,7 +42,6 @@
#ifndef QT_NO_ACTION
#include "qaction_p.h"
-#include "qapplication.h"
#include "qevent.h"
#include "qlist.h"
@@ -52,12 +51,16 @@ class QActionGroupPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QActionGroup)
public:
- QActionGroupPrivate() : exclusive(1), enabled(1), visible(1) { }
+ QActionGroupPrivate() : enabled(1),
+ visible(1),
+ exclusionPolicy(QActionGroup::ExclusionPolicy::Exclusive)
+ {
+ }
QList<QAction *> actions;
QPointer<QAction> current;
- uint exclusive : 1;
uint enabled : 1;
uint visible : 1;
+ QActionGroup::ExclusionPolicy exclusionPolicy;
private:
void _q_actionTriggered(); //private slot
@@ -69,8 +72,8 @@ void QActionGroupPrivate::_q_actionChanged()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionChanged", "internal error");
- if(exclusive) {
+ Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionChanged", "internal error");
+ if (exclusionPolicy != QActionGroup::ExclusionPolicy::None) {
if (action->isChecked()) {
if (action != current) {
if(current)
@@ -87,7 +90,7 @@ void QActionGroupPrivate::_q_actionTriggered()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionTriggered", "internal error");
+ Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionTriggered", "internal error");
emit q->triggered(action);
}
@@ -95,7 +98,7 @@ void QActionGroupPrivate::_q_actionHovered()
{
Q_Q(QActionGroup);
QAction *action = qobject_cast<QAction*>(q->sender());
- Q_ASSERT_X(action != 0, "QWidgetGroup::_q_actionHovered", "internal error");
+ Q_ASSERT_X(action != nullptr, "QActionGroup::_q_actionHovered", "internal error");
emit q->hovered(action);
}
@@ -127,12 +130,17 @@ void QActionGroupPrivate::_q_actionHovered()
actions is chosen. Each action in an action group emits its
triggered() signal as usual.
- As stated above, an action group is \l exclusive by default; it
- ensures that only one checkable action is active at any one time.
+ As stated above, an action group is exclusive by default; it
+ ensures that at most only one checkable action is active at any one time.
If you want to group checkable actions without making them
- exclusive, you can turn of exclusiveness by calling
+ exclusive, you can turn off exclusiveness by calling
setExclusive(false).
+ By default the active action of an exclusive group cannot be unchecked.
+ In some cases it may be useful to allow unchecking all the actions,
+ you can allow this by calling
+ setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional).
+
Actions can be added to an action group using addAction(), but it
is usually more convenient to specify a group when creating
actions; this ensures that actions are automatically created with
@@ -146,10 +154,33 @@ void QActionGroupPrivate::_q_actionHovered()
*/
/*!
+ \enum QActionGroup::ExclusionPolicy
+
+ This enum specifies the different policies that can be used to
+ control how the group performs exclusive checking on checkable actions.
+
+ \value None
+ The actions in the group can be checked independently of each other.
+
+ \value Exclusive
+ Exactly one action can be checked at any one time.
+ This is the default policy.
+
+ \value ExclusiveOptional
+ At most one action can be checked at any one time. The actions
+ can also be all unchecked.
+
+ \sa exclusionPolicy
+ \since 5.14
+*/
+
+/*!
Constructs an action group for the \a parent object.
The action group is exclusive by default. Call setExclusive(false)
- to make the action group non-exclusive.
+ to make the action group non-exclusive. To make the group exclusive
+ but allow unchecking the active action call instead
+ setExclusionPolicy(QActionGroup::ExclusionPolicy::ExclusiveOptional)
*/
QActionGroup::QActionGroup(QObject* parent) : QObject(*new QActionGroupPrivate, parent)
{
@@ -258,26 +289,56 @@ QList<QAction*> QActionGroup::actions() const
}
/*!
- \property QActionGroup::exclusive
- \brief whether the action group does exclusive checking
+ \brief Enable or disable the group exclusion checking
- If exclusive is true, only one checkable action in the action group
- can ever be active at any time. If the user chooses another
- checkable action in the group, the one they chose becomes active and
- the one that was active becomes inactive.
+ This is a convenience method that calls
+ setExclusionPolicy(ExclusionPolicy::Exclusive).
- \sa QAction::checkable
+ \sa QActionGroup::exclusionPolicy
*/
void QActionGroup::setExclusive(bool b)
{
- Q_D(QActionGroup);
- d->exclusive = b;
+ setExclusionPolicy(b ? QActionGroup::ExclusionPolicy::Exclusive
+ : QActionGroup::ExclusionPolicy::None);
}
+/*!
+ \brief Returs true if the group is exclusive
+
+ The group is exclusive if the ExclusionPolicy is either Exclusive
+ or ExclusionOptional.
+
+*/
bool QActionGroup::isExclusive() const
{
+ return exclusionPolicy() != QActionGroup::ExclusionPolicy::None;
+}
+
+/*!
+ \property QActionGroup::exclusionPolicy
+ \brief This property holds the group exclusive checking policy
+
+ If exclusionPolicy is set to Exclusive, only one checkable
+ action in the action group can ever be active at any time. If the user
+ chooses another checkable action in the group, the one they chose becomes
+ active and the one that was active becomes inactive. If exclusionPolicy is
+ set to ExclusionOptional the group is exclusive but the active checkable
+ action in the group can be unchecked leaving the group with no actions
+ checked.
+
+ \sa QAction::checkable
+ \since 5.14
+*/
+void QActionGroup::setExclusionPolicy(QActionGroup::ExclusionPolicy policy)
+{
+ Q_D(QActionGroup);
+ d->exclusionPolicy = policy;
+}
+
+QActionGroup::ExclusionPolicy QActionGroup::exclusionPolicy() const
+{
Q_D(const QActionGroup);
- return d->exclusive;
+ return d->exclusionPolicy;
}
/*!
@@ -301,10 +362,10 @@ void QActionGroup::setEnabled(bool b)
{
Q_D(QActionGroup);
d->enabled = b;
- for(QList<QAction*>::const_iterator it = d->actions.constBegin(); it != d->actions.constEnd(); ++it) {
- if(!(*it)->d_func()->forceDisabled) {
- (*it)->setEnabled(b);
- (*it)->d_func()->forceDisabled = false;
+ for (auto action : qAsConst(d->actions)) {
+ if (!action->d_func()->forceDisabled) {
+ action->setEnabled(b);
+ action->d_func()->forceDisabled = false;
}
}
}
@@ -338,10 +399,10 @@ void QActionGroup::setVisible(bool b)
{
Q_D(QActionGroup);
d->visible = b;
- for(QList<QAction*>::Iterator it = d->actions.begin(); it != d->actions.end(); ++it) {
- if(!(*it)->d_func()->forceInvisible) {
- (*it)->setVisible(b);
- (*it)->d_func()->forceInvisible = false;
+ for (auto action : qAsConst(d->actions)) {
+ if (!action->d_func()->forceInvisible) {
+ action->setVisible(b);
+ action->d_func()->forceInvisible = false;
}
}
}
diff --git a/src/widgets/kernel/qactiongroup.h b/src/widgets/kernel/qactiongroup.h
index 61c90b911d..90f488bedb 100644
--- a/src/widgets/kernel/qactiongroup.h
+++ b/src/widgets/kernel/qactiongroup.h
@@ -55,11 +55,18 @@ class Q_WIDGETS_EXPORT QActionGroup : public QObject
Q_OBJECT
Q_DECLARE_PRIVATE(QActionGroup)
- Q_PROPERTY(bool exclusive READ isExclusive WRITE setExclusive)
+ Q_PROPERTY(QActionGroup::ExclusionPolicy exclusionPolicy READ exclusionPolicy WRITE setExclusionPolicy)
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
Q_PROPERTY(bool visible READ isVisible WRITE setVisible)
public:
+ enum class ExclusionPolicy {
+ None,
+ Exclusive,
+ ExclusiveOptional
+ };
+ Q_ENUM(ExclusionPolicy)
+
explicit QActionGroup(QObject* parent);
~QActionGroup();
@@ -73,6 +80,7 @@ public:
bool isExclusive() const;
bool isEnabled() const;
bool isVisible() const;
+ ExclusionPolicy exclusionPolicy() const;
public Q_SLOTS:
@@ -80,6 +88,7 @@ public Q_SLOTS:
inline void setDisabled(bool b) { setEnabled(!b); }
void setVisible(bool);
void setExclusive(bool);
+ void setExclusionPolicy(ExclusionPolicy policy);
Q_SIGNALS:
void triggered(QAction *);
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index 486c424391..dfa1bc23b1 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -111,6 +111,9 @@
#include <qtwidgets_tracepoints_p.h>
+#include <algorithm>
+#include <iterator>
+
//#define ALIEN_DEBUG
static void initResources()
@@ -233,9 +236,6 @@ void QApplicationPrivate::createEventDispatcher()
encapsulated in a QStyle object. This can be changed at runtime
with setStyle().
- \li It specifies how the application is to allocate colors. See
- setColorSpec() for details.
-
\li It provides localization of strings that are visible to the
user via translate().
@@ -296,11 +296,6 @@ void QApplicationPrivate::createEventDispatcher()
setStyle().
\row
- \li Color usage
- \li colorSpec(),
- setColorSpec().
-
- \row
\li Text handling
\li installTranslator(),
removeTranslator()
@@ -334,6 +329,7 @@ void QApplicationPrivate::createEventDispatcher()
\sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
*/
+#if QT_DEPRECATED_SINCE(5, 8)
// ### fixme: Qt 6: Remove ColorSpec and accessors.
/*!
\enum QApplication::ColorSpec
@@ -347,15 +343,7 @@ void QApplicationPrivate::createEventDispatcher()
See setColorSpec() for full details.
*/
-
-/*!
- \fn QApplication::setGraphicsSystem(const QString &)
- \obsolete
-
- This call has no effect.
-
- Use the QPA framework instead.
-*/
+#endif
/*!
\fn QWidget *QApplication::topLevelAt(const QPoint &point)
@@ -570,10 +558,6 @@ void QApplicationPrivate::init()
initialize();
eventDispatcher->startingUp();
-#ifdef QT_EVAL
- extern void qt_gui_eval_init(QCoreApplicationPrivate::Type);
- qt_gui_eval_init(application_type);
-#endif
#ifndef QT_NO_ACCESSIBILITY
// factory for accessible interfaces for widgets shipped with Qt
QAccessible::installFactory(&qAccessibleFactory);
@@ -626,7 +610,7 @@ void QApplicationPrivate::initialize()
if (qt_is_gui_used)
initializeMultitouch();
- if (QApplication::desktopSettingsAware())
+ if (QGuiApplication::desktopSettingsAware())
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
QApplicationPrivate::enabledAnimations = theme->themeHint(QPlatformTheme::UiEffects).toInt();
}
@@ -1176,7 +1160,7 @@ void QApplication::setStyle(QStyle *style)
QWidget *w = *it;
if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
w->update();
}
}
@@ -1193,7 +1177,7 @@ void QApplication::setStyle(QStyle *style)
if (QApplicationPrivate::focus_widget) {
QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
- QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
+ QCoreApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
QApplicationPrivate::focus_widget->update();
}
}
@@ -1555,7 +1539,7 @@ void QApplication::setFont(const QFont &font, const char *className)
if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
// Send ApplicationFontChange to qApp itself, and to the widgets.
QEvent e(QEvent::ApplicationFontChange);
- QApplication::sendEvent(QApplication::instance(), &e);
+ QCoreApplication::sendEvent(QApplication::instance(), &e);
QWidgetList wids = QApplication::allWidgets();
for (QWidgetList::ConstIterator it = wids.constBegin(), cend = wids.constEnd(); it != cend; ++it) {
@@ -1569,7 +1553,7 @@ void QApplication::setFont(const QFont &font, const char *className)
QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
it != scenes.constEnd(); ++it) {
- QApplication::sendEvent(*it, &e);
+ QCoreApplication::sendEvent(*it, &e);
}
#endif // QT_CONFIG(graphicsview)
}
@@ -1662,12 +1646,12 @@ void QApplicationPrivate::notifyWindowIconChanged()
QWidgetList QApplication::topLevelWidgets()
{
QWidgetList list;
- QWidgetList all = allWidgets();
-
- for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
- QWidget *w = *it;
- if (w->isWindow() && w->windowType() != Qt::Desktop)
- list.append(w);
+ if (QWidgetPrivate::allWidgets != nullptr) {
+ const auto isTopLevelWidget = [] (const QWidget *w) {
+ return w->isWindow() && w->windowType() != Qt::Desktop;
+ };
+ std::copy_if(QWidgetPrivate::allWidgets->cbegin(), QWidgetPrivate::allWidgets->cend(),
+ std::back_inserter(list), isTopLevelWidget);
}
return list;
}
@@ -1688,7 +1672,7 @@ QWidgetList QApplication::topLevelWidgets()
QWidgetList QApplication::allWidgets()
{
if (QWidgetPrivate::allWidgets)
- return QWidgetPrivate::allWidgets->toList();
+ return QWidgetPrivate::allWidgets->values();
return QWidgetList();
}
@@ -1743,16 +1727,16 @@ void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
#endif
QFocusEvent out(QEvent::FocusOut, reason);
QPointer<QWidget> that = prev;
- QApplication::sendEvent(prev, &out);
+ QCoreApplication::sendEvent(prev, &out);
if (that)
- QApplication::sendEvent(that->style(), &out);
+ QCoreApplication::sendEvent(that->style(), &out);
}
if(focus && QApplicationPrivate::focus_widget == focus) {
QFocusEvent in(QEvent::FocusIn, reason);
QPointer<QWidget> that = focus;
- QApplication::sendEvent(focus, &in);
+ QCoreApplication::sendEvent(focus, &in);
if (that)
- QApplication::sendEvent(that->style(), &in);
+ QCoreApplication::sendEvent(that->style(), &in);
}
emit qApp->focusChanged(prev, focus_widget);
}
@@ -1882,22 +1866,19 @@ void QApplication::aboutQt()
bool QApplication::event(QEvent *e)
{
Q_D(QApplication);
- if(e->type() == QEvent::Close) {
- QCloseEvent *ce = static_cast<QCloseEvent*>(e);
- ce->accept();
+ if (e->type() == QEvent::Quit) {
closeAllWindows();
-
- const QWidgetList list = topLevelWidgets();
- for (auto *w : list) {
+ for (auto *w : topLevelWidgets()) {
if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
(!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
- ce->ignore();
- break;
+ e->ignore();
+ return true;
}
}
- if (ce->isAccepted()) {
- return true;
- }
+ // Explicitly call QCoreApplication instead of QGuiApplication so that
+ // we don't let QGuiApplication close any windows we skipped earlier in
+ // closeAllWindows(). FIXME: Unify all this close magic through closeAllWindows.
+ return QCoreApplication::event(e);
#ifndef Q_OS_WIN
} else if (e->type() == QEvent::LocaleChange) {
// on Windows the event propagation is taken care by the
@@ -1928,7 +1909,7 @@ bool QApplication::event(QEvent *e)
}
if (showToolTip) {
QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
- QApplication::sendEvent(d->toolTipWidget, &e);
+ QCoreApplication::sendEvent(d->toolTipWidget, &e);
if (e.isAccepted()) {
QStyle *s = d->toolTipWidget->style();
int sleepDelay = s->styleHint(QStyle::SH_ToolTip_FallAsleepDelay, 0, d->toolTipWidget, 0);
@@ -1957,13 +1938,6 @@ bool QApplication::event(QEvent *e)
return QGuiApplication::event(e);
}
-/*!
- \fn void QApplication::syncX()
- Was used to synchronize with the X server in 4.x, here for source compatibility.
- \internal
- \obsolete
-*/
-
// ### FIXME: topLevelWindows does not contain QWidgets without a parent
// until QWidgetPrivate::create is called. So we have to override the
// QGuiApplication::notifyLayoutDirectionChange
@@ -2040,7 +2014,7 @@ void QApplication::setActiveWindow(QWidget* act)
QGuiApplication::inputMethod()->commit();
QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, Qt::ActiveWindowFocusReason);
- QApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
+ QCoreApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
}
QApplicationPrivate::active_window = window;
@@ -2115,7 +2089,7 @@ QWidget *qt_tlw_for_window(QWindow *wnd)
wnd = wnd->parent();
}
if (wnd) {
- const auto tlws = qApp->topLevelWidgets();
+ const auto tlws = QApplication::topLevelWidgets();
for (QWidget *tlw : tlws) {
if (tlw->windowHandle() == wnd)
return tlw;
@@ -2209,12 +2183,12 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
#if 0
if (leave) {
QEvent e(QEvent::Leave);
- QApplication::sendEvent(leave, & e);
+ QCoreApplication::sendEvent(leave, & e);
}
if (enter) {
const QPoint windowPos = enter->window()->mapFromGlobal(globalPos);
QEnterEvent e(enter->mapFromGlobal(globalPos), windowPos, globalPos);
- QApplication::sendEvent(enter, & e);
+ QCoreApplication::sendEvent(enter, & e);
}
return;
#endif
@@ -2275,12 +2249,12 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
for (int i = 0; i < leaveList.size(); ++i) {
auto *w = leaveList.at(i);
if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
- QApplication::sendEvent(w, &leaveEvent);
+ QCoreApplication::sendEvent(w, &leaveEvent);
if (w->testAttribute(Qt::WA_Hover) &&
(!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
Q_ASSERT(instance());
QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
- QApplication::keyboardModifiers());
+ QGuiApplication::keyboardModifiers());
qApp->d_func()->notify_helper(w, &he);
}
}
@@ -2296,11 +2270,11 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con
if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
const QPointF localPos = w->mapFromGlobal(globalPos);
QEnterEvent enterEvent(localPos, windowPos, globalPosF);
- QApplication::sendEvent(w, &enterEvent);
+ QCoreApplication::sendEvent(w, &enterEvent);
if (w->testAttribute(Qt::WA_Hover) &&
(!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
QHoverEvent he(QEvent::HoverEnter, localPos, QPoint(-1, -1),
- QApplication::keyboardModifiers());
+ QGuiApplication::keyboardModifiers());
qApp->d_func()->notify_helper(w, &he);
}
}
@@ -2648,7 +2622,7 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
if (spontaneous)
result = QApplication::sendSpontaneousEvent(receiver, event);
else
- result = QApplication::sendEvent(receiver, event);
+ result = QCoreApplication::sendEvent(receiver, event);
}
if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
@@ -2902,7 +2876,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
}
#ifndef QT_NO_DEBUG
- d->checkReceiverThread(receiver);
+ QCoreApplicationPrivate::checkReceiverThread(receiver);
#endif
if (receiver->isWindowType()) {
@@ -3241,13 +3215,21 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
if (spontaneous && phase == Qt::ScrollBegin)
QApplicationPrivate::wheel_widget = nullptr;
- const QPoint &relpos = wheel->pos();
+ QPoint relpos = wheel->position().toPoint();
if (spontaneous && (phase == Qt::NoScrollPhase || phase == Qt::ScrollUpdate))
QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
wheel->modifiers(), phase, wheel->source(), wheel->inverted());
+QT_WARNING_POP
+#else
+ QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
+ wheel->modifiers(), phase, wheel->inverted(), wheel->source());
+#endif
we.setTimestamp(wheel->timestamp());
bool eventAccepted;
do {
@@ -3282,9 +3264,17 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
// is set. Since it accepted the wheel event previously, we continue
// sending those events until we get a ScrollEnd, which signifies
// the end of the natural scrolling sequence.
- const QPoint &relpos = QApplicationPrivate::wheel_widget->mapFromGlobal(wheel->globalPos());
+ const QPoint &relpos = QApplicationPrivate::wheel_widget->mapFromGlobal(wheel->globalPosition().toPoint());
+#if QT_DEPRECATED_SINCE(5, 0)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
wheel->modifiers(), wheel->phase(), wheel->source());
+QT_WARNING_POP
+#else
+ QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
+ wheel->modifiers(), wheel->phase(), wheel->inverted(), wheel->source());
+#endif
we.setTimestamp(wheel->timestamp());
we.spont = true;
we.ignore();
@@ -3401,7 +3391,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
#if QT_CONFIG(graphicsview)
// QGraphicsProxyWidget handles its own propagation,
// and we must not change QDragManagers currentTarget.
- QWExtra *extra = w->window()->d_func()->extra;
+ const auto &extra = w->window()->d_func()->extra;
if (extra && extra->proxyWidget) {
res = d->notify_helper(w, dragEvent);
break;
@@ -3429,7 +3419,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
#if QT_CONFIG(graphicsview)
// QGraphicsProxyWidget handles its own propagation,
// and we must not change QDragManagers currentTarget.
- QWExtra *extra = w->window()->d_func()->extra;
+ const auto &extra = w->window()->d_func()->extra;
bool isProxyWidget = extra && extra->proxyWidget;
if (!isProxyWidget)
#endif
@@ -3670,7 +3660,7 @@ bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
// send to all application event filters
if (threadRequiresCoreApplication()
- && receiver->d_func()->threadData->thread == mainThread()
+ && receiver->d_func()->threadData->thread.loadAcquire() == mainThread()
&& sendThroughApplicationEventFilters(receiver, e)) {
filtered = true;
return filtered;
@@ -3822,7 +3812,7 @@ void QApplicationPrivate::openPopup(QWidget *popup)
} else if (popupWidgets->count() == 1) { // this was the first popup
if (QWidget *fw = QApplication::focusWidget()) {
QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
- QApplication::sendEvent(fw, &e);
+ QCoreApplication::sendEvent(fw, &e);
}
}
}
@@ -3834,8 +3824,6 @@ void QApplicationPrivate::openPopup(QWidget *popup)
This feature is available in Qt for Embedded Linux only.
\since 4.6
-
- \sa keypadNavigationEnabled()
*/
void QApplication::setNavigationMode(Qt::NavigationMode mode)
{
@@ -3848,8 +3836,6 @@ void QApplication::setNavigationMode(Qt::NavigationMode mode)
This feature is available in Qt for Embedded Linux only.
\since 4.6
-
- \sa keypadNavigationEnabled()
*/
Qt::NavigationMode QApplication::navigationMode()
{
@@ -3985,15 +3971,6 @@ int QApplication::doubleClickInterval()
}
/*!
- \fn QApplication::keyboardInputDirection()
- \since 4.2
- \deprecated
-
- Returns the current keyboard input direction. Replaced with QInputMethod::inputDirection()
- \sa QInputMethod::inputDirection()
-*/
-
-/*!
\property QApplication::keyboardInputInterval
\brief the time limit in milliseconds that distinguishes a key press
from two consecutive key presses
@@ -4130,14 +4107,6 @@ void QApplication::beep()
\sa QCoreApplication::instance(), qGuiApp
*/
-/*!
- \fn QLocale QApplication::keyboardInputLocale()
- \since 4.2
- \obsolete
-
- Returns the current keyboard input locale. Replaced with QInputMethod::locale()
-*/
-
bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
{
return QGuiApplication::sendSpontaneousEvent(receiver, event);
@@ -4387,7 +4356,7 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
QTouchEvent touchEvent(eventType,
device,
- QApplication::keyboardModifiers(),
+ QGuiApplication::keyboardModifiers(),
it.value().first,
it.value().second);
bool containsPress = updateTouchPointsForWidget(widget, &touchEvent);
@@ -4430,7 +4399,7 @@ bool QApplicationPrivate::translateRawTouchEvent(QWidget *window,
void QApplicationPrivate::translateTouchCancel(QTouchDevice *device, ulong timestamp)
{
- QTouchEvent touchEvent(QEvent::TouchCancel, device, QApplication::keyboardModifiers());
+ QTouchEvent touchEvent(QEvent::TouchCancel, device, QGuiApplication::keyboardModifiers());
touchEvent.setTimestamp(timestamp);
QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it
= self->activeTouchPoints.constBegin(), ite = self->activeTouchPoints.constEnd();
@@ -4466,12 +4435,12 @@ void QApplicationPrivate::sendApplicationPaletteChange(bool toAllWidgets, const
const QWidgetList widgets = QApplication::allWidgets();
for (auto widget : widgets) {
if (toAllWidgets || (!className && widget->isWindow()) || (className && widget->inherits(className)))
- QApplication::sendEvent(widget, &event);
+ QCoreApplication::sendEvent(widget, &event);
}
#if QT_CONFIG(graphicsview)
for (auto scene : qAsConst(scene_list))
- QApplication::sendEvent(scene, &event);
+ QCoreApplication::sendEvent(scene, &event);
#endif // QT_CONFIG(graphicsview)
}
diff --git a/src/widgets/kernel/qapplication_p.h b/src/widgets/kernel/qapplication_p.h
index 133279f977..3167bd423f 100644
--- a/src/widgets/kernel/qapplication_p.h
+++ b/src/widgets/kernel/qapplication_p.h
@@ -112,52 +112,41 @@ public:
virtual bool shouldQuit() override;
bool tryCloseAllWindows() override;
-#if 0 // Used to be included in Qt4 for Q_WS_X11
-#if QT_CONFIG(settings)
- static bool x11_apply_settings();
-#endif
- static void reset_instance_pointer();
-#endif
static bool autoSipEnabled;
static QString desktopStyleKey();
-
void createEventDispatcher() override;
static void dispatchEnterLeave(QWidget *enter, QWidget *leave, const QPointF &globalPosF);
void notifyWindowIconChanged() override;
//modality
- bool isWindowBlocked(QWindow *window, QWindow **blockingWindow = 0) const override;
+ bool isWindowBlocked(QWindow *window, QWindow **blockingWindow = nullptr) const override;
static bool isBlockedByModal(QWidget *widget);
static bool modalState();
- static bool tryModalHelper(QWidget *widget, QWidget **rettop = 0);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- static QWidget *tryModalHelper_sys(QWidget *top);
- bool canQuit();
+ static bool tryModalHelper(QWidget *widget, QWidget **rettop = nullptr);
+
+#ifdef QT_KEYPAD_NAVIGATION
+ static bool keypadNavigationEnabled()
+ {
+ return navigationMode == Qt::NavigationModeKeypadTabOrder ||
+ navigationMode == Qt::NavigationModeKeypadDirectional;
+ }
#endif
bool notify_helper(QObject *receiver, QEvent * e);
- void init(
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- Display *dpy = 0, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0
-#endif
- );
+ void init();
void initialize();
void process_cmdline();
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- static void x11_initialize_style();
-#endif
-
static bool inPopupMode();
bool popupActive() override { return inPopupMode(); }
void closePopup(QWidget *popup);
void openPopup(QWidget *popup);
static void setFocusWidget(QWidget *focus, Qt::FocusReason reason);
static QWidget *focusNextPrevChild_helper(QWidget *toplevel, bool next,
- bool *wrappingOccurred = 0);
+ bool *wrappingOccurred = nullptr);
#if QT_CONFIG(graphicsview)
// Maintain a list of all scenes to ensure font and palette propagation to
@@ -205,10 +194,6 @@ public:
static void initializeWidgetFontHash();
static void setSystemFont(const QFont &font);
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- static void applyX11SpecificCommandLineArguments(QWidget *main_widget);
-#endif
-
static QApplicationPrivate *instance() { return self; }
#ifdef QT_KEYPAD_NAVIGATION
@@ -216,10 +201,6 @@ public:
static Qt::NavigationMode navigationMode;
#endif
-#if 0 /* Used to be included in Qt4 for Q_WS_MAC */ || 0 /* Used to be included in Qt4 for Q_WS_X11 */
- void _q_alertTimeOut();
- QHash<QWidget *, QTimer *> alertTimerHash;
-#endif
#ifndef QT_NO_STYLE_STYLESHEET
static QString styleSheet;
#endif
@@ -238,7 +219,7 @@ public:
return window;
if (const QWidget *nativeParent = widget->nativeParentWidget())
return nativeParent->windowHandle();
- return 0;
+ return nullptr;
}
#ifdef Q_OS_WIN
@@ -256,14 +237,6 @@ public:
QGestureManager *gestureManager;
QWidget *gestureWidget;
#endif
-#if 0 /* Used to be included in Qt4 for Q_WS_X11 */ || 0 /* Used to be included in Qt4 for Q_WS_WIN */
- QPixmap *move_cursor;
- QPixmap *copy_cursor;
- QPixmap *link_cursor;
-#endif
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- QPixmap *ignore_cursor;
-#endif
static bool updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent);
void initializeMultitouch();
@@ -292,14 +265,7 @@ private:
static bool isAlien(QWidget *);
};
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- extern void qt_win_set_cursor(QWidget *, bool);
-#elif 0 // Used to be included in Qt4 for Q_WS_X11
- extern void qt_x11_enforce_cursor(QWidget *, bool);
- extern void qt_x11_enforce_cursor(QWidget *);
-#else
- extern void qt_qpa_set_cursor(QWidget * w, bool force);
-#endif
+extern void qt_qpa_set_cursor(QWidget * w, bool force);
QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qboxlayout.cpp b/src/widgets/kernel/qboxlayout.cpp
index a368f379ad..76d8533271 100644
--- a/src/widgets/kernel/qboxlayout.cpp
+++ b/src/widgets/kernel/qboxlayout.cpp
@@ -172,7 +172,7 @@ void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *b
rightDelta = w->geometry().right() - itm->geometry().right();
}
QWidget *w = q->parentWidget();
- Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection();
+ Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QGuiApplication::layoutDirection();
if (layoutDirection == Qt::RightToLeft)
qSwap(leftDelta, rightDelta);
diff --git a/src/widgets/kernel/qdesktopwidget.cpp b/src/widgets/kernel/qdesktopwidget.cpp
index d17c7eb36c..9e90adec46 100644
--- a/src/widgets/kernel/qdesktopwidget.cpp
+++ b/src/widgets/kernel/qdesktopwidget.cpp
@@ -111,7 +111,7 @@ const QRect QDesktopWidgetPrivate::availableGeometry(const QWidget *widget)
QDesktopScreenWidget *QDesktopWidgetPrivate::widgetForScreen(QScreen *qScreen) const
{
foreach (QDesktopScreenWidget *widget, screens) {
- if (widget->screen() == qScreen)
+ if (widget->assignedScreen() == qScreen)
return widget;
}
return nullptr;
@@ -211,7 +211,9 @@ QDesktopWidget::QDesktopWidget()
setObjectName(QLatin1String("desktop"));
d->_q_updateScreens();
connect(qApp, SIGNAL(screenAdded(QScreen*)), this, SLOT(_q_updateScreens()));
+#if QT_DEPRECATED_SINCE(5, 11)
connect(qApp, SIGNAL(primaryScreenChanged(QScreen*)), this, SIGNAL(primaryScreenChanged()));
+#endif
}
QDesktopWidget::~QDesktopWidget()
@@ -321,20 +323,12 @@ int QDesktopWidgetPrivate::screenNumber(const QWidget *w)
if (screens.isEmpty()) // This should never happen
return primaryScreen();
- const QWindow *winHandle = w->windowHandle();
- if (!winHandle) {
- if (const QWidget *nativeParent = w->nativeParentWidget())
- winHandle = nativeParent->windowHandle();
- }
-
// If there is more than one virtual desktop
if (screens.count() != screens.constFirst()->virtualSiblings().count()) {
// Find the root widget, get a QScreen from it and use the
// virtual siblings for checking the window position.
- if (winHandle) {
- if (const QScreen *winScreen = winHandle->screen())
- screens = winScreen->virtualSiblings();
- }
+ if (const QScreen *winScreen = qt_widget_private(const_cast<QWidget *>(w))->associatedScreen())
+ screens = winScreen->virtualSiblings();
}
// Get the screen number from window position using screen geometry
diff --git a/src/widgets/kernel/qdesktopwidget_p.h b/src/widgets/kernel/qdesktopwidget_p.h
index 69f87337b3..63949055aa 100644
--- a/src/widgets/kernel/qdesktopwidget_p.h
+++ b/src/widgets/kernel/qdesktopwidget_p.h
@@ -68,7 +68,7 @@ public:
int screenNumber() const;
void setScreenGeometry(const QRect &geometry);
- QScreen *screen() const { return m_screen.data(); }
+ QScreen *assignedScreen() const { return m_screen.data(); }
QRect screenGeometry() const { return m_geometry; }
private:
diff --git a/src/widgets/kernel/qformlayout.cpp b/src/widgets/kernel/qformlayout.cpp
index bd0ea2598a..6f7527c013 100644
--- a/src/widgets/kernel/qformlayout.cpp
+++ b/src/widgets/kernel/qformlayout.cpp
@@ -783,7 +783,7 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width)
vLayouts[vidx].expansive = expanding || (vLayouts[vidx].stretch > 0);
vLayouts[vidx].empty = false;
- if (vLayouts[vidx].stretch > 0)
+ if (vLayouts[vidx].expansive)
addTopBottomStretch = false;
if (vidx > 1)
@@ -2178,7 +2178,7 @@ void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, Q
int i;
const int rr = m_matrix.rowCount();
QWidget *w = q->parentWidget();
- Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection();
+ Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QGuiApplication::layoutDirection();
Qt::Alignment formAlignment = fixedAlignment(q->formAlignment(), layoutDirection);
int leftOffset = 0;
diff --git a/src/widgets/kernel/qgesture_p.h b/src/widgets/kernel/qgesture_p.h
index 636103c1e1..cbf8d60892 100644
--- a/src/widgets/kernel/qgesture_p.h
+++ b/src/widgets/kernel/qgesture_p.h
@@ -111,7 +111,7 @@ class QPinchGesturePrivate : public QGesturePrivate
public:
QPinchGesturePrivate()
- : totalChangeFlags(0), changeFlags(0),
+ : totalChangeFlags(nullptr), changeFlags(nullptr),
totalScaleFactor(1), lastScaleFactor(1), scaleFactor(1),
totalRotationAngle(0), lastRotationAngle(0), rotationAngle(0),
isNewSequence(true)
diff --git a/src/widgets/kernel/qgesturemanager.cpp b/src/widgets/kernel/qgesturemanager.cpp
index 5d2adc1e1c..d0c6b882b5 100644
--- a/src/widgets/kernel/qgesturemanager.cpp
+++ b/src/widgets/kernel/qgesturemanager.cpp
@@ -54,9 +54,6 @@
#ifdef Q_OS_OSX
#include "qmacgesturerecognizer_p.h"
#endif
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ && !defined(QT_NO_NATIVE_GESTURES)
-#include "qwinnativepangesturerecognizer_win_p.h"
-#endif
#include "qdebug.h"
#include <QtCore/QLoggingCategory>
@@ -102,14 +99,7 @@ QGestureManager::QGestureManager(QObject *parent)
registerGestureRecognizer(new QSwipeGestureRecognizer);
registerGestureRecognizer(new QTapGestureRecognizer);
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- #if !defined(QT_NO_NATIVE_GESTURES)
- if (QApplicationPrivate::HasTouchSupport)
- registerGestureRecognizer(new QWinNativePanGestureRecognizer);
- #endif
-#else
registerGestureRecognizer(new QTapAndHoldGestureRecognizer);
-#endif
}
QGestureManager::~QGestureManager()
@@ -168,30 +158,26 @@ void QGestureManager::unregisterGestureRecognizer(Qt::GestureType type)
void QGestureManager::cleanupCachedGestures(QObject *target, Qt::GestureType type)
{
- QMap<ObjectGesture, QList<QGesture *> >::Iterator iter = m_objectGestures.begin();
- while (iter != m_objectGestures.end()) {
- ObjectGesture objectGesture = iter.key();
- if (objectGesture.gesture == type && target == objectGesture.object) {
- QSet<QGesture *> gestures = iter.value().toSet();
- for (QHash<QGestureRecognizer *, QSet<QGesture *> >::iterator
- it = m_obsoleteGestures.begin(), e = m_obsoleteGestures.end(); it != e; ++it) {
- it.value() -= gestures;
- }
- foreach (QGesture *g, gestures) {
- m_deletedRecognizers.remove(g);
- m_gestureToRecognizer.remove(g);
- m_maybeGestures.remove(g);
- m_activeGestures.remove(g);
- m_gestureOwners.remove(g);
- m_gestureTargets.remove(g);
- m_gesturesToDelete.insert(g);
- }
+ const auto iter = m_objectGestures.find({target, type});
+ if (iter == m_objectGestures.end())
+ return;
- iter = m_objectGestures.erase(iter);
- } else {
- ++iter;
- }
+ const QList<QGesture *> &gestures = iter.value();
+ for (auto &e : m_obsoleteGestures) {
+ for (QGesture *g : gestures)
+ e -= g;
+ }
+ for (QGesture *g : gestures) {
+ m_deletedRecognizers.remove(g);
+ m_gestureToRecognizer.remove(g);
+ m_maybeGestures.remove(g);
+ m_activeGestures.remove(g);
+ m_gestureOwners.remove(g);
+ m_gestureTargets.remove(g);
+ m_gesturesToDelete.insert(g);
}
+
+ m_objectGestures.erase(iter);
}
// get or create a QGesture object that will represent the state for a given object, used by the recognizer
@@ -510,14 +496,14 @@ void QGestureManager::cleanupGesturesForRemovedRecognizer(QGesture *gesture)
// return true if accepted (consumed)
bool QGestureManager::filterEvent(QWidget *receiver, QEvent *event)
{
- QMap<Qt::GestureType, int> types;
+ QVarLengthArray<Qt::GestureType, 16> types;
QMultiMap<QObject *, Qt::GestureType> contexts;
QWidget *w = receiver;
typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
if (!w->d_func()->gestureContext.isEmpty()) {
for(ContextIterator it = w->d_func()->gestureContext.constBegin(),
e = w->d_func()->gestureContext.constEnd(); it != e; ++it) {
- types.insert(it.key(), 0);
+ types.push_back(it.key());
contexts.insert(w, it.key());
}
}
@@ -529,7 +515,7 @@ bool QGestureManager::filterEvent(QWidget *receiver, QEvent *event)
e = w->d_func()->gestureContext.constEnd(); it != e; ++it) {
if (!(it.value() & Qt::DontStartGestureOnChildren)) {
if (!types.contains(it.key())) {
- types.insert(it.key(), 0);
+ types.push_back(it.key());
contexts.insert(w, it.key());
}
}
@@ -544,14 +530,14 @@ bool QGestureManager::filterEvent(QWidget *receiver, QEvent *event)
#if QT_CONFIG(graphicsview)
bool QGestureManager::filterEvent(QGraphicsObject *receiver, QEvent *event)
{
- QMap<Qt::GestureType, int> types;
+ QVarLengthArray<Qt::GestureType, 16> types;
QMultiMap<QObject *, Qt::GestureType> contexts;
QGraphicsObject *item = receiver;
if (!item->QGraphicsItem::d_func()->gestureContext.isEmpty()) {
typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
for(ContextIterator it = item->QGraphicsItem::d_func()->gestureContext.constBegin(),
e = item->QGraphicsItem::d_func()->gestureContext.constEnd(); it != e; ++it) {
- types.insert(it.key(), 0);
+ types.push_back(it.key());
contexts.insert(item, it.key());
}
}
@@ -564,7 +550,7 @@ bool QGestureManager::filterEvent(QGraphicsObject *receiver, QEvent *event)
e = item->QGraphicsItem::d_func()->gestureContext.constEnd(); it != e; ++it) {
if (!(it.value() & Qt::DontStartGestureOnChildren)) {
if (!types.contains(it.key())) {
- types.insert(it.key(), 0);
+ types.push_back(it.key());
contexts.insert(item, it.key());
}
}
@@ -712,7 +698,7 @@ void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
foreach(QGesture *g, gestures)
event.setAccepted(g, false);
- QApplication::sendEvent(receiver, &event);
+ QCoreApplication::sendEvent(receiver, &event);
bool eventAccepted = event.isAccepted();
const auto eventGestures = event.gestures();
for (QGesture *gesture : eventGestures) {
@@ -739,7 +725,7 @@ void QGestureManager::deliverEvents(const QSet<QGesture *> &gestures,
qCDebug(lcGestureManager) << "QGestureManager::deliverEvents: sending to" << it.key()
<< "gestures:" << it.value();
QGestureEvent event(it.value());
- QApplication::sendEvent(it.key(), &event);
+ QCoreApplication::sendEvent(it.key(), &event);
bool eventAccepted = event.isAccepted();
const auto eventGestures = event.gestures();
for (QGesture *gesture : eventGestures) {
diff --git a/src/widgets/kernel/qlayout.cpp b/src/widgets/kernel/qlayout.cpp
index 53c4de49c6..3ce81a390b 100644
--- a/src/widgets/kernel/qlayout.cpp
+++ b/src/widgets/kernel/qlayout.cpp
@@ -1040,7 +1040,7 @@ void QLayout::update()
if (layout->d_func()->topLevel) {
Q_ASSERT(layout->parent()->isWidgetType());
QWidget *mw = static_cast<QWidget*>(layout->parent());
- QApplication::postEvent(mw, new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(mw, new QEvent(QEvent::LayoutRequest));
break;
}
layout = static_cast<QLayout*>(layout->parent());
@@ -1156,6 +1156,8 @@ QLayoutItem *QLayout::replaceWidget(QWidget *from, QWidget *to, Qt::FindChildOpt
Q_D(QLayout);
if (!from || !to)
return 0;
+ if (from == to) // Do not return a QLayoutItem for \a from, since ownership still
+ return nullptr; // belongs to the layout (since nothing was changed)
int index = -1;
QLayoutItem *item = 0;
@@ -1364,7 +1366,7 @@ QRect QLayout::alignmentRect(const QRect &r) const
y += (r.height() - s.height()) / 2;
QWidget *parent = parentWidget();
- a = QStyle::visualAlignment(parent ? parent->layoutDirection() : QApplication::layoutDirection(), a);
+ a = QStyle::visualAlignment(parent ? parent->layoutDirection() : QGuiApplication::layoutDirection(), a);
if (a & Qt::AlignRight)
x += (r.width() - s.width());
else if (!(a & Qt::AlignLeft))
diff --git a/src/widgets/kernel/qlayout_p.h b/src/widgets/kernel/qlayout_p.h
index 8a1b12a6be..8e1d773355 100644
--- a/src/widgets/kernel/qlayout_p.h
+++ b/src/widgets/kernel/qlayout_p.h
@@ -80,7 +80,7 @@ public:
static QWidgetItem *createWidgetItem(const QLayout *layout, QWidget *widget);
static QSpacerItem *createSpacerItem(const QLayout *layout, int w, int h, QSizePolicy::Policy hPolicy = QSizePolicy::Minimum, QSizePolicy::Policy vPolicy = QSizePolicy::Minimum);
- virtual QLayoutItem* replaceAt(int index, QLayoutItem *newitem) { Q_UNUSED(index); Q_UNUSED(newitem); return 0; }
+ virtual QLayoutItem* replaceAt(int index, QLayoutItem *newitem) { Q_UNUSED(index); Q_UNUSED(newitem); return nullptr; }
static QWidgetItemFactoryMethod widgetItemFactoryMethod;
static QSpacerItemFactoryMethod spacerItemFactoryMethod;
diff --git a/src/widgets/kernel/qlayoutengine_p.h b/src/widgets/kernel/qlayoutengine_p.h
index 812fa7cf3b..948c2424e6 100644
--- a/src/widgets/kernel/qlayoutengine_p.h
+++ b/src/widgets/kernel/qlayoutengine_p.h
@@ -105,9 +105,9 @@ Q_WIDGETS_EXPORT QSize qSmartMinSize(const QWidgetItem *i);
Q_WIDGETS_EXPORT QSize qSmartMinSize(const QWidget *w);
Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QSize &sizeHint,
const QSize &minSize, const QSize &maxSize,
- const QSizePolicy &sizePolicy, Qt::Alignment align = 0);
-Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QWidgetItem *i, Qt::Alignment align = 0);
-Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QWidget *w, Qt::Alignment align = 0);
+ const QSizePolicy &sizePolicy, Qt::Alignment align = nullptr);
+Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QWidgetItem *i, Qt::Alignment align = nullptr);
+Q_WIDGETS_EXPORT QSize qSmartMaxSize(const QWidget *w, Qt::Alignment align = nullptr);
Q_WIDGETS_EXPORT int qSmartSpacing(const QLayout *layout, QStyle::PixelMetric pm);
diff --git a/src/widgets/kernel/qlayoutitem.cpp b/src/widgets/kernel/qlayoutitem.cpp
index 9e6d1c5eac..0aab0bb06d 100644
--- a/src/widgets/kernel/qlayoutitem.cpp
+++ b/src/widgets/kernel/qlayoutitem.cpp
@@ -502,6 +502,17 @@ void QWidgetItem::setGeometry(const QRect &rect)
else if (!(align & Qt::AlignTop))
y = y + (r.height() - s.height()) / 2;
+ // Make sure we don't move outside of the parent, e.g when styles demand
+ // surplus space that exceeds the available margins (f.ex macOS with QGroupBox)
+ if (x < 0) {
+ s.rwidth() += x;
+ x = 0;
+ }
+ if (y < 0) {
+ s.rheight() += y;
+ y = 0;
+ }
+
wid->setGeometry(x, y, s.width(), s.height());
}
diff --git a/src/widgets/kernel/qopenglwidget.cpp b/src/widgets/kernel/qopenglwidget.cpp
index a88054a0d0..bc5ca21b97 100644
--- a/src/widgets/kernel/qopenglwidget.cpp
+++ b/src/widgets/kernel/qopenglwidget.cpp
@@ -1335,11 +1335,8 @@ int QOpenGLWidget::metric(QPaintDevice::PaintDeviceMetric metric) const
if (d->inBackingStorePaint)
return QWidget::metric(metric);
- QWidget *tlw = window();
- QWindow *window = tlw ? tlw->windowHandle() : 0;
- QScreen *screen = tlw && tlw->windowHandle() ? tlw->windowHandle()->screen() : 0;
- if (!screen && QGuiApplication::primaryScreen())
- screen = QGuiApplication::primaryScreen();
+ auto window = d->windowHandle(QWidgetPrivate::WindowHandleMode::TopLevel);
+ QScreen *screen = window ? window->screen() : QGuiApplication::primaryScreen();
const float dpmx = qt_defaultDpiX() * 100. / 2.54;
const float dpmy = qt_defaultDpiY() * 100. / 2.54;
@@ -1437,7 +1434,7 @@ bool QOpenGLWidget::event(QEvent *e)
Q_D(QOpenGLWidget);
switch (e->type()) {
case QEvent::WindowChangeInternal:
- if (qGuiApp->testAttribute(Qt::AA_ShareOpenGLContexts))
+ if (QCoreApplication::testAttribute(Qt::AA_ShareOpenGLContexts))
break;
if (d->initialized)
d->reset();
@@ -1450,7 +1447,7 @@ bool QOpenGLWidget::event(QEvent *e)
{
// Special case: did grabFramebuffer() for a hidden widget that then became visible.
// Recreate all resources since the context now needs to share with the TLW's.
- if (!qGuiApp->testAttribute(Qt::AA_ShareOpenGLContexts))
+ if (!QCoreApplication::testAttribute(Qt::AA_ShareOpenGLContexts))
d->reset();
}
if (!d->initialized && !size().isEmpty() && window()->windowHandle()) {
diff --git a/src/widgets/kernel/qshortcut.cpp b/src/widgets/kernel/qshortcut.cpp
index db06dce042..eec65c8625 100644
--- a/src/widgets/kernel/qshortcut.cpp
+++ b/src/widgets/kernel/qshortcut.cpp
@@ -96,8 +96,7 @@ bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
QWindow *qwindow = QGuiApplication::focusWindow();
if (qwindow && qwindow->isActive()) {
while (qwindow) {
- QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(qwindow);
- if (widgetWindow) {
+ if (auto widgetWindow = qobject_cast<QWidgetWindow *>(qwindow)) {
active_window = widgetWindow->widget();
break;
}
@@ -110,27 +109,25 @@ bool qWidgetShortcutContextMatcher(QObject *object, Qt::ShortcutContext context)
return false;
#ifndef QT_NO_ACTION
- if (QAction *a = qobject_cast<QAction *>(object))
+ if (auto a = qobject_cast<QAction *>(object))
return correctActionContext(context, a, active_window);
#endif
#if QT_CONFIG(graphicsview)
- if (QGraphicsWidget *gw = qobject_cast<QGraphicsWidget *>(object))
+ if (auto gw = qobject_cast<QGraphicsWidget *>(object))
return correctGraphicsWidgetContext(context, gw, active_window);
#endif
- QWidget *w = qobject_cast<QWidget *>(object);
+ auto w = qobject_cast<QWidget *>(object);
if (!w) {
- QShortcut *s = qobject_cast<QShortcut *>(object);
- if (s)
+ if (auto s = qobject_cast<QShortcut *>(object))
w = s->parentWidget();
}
if (!w) {
- QWindow *qwindow = qobject_cast<QWindow *>(object);
+ auto qwindow = qobject_cast<QWindow *>(object);
while (qwindow) {
- QWidgetWindow *widget_window = qobject_cast<QWidgetWindow *>(qwindow);
- if (widget_window) {
+ if (auto widget_window = qobject_cast<QWidgetWindow *>(qwindow)) {
w = widget_window->widget();
break;
}
@@ -148,7 +145,7 @@ static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidge
{
bool visible = w->isVisible();
#if QT_CONFIG(menubar)
- if (QMenuBar *menuBar = qobject_cast<QMenuBar *>(w)) {
+ if (auto menuBar = qobject_cast<QMenuBar *>(w)) {
if (auto *pmb = menuBar->platformMenuBar()) {
if (menuBar->parentWidget()) {
visible = true;
@@ -166,7 +163,7 @@ static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidge
return false;
if (context == Qt::ApplicationShortcut)
- return QApplicationPrivate::tryModalHelper(w, 0); // true, unless w is shadowed by a modal dialog
+ return QApplicationPrivate::tryModalHelper(w, nullptr); // true, unless w is shadowed by a modal dialog
if (context == Qt::WidgetShortcut)
return w == QApplication::focusWidget();
@@ -181,9 +178,9 @@ static bool correctWidgetContext(Qt::ShortcutContext context, QWidget *w, QWidge
// Below is Qt::WindowShortcut context
QWidget *tlw = w->window();
#if QT_CONFIG(graphicsview)
- if (QWExtra *topData = static_cast<QWidgetPrivate *>(QObjectPrivate::get(tlw))->extra) {
+ if (auto topData = static_cast<QWidgetPrivate *>(QObjectPrivate::get(tlw))->extra.get()) {
if (topData->proxyWidget) {
- bool res = correctGraphicsWidgetContext(context, (QGraphicsWidget *)topData->proxyWidget, active_window);
+ bool res = correctGraphicsWidgetContext(context, topData->proxyWidget, active_window);
return res;
}
}
@@ -233,7 +230,7 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
{
bool visible = w->isVisible();
#if defined(Q_OS_DARWIN) && QT_CONFIG(menubar)
- if (!qApp->testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
+ if (!QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuBar) && qobject_cast<QMenuBar *>(w))
visible = true;
#endif
@@ -244,9 +241,9 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
// Applicationwide shortcuts are always reachable unless their owner
// is shadowed by modality. In QGV there's no modality concept, but we
// must still check if all views are shadowed.
- QList<QGraphicsView *> views = w->scene()->views();
- for (int i = 0; i < views.size(); ++i) {
- if (QApplicationPrivate::tryModalHelper(views.at(i), 0))
+ const auto &views = w->scene()->views();
+ for (auto view : views) {
+ if (QApplicationPrivate::tryModalHelper(view, nullptr))
return true;
}
return false;
@@ -258,7 +255,7 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
if (context == Qt::WidgetWithChildrenShortcut) {
const QGraphicsItem *ti = w->scene()->focusItem();
if (ti && ti->isWidget()) {
- const QGraphicsWidget *tw = static_cast<const QGraphicsWidget *>(ti);
+ const auto *tw = static_cast<const QGraphicsWidget *>(ti);
while (tw && tw != w && (tw->windowType() == Qt::Widget || tw->windowType() == Qt::Popup))
tw = tw->parentWidget();
return tw == w;
@@ -269,10 +266,9 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
// Below is Qt::WindowShortcut context
// Find the active view (if any).
- QList<QGraphicsView *> views = w->scene()->views();
- QGraphicsView *activeView = 0;
- for (int i = 0; i < views.size(); ++i) {
- QGraphicsView *view = views.at(i);
+ const auto &views = w->scene()->views();
+ QGraphicsView *activeView = nullptr;
+ for (auto view : views) {
if (view->window() == active_window) {
activeView = view;
break;
@@ -291,15 +287,14 @@ static bool correctGraphicsWidgetContext(Qt::ShortcutContext context, QGraphicsW
#ifndef QT_NO_ACTION
static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidget *active_window)
{
- const QList<QWidget *> &widgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->widgets;
+ const QWidgetList &widgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->widgets;
#if defined(DEBUG_QSHORTCUTMAP)
if (widgets.isEmpty())
qDebug() << a << "not connected to any widgets; won't trigger";
#endif
- for (int i = 0; i < widgets.size(); ++i) {
- QWidget *w = widgets.at(i);
+ for (auto w : widgets) {
#if QT_CONFIG(menu)
- if (QMenu *menu = qobject_cast<QMenu *>(w)) {
+ if (auto menu = qobject_cast<QMenu *>(w)) {
#ifdef Q_OS_DARWIN
// On Mac, menu item shortcuts are processed before reaching any window.
// That means that if a menu action shortcut has not been already processed
@@ -325,14 +320,13 @@ static bool correctActionContext(Qt::ShortcutContext context, QAction *a, QWidge
}
#if QT_CONFIG(graphicsview)
- const QList<QGraphicsWidget *> &graphicsWidgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->graphicsWidgets;
+ const auto &graphicsWidgets = static_cast<QActionPrivate *>(QObjectPrivate::get(a))->graphicsWidgets;
#if defined(DEBUG_QSHORTCUTMAP)
if (graphicsWidgets.isEmpty())
qDebug() << a << "not connected to any widgets; won't trigger";
#endif
- for (int i = 0; i < graphicsWidgets.size(); ++i) {
- QGraphicsWidget *w = graphicsWidgets.at(i);
- if (correctGraphicsWidgetContext(context, w, active_window))
+ for (auto graphicsWidget : graphicsWidgets) {
+ if (correctGraphicsWidgetContext(context, graphicsWidget, active_window))
return true;
}
#endif
@@ -433,12 +427,12 @@ class QShortcutPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QShortcut)
public:
- QShortcutPrivate() : sc_context(Qt::WindowShortcut), sc_enabled(true), sc_autorepeat(true), sc_id(0) {}
+ QShortcutPrivate() = default;
QKeySequence sc_sequence;
- Qt::ShortcutContext sc_context;
- bool sc_enabled;
- bool sc_autorepeat;
- int sc_id;
+ Qt::ShortcutContext sc_context = Qt::WindowShortcut;
+ bool sc_enabled = true;
+ bool sc_autorepeat = true;
+ int sc_id = 0;
QString sc_whatsthis;
void redoGrab(QShortcutMap &map);
};
@@ -472,7 +466,7 @@ void QShortcutPrivate::redoGrab(QShortcutMap &map)
QShortcut::QShortcut(QWidget *parent)
: QObject(*new QShortcutPrivate, parent)
{
- Q_ASSERT(parent != 0);
+ Q_ASSERT(parent != nullptr);
}
/*!
@@ -493,7 +487,7 @@ QShortcut::QShortcut(const QKeySequence &key, QWidget *parent,
Q_D(QShortcut);
d->sc_context = context;
d->sc_sequence = key;
- d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
if (member)
connect(this, SIGNAL(activated()), parent, member);
if (ambiguousMember)
@@ -507,7 +501,7 @@ QShortcut::~QShortcut()
{
Q_D(QShortcut);
if (qApp)
- qApp->d_func()->shortcutMap.removeShortcut(d->sc_id, this);
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(d->sc_id, this);
}
/*!
@@ -528,7 +522,7 @@ void QShortcut::setKey(const QKeySequence &key)
return;
QAPP_CHECK("setKey");
d->sc_sequence = key;
- d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
}
QKeySequence QShortcut::key() const
@@ -559,7 +553,7 @@ void QShortcut::setEnabled(bool enable)
return;
QAPP_CHECK("setEnabled");
d->sc_enabled = enable;
- qApp->d_func()->shortcutMap.setShortcutEnabled(enable, d->sc_id, this);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutEnabled(enable, d->sc_id, this);
}
bool QShortcut::isEnabled() const
@@ -587,7 +581,7 @@ void QShortcut::setContext(Qt::ShortcutContext context)
return;
QAPP_CHECK("setContext");
d->sc_context = context;
- d->redoGrab(qApp->d_func()->shortcutMap);
+ d->redoGrab(QGuiApplicationPrivate::instance()->shortcutMap);
}
Qt::ShortcutContext QShortcut::context() const
@@ -639,7 +633,7 @@ void QShortcut::setAutoRepeat(bool on)
return;
QAPP_CHECK("setAutoRepeat");
d->sc_autorepeat = on;
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(on, d->sc_id, this);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutAutoRepeat(on, d->sc_id, this);
}
bool QShortcut::autoRepeat() const
@@ -666,7 +660,7 @@ bool QShortcut::event(QEvent *e)
{
Q_D(QShortcut);
if (d->sc_enabled && e->type() == QEvent::Shortcut) {
- QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
+ auto se = static_cast<QShortcutEvent *>(e);
if (se->shortcutId() == d->sc_id && se->key() == d->sc_sequence){
#if QT_CONFIG(whatsthis)
if (QWhatsThis::inWhatsThisMode()) {
diff --git a/src/widgets/kernel/qsizepolicy.cpp b/src/widgets/kernel/qsizepolicy.cpp
index b5a0cd3940..54bf8fe0dc 100644
--- a/src/widgets/kernel/qsizepolicy.cpp
+++ b/src/widgets/kernel/qsizepolicy.cpp
@@ -232,7 +232,7 @@ QT_BEGIN_NAMESPACE
Returns the control type associated with the widget for which
this size policy applies.
*/
-QSizePolicy::ControlType QSizePolicy::controlType() const Q_DECL_NOTHROW
+QSizePolicy::ControlType QSizePolicy::controlType() const noexcept
{
return QSizePolicy::ControlType(1 << bits.ctype);
}
@@ -253,7 +253,7 @@ QSizePolicy::ControlType QSizePolicy::controlType() const Q_DECL_NOTHROW
\sa QStyle::layoutSpacing()
*/
-void QSizePolicy::setControlType(ControlType type) Q_DECL_NOTHROW
+void QSizePolicy::setControlType(ControlType type) noexcept
{
bits.ctype = toControlTypeFieldValue(type);
}
diff --git a/src/widgets/kernel/qsizepolicy.h b/src/widgets/kernel/qsizepolicy.h
index dba742dec5..f26923eeb0 100644
--- a/src/widgets/kernel/qsizepolicy.h
+++ b/src/widgets/kernel/qsizepolicy.h
@@ -65,7 +65,7 @@ QT_BEGIN_NAMESPACE
class QVariant;
class QSizePolicy;
-Q_DECL_CONST_FUNCTION inline uint qHash(QSizePolicy key, uint seed = 0) Q_DECL_NOTHROW;
+Q_DECL_CONST_FUNCTION inline uint qHash(QSizePolicy key, uint seed = 0) noexcept;
class Q_WIDGETS_EXPORT QSizePolicy
{
@@ -110,60 +110,60 @@ public:
Q_DECLARE_FLAGS(ControlTypes, ControlType)
Q_FLAG(ControlTypes)
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy() Q_DECL_NOTHROW : data(0) { }
+ QT_SIZEPOLICY_CONSTEXPR QSizePolicy() noexcept : data(0) { }
#if defined(Q_COMPILER_UNIFORM_INIT) && !defined(Q_QDOC)
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) Q_DECL_NOTHROW
+ QT_SIZEPOLICY_CONSTEXPR QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) noexcept
: bits{0, 0, quint32(horizontal), quint32(vertical),
type == DefaultType ? 0 : toControlTypeFieldValue(type), 0, 0, 0}
{}
#else
- QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) Q_DECL_NOTHROW
+ QSizePolicy(Policy horizontal, Policy vertical, ControlType type = DefaultType) noexcept
: data(0) {
bits.horPolicy = horizontal;
bits.verPolicy = vertical;
setControlType(type);
}
#endif // uniform-init
- QT_SIZEPOLICY_CONSTEXPR Policy horizontalPolicy() const Q_DECL_NOTHROW { return static_cast<Policy>(bits.horPolicy); }
- QT_SIZEPOLICY_CONSTEXPR Policy verticalPolicy() const Q_DECL_NOTHROW { return static_cast<Policy>(bits.verPolicy); }
- ControlType controlType() const Q_DECL_NOTHROW;
+ QT_SIZEPOLICY_CONSTEXPR Policy horizontalPolicy() const noexcept { return static_cast<Policy>(bits.horPolicy); }
+ QT_SIZEPOLICY_CONSTEXPR Policy verticalPolicy() const noexcept { return static_cast<Policy>(bits.verPolicy); }
+ ControlType controlType() const noexcept;
- Q_DECL_RELAXED_CONSTEXPR void setHorizontalPolicy(Policy d) Q_DECL_NOTHROW { bits.horPolicy = d; }
- Q_DECL_RELAXED_CONSTEXPR void setVerticalPolicy(Policy d) Q_DECL_NOTHROW { bits.verPolicy = d; }
- void setControlType(ControlType type) Q_DECL_NOTHROW;
+ Q_DECL_RELAXED_CONSTEXPR void setHorizontalPolicy(Policy d) noexcept { bits.horPolicy = d; }
+ Q_DECL_RELAXED_CONSTEXPR void setVerticalPolicy(Policy d) noexcept { bits.verPolicy = d; }
+ void setControlType(ControlType type) noexcept;
- QT_SIZEPOLICY_CONSTEXPR Qt::Orientations expandingDirections() const Q_DECL_NOTHROW {
+ QT_SIZEPOLICY_CONSTEXPR Qt::Orientations expandingDirections() const noexcept {
return ( (verticalPolicy() & ExpandFlag) ? Qt::Vertical : Qt::Orientations() )
| ( (horizontalPolicy() & ExpandFlag) ? Qt::Horizontal : Qt::Orientations() ) ;
}
- Q_DECL_RELAXED_CONSTEXPR void setHeightForWidth(bool b) Q_DECL_NOTHROW { bits.hfw = b; }
- QT_SIZEPOLICY_CONSTEXPR bool hasHeightForWidth() const Q_DECL_NOTHROW { return bits.hfw; }
- Q_DECL_RELAXED_CONSTEXPR void setWidthForHeight(bool b) Q_DECL_NOTHROW { bits.wfh = b; }
- QT_SIZEPOLICY_CONSTEXPR bool hasWidthForHeight() const Q_DECL_NOTHROW { return bits.wfh; }
+ Q_DECL_RELAXED_CONSTEXPR void setHeightForWidth(bool b) noexcept { bits.hfw = b; }
+ QT_SIZEPOLICY_CONSTEXPR bool hasHeightForWidth() const noexcept { return bits.hfw; }
+ Q_DECL_RELAXED_CONSTEXPR void setWidthForHeight(bool b) noexcept { bits.wfh = b; }
+ QT_SIZEPOLICY_CONSTEXPR bool hasWidthForHeight() const noexcept { return bits.wfh; }
- QT_SIZEPOLICY_CONSTEXPR bool operator==(const QSizePolicy& s) const Q_DECL_NOTHROW { return data == s.data; }
- QT_SIZEPOLICY_CONSTEXPR bool operator!=(const QSizePolicy& s) const Q_DECL_NOTHROW { return data != s.data; }
+ QT_SIZEPOLICY_CONSTEXPR bool operator==(const QSizePolicy& s) const noexcept { return data == s.data; }
+ QT_SIZEPOLICY_CONSTEXPR bool operator!=(const QSizePolicy& s) const noexcept { return data != s.data; }
- friend Q_DECL_CONST_FUNCTION uint qHash(QSizePolicy key, uint seed) Q_DECL_NOTHROW { return qHash(key.data, seed); }
+ friend Q_DECL_CONST_FUNCTION uint qHash(QSizePolicy key, uint seed) noexcept { return qHash(key.data, seed); }
operator QVariant() const;
- QT_SIZEPOLICY_CONSTEXPR int horizontalStretch() const Q_DECL_NOTHROW { return static_cast<int>(bits.horStretch); }
- QT_SIZEPOLICY_CONSTEXPR int verticalStretch() const Q_DECL_NOTHROW { return static_cast<int>(bits.verStretch); }
+ QT_SIZEPOLICY_CONSTEXPR int horizontalStretch() const noexcept { return static_cast<int>(bits.horStretch); }
+ QT_SIZEPOLICY_CONSTEXPR int verticalStretch() const noexcept { return static_cast<int>(bits.verStretch); }
Q_DECL_RELAXED_CONSTEXPR void setHorizontalStretch(int stretchFactor) { bits.horStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
Q_DECL_RELAXED_CONSTEXPR void setVerticalStretch(int stretchFactor) { bits.verStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
- QT_SIZEPOLICY_CONSTEXPR bool retainSizeWhenHidden() const Q_DECL_NOTHROW { return bits.retainSizeWhenHidden; }
- Q_DECL_RELAXED_CONSTEXPR void setRetainSizeWhenHidden(bool retainSize) Q_DECL_NOTHROW { bits.retainSizeWhenHidden = retainSize; }
+ QT_SIZEPOLICY_CONSTEXPR bool retainSizeWhenHidden() const noexcept { return bits.retainSizeWhenHidden; }
+ Q_DECL_RELAXED_CONSTEXPR void setRetainSizeWhenHidden(bool retainSize) noexcept { bits.retainSizeWhenHidden = retainSize; }
- Q_DECL_RELAXED_CONSTEXPR void transpose() Q_DECL_NOTHROW { *this = transposed(); }
+ Q_DECL_RELAXED_CONSTEXPR void transpose() noexcept { *this = transposed(); }
Q_REQUIRED_RESULT
#ifndef Q_QDOC
QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
#endif
- QSizePolicy transposed() const Q_DECL_NOTHROW
+ QSizePolicy transposed() const noexcept
{
return QSizePolicy(bits.transposed());
}
@@ -173,11 +173,11 @@ private:
friend Q_WIDGETS_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &);
friend Q_WIDGETS_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &);
#endif
- QT_SIZEPOLICY_CONSTEXPR QSizePolicy(int i) Q_DECL_NOTHROW : data(i) { }
+ QT_SIZEPOLICY_CONSTEXPR QSizePolicy(int i) noexcept : data(i) { }
struct Bits;
- QT_SIZEPOLICY_CONSTEXPR explicit QSizePolicy(Bits b) Q_DECL_NOTHROW : bits(b) { }
+ QT_SIZEPOLICY_CONSTEXPR explicit QSizePolicy(Bits b) noexcept : bits(b) { }
- static Q_DECL_RELAXED_CONSTEXPR quint32 toControlTypeFieldValue(ControlType type) Q_DECL_NOTHROW
+ static Q_DECL_RELAXED_CONSTEXPR quint32 toControlTypeFieldValue(ControlType type) noexcept
{
/*
The control type is a flag type, with values 0x1, 0x2, 0x4, 0x8, 0x10,
@@ -207,7 +207,7 @@ private:
quint32 retainSizeWhenHidden : 1;
QT_SIZEPOLICY_CONSTEXPR_AND_UNIFORM_INIT
- Bits transposed() const Q_DECL_NOTHROW
+ Bits transposed() const noexcept
{
return {verStretch, // \ swap
horStretch, // /
diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp
index f81cb471fa..97a279d65d 100644
--- a/src/widgets/kernel/qtooltip.cpp
+++ b/src/widgets/kernel/qtooltip.cpp
@@ -36,12 +36,8 @@
** $QT_END_LICENSE$
**
****************************************************************************/
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# include <private/qcore_mac_p.h>
-#endif
#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <QtWidgets/private/qlabel_p.h>
#include <qapplication.h>
#include <qdesktopwidget.h>
@@ -61,13 +57,9 @@
#ifndef QT_NO_TOOLTIP
#include <qlabel.h>
+#include <QtWidgets/private/qlabel_p.h>
#include <qtooltip.h>
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# include <private/qcore_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
QT_BEGIN_NAMESPACE
/*!
@@ -317,20 +309,7 @@ void QTipLabel::timerEvent(QTimerEvent *e)
|| e->timerId() == expireTimer.timerId()){
hideTimer.stop();
expireTimer.stop();
-#if 0 /* Used to be included in Qt4 for Q_WS_MAC */ && QT_CONFIG(effects)
- if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip)){
- // Fade out tip on mac (makes it invisible).
- // The tip will not be deleted until a new tip is shown.
-
- // DRSWAT - Cocoa
- macWindowFade(qt_mac_window_for(this));
- QTipLabel::instance->fadingOut = true; // will never be false again.
- }
- else
- hideTipImmediately();
-#else
hideTipImmediately();
-#endif
}
}
@@ -420,29 +399,11 @@ void QTipLabel::placeTip(const QPoint &pos, QWidget *w)
#endif //QT_NO_STYLE_STYLESHEET
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // When in full screen mode, there is no Dock nor Menu so we can use
- // the whole screen for displaying the tooltip. However when not in
- // full screen mode we need to save space for the dock, so we use
- // availableGeometry instead.
- extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
- QRect screen;
- if(qt_mac_app_fullscreen)
- screen = QDesktopWidgetPrivate::screenGeometry(getTipScreen(pos, w));
- else
- screen = QDesktopWidgetPrivate::availableGeometry(getTipScreen(pos, w));
-#else
QRect screen = QDesktopWidgetPrivate::screenGeometry(getTipScreen(pos, w));
-#endif
QPoint p = pos;
- p += QPoint(2,
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- 21
-#else
- 16
-#endif
- );
+ p += QPoint(2, 16);
+
if (p.x() + this->width() > screen.x() + screen.width())
p.rx() -= 4 + this->width();
if (p.y() + this->height() > screen.y() + screen.height())
@@ -541,7 +502,7 @@ QT_WARNING_POP
QTipLabel::instance->setObjectName(QLatin1String("qtooltip_label"));
-#if QT_CONFIG(effects) && !0 /* Used to be included in Qt4 for Q_WS_MAC */
+#if QT_CONFIG(effects)
if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
qFadeEffect(QTipLabel::instance);
else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
diff --git a/src/widgets/kernel/qtooltip.h b/src/widgets/kernel/qtooltip.h
index edf1de0c1d..1b263a6629 100644
--- a/src/widgets/kernel/qtooltip.h
+++ b/src/widgets/kernel/qtooltip.h
@@ -50,7 +50,7 @@ QT_BEGIN_NAMESPACE
class Q_WIDGETS_EXPORT QToolTip
{
- QToolTip() Q_DECL_EQ_DELETE;
+ QToolTip() = delete;
public:
// ### Qt 6 - merge the three showText functions below
static void showText(const QPoint &pos, const QString &text, QWidget *w = nullptr);
diff --git a/src/widgets/kernel/qwhatsthis.cpp b/src/widgets/kernel/qwhatsthis.cpp
index 4a798a7490..228ca4d38a 100644
--- a/src/widgets/kernel/qwhatsthis.cpp
+++ b/src/widgets/kernel/qwhatsthis.cpp
@@ -263,7 +263,7 @@ void QWhatsThat::mouseReleaseEvent(QMouseEvent* e)
anchor.clear();
if (!href.isEmpty()) {
QWhatsThisClickedEvent e(href);
- if (QApplication::sendEvent(widget, &e))
+ if (QCoreApplication::sendEvent(widget, &e))
return;
}
}
@@ -380,7 +380,7 @@ void QWhatsThisPrivate::notifyToplevels(QEvent *e)
{
const QWidgetList toplevels = QApplication::topLevelWidgets();
for (auto *w : toplevels)
- QApplication::sendEvent(w, e);
+ QCoreApplication::sendEvent(w, e);
}
QWhatsThisPrivate *QWhatsThisPrivate::instance = 0;
@@ -394,7 +394,7 @@ QWhatsThisPrivate::QWhatsThisPrivate()
QPoint pos = QCursor::pos();
if (QWidget *w = QApplication::widgetAt(pos)) {
QHelpEvent e(QEvent::QueryWhatsThis, w->mapFromGlobal(pos), pos);
- bool sentEvent = QApplication::sendEvent(w, &e);
+ const bool sentEvent = QCoreApplication::sendEvent(w, &e);
#ifdef QT_NO_CURSOR
Q_UNUSED(sentEvent);
#else
@@ -439,7 +439,7 @@ bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
if (me->button() == Qt::RightButton || customWhatsThis)
return false;
QHelpEvent e(QEvent::WhatsThis, me->pos(), me->globalPos());
- if (!QApplication::sendEvent(w, &e) || !e.isAccepted())
+ if (!QCoreApplication::sendEvent(w, &e) || !e.isAccepted())
leaveOnMouseRelease = true;
} break;
@@ -448,12 +448,12 @@ bool QWhatsThisPrivate::eventFilter(QObject *o, QEvent *e)
{
QMouseEvent *me = static_cast<QMouseEvent*>(e);
QHelpEvent e(QEvent::QueryWhatsThis, me->pos(), me->globalPos());
- bool sentEvent = QApplication::sendEvent(w, &e);
+ const bool sentEvent = QCoreApplication::sendEvent(w, &e);
#ifdef QT_NO_CURSOR
Q_UNUSED(sentEvent);
#else
- QApplication::changeOverrideCursor((!sentEvent || !e.isAccepted())?
- Qt::ForbiddenCursor:Qt::WhatsThisCursor);
+ QGuiApplication::changeOverrideCursor((!sentEvent || !e.isAccepted())?
+ Qt::ForbiddenCursor:Qt::WhatsThisCursor);
#endif
Q_FALLTHROUGH();
}
@@ -577,26 +577,12 @@ void QWhatsThisPrivate::say(QWidget * widget, const QString &text, int x, int y)
if (text.size() == 0)
return;
// make a fresh widget, and set it up
- QWhatsThat *whatsThat = new QWhatsThat(
- text,
-#if 0 /* Used to be included in Qt4 for Q_WS_X11 */ && !defined(QT_NO_CURSOR)
- QApplication::desktop()->screen(widget ? widget->x11Info().screen() : QCursor::x11Screen()),
-#else
- 0,
-#endif
- widget
- );
-
+ QWhatsThat *whatsThat = new QWhatsThat(text, 0, widget);
// okay, now to find a suitable location
-
int scr = (widget ?
QDesktopWidgetPrivate::screenNumber(widget) :
-#if 0 /* Used to be included in Qt4 for Q_WS_X11 */ && !defined(QT_NO_CURSOR)
- QCursor::x11Screen()
-#else
QDesktopWidgetPrivate::screenNumber(QPoint(x,y))
-#endif
);
QRect screen = QDesktopWidgetPrivate::screenGeometry(scr);
diff --git a/src/widgets/kernel/qwhatsthis.h b/src/widgets/kernel/qwhatsthis.h
index 59c0b01c9b..fa5b97d98a 100644
--- a/src/widgets/kernel/qwhatsthis.h
+++ b/src/widgets/kernel/qwhatsthis.h
@@ -54,7 +54,7 @@ class QAction;
class Q_WIDGETS_EXPORT QWhatsThis
{
- QWhatsThis() Q_DECL_EQ_DELETE;
+ QWhatsThis() = delete;
public:
static void enterWhatsThisMode();
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 048a17364b..e9968e41b4 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -61,13 +61,6 @@
#ifndef QT_NO_ACCESSIBILITY
# include "qaccessible.h"
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# include "qt_mac_p.h"
-# include "qt_cocoa_helpers_mac_p.h"
-# include "qmainwindow.h"
-# include "qtoolbar.h"
-# include <private/qmainwindowlayout_p.h>
-#endif
#include <qpa/qplatformwindow.h>
#include "private/qwidgetwindow_p.h"
#include "qpainter.h"
@@ -79,6 +72,7 @@
#include "private/qstylesheetstyle_p.h"
#include "private/qstyle_p.h"
#include "qfileinfo.h"
+#include "qscopeguard.h"
#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qinputmethod.h>
#include <QtGui/qopenglcontext.h>
@@ -89,10 +83,7 @@
#include <private/qgraphicseffect_p.h>
#endif
#include <qbackingstore.h>
-#include <private/qwidgetbackingstore_p.h>
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# include <private/qpaintengine_mac_p.h>
-#endif
+#include <private/qwidgetrepaintmanager_p.h>
#include <private/qpaintengine_raster_p.h>
#include "qwidget_p.h"
@@ -120,15 +111,15 @@
#include <QtPlatformHeaders/qxcbwindowfunctions.h>
+#include <private/qmemory_p.h>
+
// widget/widget data creation count
//#define QWIDGET_EXTRA_DEBUG
//#define ALIEN_DEBUG
QT_BEGIN_NAMESPACE
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
-#endif
+Q_LOGGING_CATEGORY(lcWidgetPainting, "qt.widgets.painting", QtWarningMsg);
static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
{
@@ -136,101 +127,11 @@ static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# define QT_NO_PAINT_DEBUG
-#endif
-
extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
-/*!
- \internal
- \class QWidgetBackingStoreTracker
- \brief Class which allows tracking of which widgets are using a given backing store
-
- QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
- which maintains a list of the QWidgets which are currently using the backing
- store. This list is modified via the registerWidget and unregisterWidget functions.
- */
-
-QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
- : m_ptr(0)
-{
-
-}
-
-QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
-{
- delete m_ptr;
-}
-
-/*!
- \internal
- Destroy the contained QWidgetBackingStore, if not null, and clear the list of
- widgets using the backing store, then create a new QWidgetBackingStore, providing
- the QWidget.
- */
-void QWidgetBackingStoreTracker::create(QWidget *widget)
-{
- destroy();
- m_ptr = new QWidgetBackingStore(widget);
-}
-
-/*!
- \internal
- Destroy the contained QWidgetBackingStore, if not null, and clear the list of
- widgets using the backing store.
- */
-void QWidgetBackingStoreTracker::destroy()
-{
- delete m_ptr;
- m_ptr = 0;
- m_widgets.clear();
-}
-
-/*!
- \internal
- Add the widget to the list of widgets currently using the backing store.
- If the widget was already in the list, this function is a no-op.
- */
-void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
-{
- Q_ASSERT(m_ptr);
- Q_ASSERT(w->internalWinId());
- Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
- m_widgets.insert(w);
-}
-
-/*!
- \internal
- Remove the widget from the list of widgets currently using the backing store.
- If the widget was in the list, and removing it causes the list to be empty,
- the backing store is deleted.
- If the widget was not in the list, this function is a no-op.
- */
-void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
-{
- if (m_widgets.remove(w) && m_widgets.isEmpty()) {
- delete m_ptr;
- m_ptr = 0;
- }
-}
-
-/*!
- \internal
- Recursively remove widget and all of its descendents.
- */
-void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
-{
- unregisterWidget(widget);
- foreach (QObject *child, widget->children())
- if (QWidget *childWidget = qobject_cast<QWidget *>(child))
- unregisterWidgetSubtree(childWidget);
-}
-
QWidgetPrivate::QWidgetPrivate(int version)
: QObjectPrivate(version)
- , extra(0)
, focus_next(0)
, focus_prev(0)
, focus_child(0)
@@ -284,17 +185,6 @@ QWidgetPrivate::QWidgetPrivate(int version)
#if defined(Q_OS_WIN)
, noPaintOnScreen(0)
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- , picture(0)
-#elif 0 // Used to be included in Qt4 for Q_WS_WIN
- #ifndef QT_NO_GESTURES
- , nativeGesturePanEnabled(0)
- #endif
-#elif 0 // Used to be included in Qt4 for Q_WS_MAC
- , needWindowChange(0)
- , window_event(0)
- , qd_hd(0)
-#endif
{
if (Q_UNLIKELY(!qApp)) {
qFatal("QWidget: Must construct a QApplication before a QWidget");
@@ -313,16 +203,7 @@ QWidgetPrivate::QWidgetPrivate(int version)
isWidget = true;
memset(high_attributes, 0, sizeof(high_attributes));
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- drawRectOriginalAdded = false;
- originalDrawMethod = true;
- changeMethods = false;
- isInUnifiedToolbar = false;
- unifiedSurface = 0;
- toolbar_ancestor = 0;
- flushRequested = false;
- touchEventsEnabled = false;
-#endif
+
#ifdef QWIDGET_EXTRA_DEBUG
static int count = 0;
qDebug() << "widgets" << ++count;
@@ -358,7 +239,7 @@ void QWidgetPrivate::scrollChildren(int dx, int dy)
w->d_func()->setWSGeometry();
w->d_func()->setDirtyOpaqueRegion();
QMoveEvent e(r.topLeft(), oldp);
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
}
}
@@ -392,7 +273,7 @@ QPointer<QWidget> QWidgetPrivate::editingWidget;
This feature is only available in Qt for Embedded Linux.
- \sa setEditFocus(), QApplication::keypadNavigationEnabled()
+ \sa setEditFocus(), QApplication::navigationMode()
*/
bool QWidget::hasEditFocus() const
{
@@ -412,7 +293,7 @@ bool QWidget::hasEditFocus() const
This feature is only available in Qt for Embedded Linux.
- \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
+ \sa hasEditFocus(), QApplication::navigationMode()
*/
void QWidget::setEditFocus(bool on)
{
@@ -434,13 +315,13 @@ void QWidget::setEditFocus(bool on)
if (!on && QWidgetPrivate::editingWidget == f) {
QWidgetPrivate::editingWidget = 0;
QEvent event(QEvent::LeaveEditFocus);
- QApplication::sendEvent(f, &event);
- QApplication::sendEvent(f->style(), &event);
+ QCoreApplication::sendEvent(f, &event);
+ QCoreApplication::sendEvent(f->style(), &event);
} else if (on) {
QWidgetPrivate::editingWidget = f;
QEvent event(QEvent::EnterEditFocus);
- QApplication::sendEvent(f, &event);
- QApplication::sendEvent(f->style(), &event);
+ QCoreApplication::sendEvent(f, &event);
+ QCoreApplication::sendEvent(f->style(), &event);
}
}
#endif
@@ -943,22 +824,6 @@ QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
/*****************************************************************************
- QWidget utility functions
- *****************************************************************************/
-
-QRegion qt_dirtyRegion(QWidget *widget)
-{
- if (!widget)
- return QRegion();
-
- QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
- if (!bs)
- return QRegion();
-
- return bs->dirtyRegion(widget);
-}
-
-/*****************************************************************************
QWidget member functions
*****************************************************************************/
@@ -1083,17 +948,12 @@ void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
// Only enable this on non-Mac platforms. Since the old way of doing this would
// interpret WindowSystemMenuHint as a close button and we can't change that behavior
// we can't just add this in.
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
if ((flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint))
# ifdef Q_OS_WIN
&& type != Qt::Dialog // QTBUG-2027, allow for menu-less dialogs.
# endif
) {
flags |= Qt::WindowSystemMenuHint;
-#else
- if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
- | Qt::WindowSystemMenuHint)) {
-#endif
flags |= Qt::WindowTitleHint;
flags &= ~Qt::FramelessWindowHint;
}
@@ -1123,6 +983,8 @@ void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
{
Q_Q(QWidget);
+ Q_ASSERT_X(q != parentWidget, Q_FUNC_INFO, "Cannot parent a QWidget to itself");
+
if (Q_UNLIKELY(!qobject_cast<QApplication *>(QCoreApplication::instance())))
qFatal("QWidget: Cannot create a QWidget without QApplication");
@@ -1146,13 +1008,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
}
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- if (desktopWidget) {
- // make sure the widget is created on the same screen as the
- // programmer specified desktop widget
- xinfo = desktopWidget->d_func()->xinfo;
- }
-#endif
if (targetScreen >= 0) {
topData()->initialScreenIndex = targetScreen;
if (QWindow *window = q->windowHandle())
@@ -1180,9 +1035,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
mustHaveWindowHandle = 1;
q->setAttribute(Qt::WA_NativeWindow);
}
-//#if 0 // Used to be included in Qt4 for Q_WS_MAC
-// q->setAttribute(Qt::WA_NativeWindow);
-//#endif
q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
adjustQuitOnCloseAttribute();
@@ -1206,9 +1058,6 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
}
data.fnt = QFont(data.fnt, q);
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- data.fnt.x11SetScreen(xinfo.screen());
-#endif
q->setAttribute(Qt::WA_PendingMoveEvent);
q->setAttribute(Qt::WA_PendingResizeEvent);
@@ -1220,24 +1069,12 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
q->create();
QEvent e(QEvent::Create);
- QApplication::sendEvent(q, &e);
- QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
+ QCoreApplication::sendEvent(q, &e);
+ QCoreApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
extraPaintEngine = 0;
-
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // If we add a child to the unified toolbar, we have to redirect the painting.
- if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
- if (parentWidget->d_func()->unifiedSurface) {
- QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
- parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
- }
- }
-#endif
}
-
-
void QWidgetPrivate::createRecursively()
{
Q_Q(QWidget);
@@ -1249,6 +1086,35 @@ void QWidgetPrivate::createRecursively()
}
}
+QWindow *QWidgetPrivate::windowHandle(WindowHandleMode mode) const
+{
+ if (mode == WindowHandleMode::Direct || mode == WindowHandleMode::Closest) {
+ if (QTLWExtra *x = maybeTopData()) {
+ if (x->window != nullptr || mode == WindowHandleMode::Direct)
+ return x->window;
+ }
+ }
+ if (mode == WindowHandleMode::Closest) {
+ if (auto nativeParent = q_func()->nativeParentWidget()) {
+ if (auto window = nativeParent->windowHandle())
+ return window;
+ }
+ }
+ if (mode == WindowHandleMode::TopLevel || mode == WindowHandleMode::Closest) {
+ if (auto topLevel = q_func()->topLevelWidget()) {
+ if (auto window = topLevel ->windowHandle())
+ return window;
+ }
+ }
+ return nullptr;
+}
+
+QScreen *QWidgetPrivate::associatedScreen() const
+{
+ if (auto window = windowHandle(WindowHandleMode::Closest))
+ return window->screen();
+ return nullptr;
+}
// ### fixme: Qt 6: Remove parameter window from QWidget::create()
@@ -1315,36 +1181,20 @@ void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
<< "Alien?" << !testAttribute(Qt::WA_NativeWindow);
#endif
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ && QT_CONFIG(draganddrop)
- // Unregister the dropsite (if already registered) before we
- // re-create the widget with a native window.
- if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
- && d->extra && d->extra->dropTarget) {
- d->registerDropSite(false);
- }
-#endif
-
d->updateIsOpaque();
setAttribute(Qt::WA_WState_Created); // set created flag
d->create();
- // a real toplevel window needs a backing store
- if (isWindow() && windowType() != Qt::Desktop) {
- d->topData()->backingStoreTracker.destroy();
- d->topData()->backingStoreTracker.create(this);
- }
+ // A real toplevel window needs a paint manager
+ if (isWindow() && windowType() != Qt::Desktop)
+ d->topData()->repaintManager.reset(new QWidgetRepaintManager(this));
d->setModal_sys();
if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
setAttribute(Qt::WA_DropSiteRegistered, true);
-#ifdef QT_EVAL
- extern void qt_eval_init_widget(QWidget *w);
- qt_eval_init_widget(this);
-#endif
-
// need to force the resting of the icon after changing parents
if (testAttribute(Qt::WA_SetWindowIcon))
d->setWindowIcon_sys();
@@ -1587,7 +1437,7 @@ QWidget::~QWidget()
// Remove all shortcuts grabbed by this
// widget, unless application is closing
if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
- qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(0, this, QKeySequence());
#endif
// delete layout while we still are a valid widget
@@ -1611,7 +1461,7 @@ QWidget::~QWidget()
while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
w = w->d_func()->extra->focus_proxy;
QWidget *window = w->window();
- QWExtra *e = window ? window->d_func()->extra : 0;
+ QWExtra *e = window ? window->d_func()->extra.get() : nullptr ;
if (!e || !e->proxyWidget || (w->parentWidget() && w->parentWidget()->d_func()->focus_child == this))
#endif
clearFocus();
@@ -1632,21 +1482,14 @@ QWidget::~QWidget()
// and if that also doesn't work, then give up
}
}
- }
-
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || 0 /* Used to be included in Qt4 for Q_WS_X11 */|| 0 /* Used to be included in Qt4 for Q_WS_MAC */
- else if (!internalWinId() && isVisible()) {
- qApp->d_func()->sendSyntheticEnterLeave(this);
- }
-#endif
- else if (isVisible()) {
+ } else if (isVisible()) {
qApp->d_func()->sendSyntheticEnterLeave(this);
}
- if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
- bs->removeDirtyWidget(this);
+ if (QWidgetRepaintManager *repaintManager = d->maybeRepaintManager()) {
+ repaintManager->removeDirtyWidget(this);
if (testAttribute(Qt::WA_StaticContents))
- bs->removeStaticWidget(this);
+ repaintManager->removeStaticWidget(this);
}
delete d->needsFlush;
@@ -1683,19 +1526,10 @@ QWidget::~QWidget()
d->blockSig = blocked;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // QCocoaView holds a pointer back to this widget. Clear it now
- // to make sure it's not followed later on. The lifetime of the
- // QCocoaView might exceed the lifetime of this widget in cases
- // where Cocoa itself holds references to it.
- extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
- qt_mac_clearCocoaViewQWidgetPointers(this);
-#endif
-
if (!d->children.isEmpty())
d->deleteChildren();
- QApplication::removePostedEvents(this);
+ QCoreApplication::removePostedEvents(this);
QT_TRY {
destroy(); // platform-dependent cleanup
@@ -1738,9 +1572,6 @@ void QWidgetPrivate::setWinId(WId id) // set widget identifier
const WId oldWinId = data.winid;
data.winid = id;
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- hd = id; // X11: hd == ident
-#endif
if (mapper && id && !userDesktopWidget) {
mapper->insert(data.winid, q);
}
@@ -1756,8 +1587,8 @@ void QWidgetPrivate::createTLExtra()
if (!extra)
createExtra();
if (!extra->topextra) {
- QTLWExtra* x = extra->topextra = new QTLWExtra;
- x->icon = 0;
+ extra->topextra = qt_make_unique<QTLWExtra>();
+ QTLWExtra* x = extra->topextra.get();
x->backingStore = 0;
x->sharedPainter = 0;
x->incw = x->inch = 0;
@@ -1771,11 +1602,8 @@ void QWidgetPrivate::createTLExtra()
x->inTopLevelResize = false;
x->embedded = 0;
x->window = 0;
- x->shareContext = 0;
x->initialScreenIndex = -1;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- x->wasMaximized = false;
-#endif
+
#ifdef QWIDGET_EXTRA_DEBUG
static int count = 0;
qDebug() << "tlextra" << ++count;
@@ -1791,15 +1619,11 @@ void QWidgetPrivate::createTLExtra()
void QWidgetPrivate::createExtra()
{
if (!extra) { // if not exists
- extra = new QWExtra;
+ extra = qt_make_unique<QWExtra>();
extra->glContext = 0;
- extra->topextra = 0;
#if QT_CONFIG(graphicsview)
extra->proxyWidget = 0;
#endif
-#ifndef QT_NO_CURSOR
- extra->curs = 0;
-#endif
extra->minw = 0;
extra->minh = 0;
extra->maxw = QWIDGETSIZE_MAX;
@@ -1833,9 +1657,6 @@ void QWidgetPrivate::createSysExtra()
void QWidgetPrivate::deleteExtra()
{
if (extra) { // if exists
-#ifndef QT_NO_CURSOR
- delete extra->curs;
-#endif
deleteSysExtra();
#ifndef QT_NO_STYLE_STYLESHEET
// dereference the stylesheet style
@@ -1845,12 +1666,9 @@ void QWidgetPrivate::deleteExtra()
if (extra->topextra) {
deleteTLSysExtra();
// extra->topextra->backingStore destroyed in QWidgetPrivate::deleteTLSysExtra()
- delete extra->topextra->icon;
- delete extra->topextra;
}
- delete extra;
// extra->xic destroyed in QWidget::destroy()
- extra = 0;
+ extra.reset();
}
}
@@ -1872,13 +1690,11 @@ void QWidgetPrivate::deleteTLSysExtra()
//the qplatformbackingstore may hold a reference to the window, so the backingstore
//needs to be deleted first.
- extra->topextra->backingStoreTracker.destroy();
+ extra->topextra->repaintManager.reset(nullptr);
deleteBackingStore(this);
#ifndef QT_NO_OPENGL
- qDeleteAll(extra->topextra->widgetTextures);
extra->topextra->widgetTextures.clear();
- delete extra->topextra->shareContext;
- extra->topextra->shareContext = 0;
+ extra->topextra->shareContext.reset();
#endif
//the toplevel might have a context with a "qglcontext associated with it. We need to
@@ -1923,7 +1739,7 @@ QRegion QWidgetPrivate::overlappedRegion(const QRect &rect, bool breakAfterFirst
const QRect siblingRect = sibling->d_func()->effectiveRectFor(sibling->data->crect);
if (qRectIntersects(siblingRect, r)) {
- const QWExtra *siblingExtra = sibling->d_func()->extra;
+ const auto &siblingExtra = sibling->d_func()->extra;
if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
&& !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
continue;
@@ -1942,23 +1758,59 @@ QRegion QWidgetPrivate::overlappedRegion(const QRect &rect, bool breakAfterFirst
void QWidgetPrivate::syncBackingStore()
{
- if (paintOnScreen()) {
- repaint_sys(dirty);
+ if (shouldPaintOnScreen()) {
+ paintOnScreen(dirty);
dirty = QRegion();
- } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
- bs->sync();
+ } else if (QWidgetRepaintManager *repaintManager = maybeRepaintManager()) {
+ repaintManager->sync();
}
}
void QWidgetPrivate::syncBackingStore(const QRegion &region)
{
- if (paintOnScreen())
- repaint_sys(region);
- else if (QWidgetBackingStore *bs = maybeBackingStore()) {
- bs->sync(q_func(), region);
+ if (shouldPaintOnScreen())
+ paintOnScreen(region);
+ else if (QWidgetRepaintManager *repaintManager = maybeRepaintManager()) {
+ repaintManager->sync(q_func(), region);
}
}
+void QWidgetPrivate::paintOnScreen(const QRegion &rgn)
+{
+ if (data.in_destructor)
+ return;
+
+ if (shouldDiscardSyncRequest())
+ return;
+
+ Q_Q(QWidget);
+ if (q->testAttribute(Qt::WA_StaticContents)) {
+ if (!extra)
+ createExtra();
+ extra->staticContentsSize = data.crect.size();
+ }
+
+ QPaintEngine *engine = q->paintEngine();
+
+ // QGLWidget does not support partial updates if:
+ // 1) The context is double buffered
+ // 2) The context is single buffered and auto-fill background is enabled.
+ const bool noPartialUpdateSupport = (engine && (engine->type() == QPaintEngine::OpenGL
+ || engine->type() == QPaintEngine::OpenGL2))
+ && (usesDoubleBufferedGLContext || q->autoFillBackground());
+ QRegion toBePainted(noPartialUpdateSupport ? q->rect() : rgn);
+
+ toBePainted &= clipRect();
+ clipToEffectiveMask(toBePainted);
+ if (toBePainted.isEmpty())
+ return; // Nothing to repaint.
+
+ drawWidget(q, toBePainted, QPoint(), QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawPaintOnScreen, 0);
+
+ if (Q_UNLIKELY(q->paintingActive()))
+ qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
+}
+
void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
{
Q_Q(QWidget);
@@ -2007,7 +1859,7 @@ void QWidgetPrivate::propagatePaletteChange()
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
QEvent pc(QEvent::PaletteChange);
- QApplication::sendEvent(q, &pc);
+ QCoreApplication::sendEvent(q, &pc);
for (int i = 0; i < children.size(); ++i) {
QWidget *w = qobject_cast<QWidget*>(children.at(i));
if (w && (!w->testAttribute(Qt::WA_StyleSheet) || useStyleSheetPropagationInWidgetStyles)
@@ -2183,11 +2035,6 @@ void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirt
if (disableSubtractOpaqueSiblings || q->isWindow())
return;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (q->d_func()->isInUnifiedToolbar)
- return;
-#endif
-
QRect clipBoundingRect;
bool dirtyClipBoundingRect = true;
@@ -2291,7 +2138,7 @@ void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const
}
}
-bool QWidgetPrivate::paintOnScreen() const
+bool QWidgetPrivate::shouldPaintOnScreen() const
{
#if defined(QT_NO_BACKINGSTORE)
return true;
@@ -2320,13 +2167,6 @@ void QWidgetPrivate::updateIsOpaque()
#endif // QT_CONFIG(graphicseffect)
Q_Q(QWidget);
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
- setOpaque(false);
- return;
- }
-#endif
-
if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
setOpaque(true);
return;
@@ -2379,20 +2219,9 @@ static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrus
Q_ASSERT(painter);
if (brush.style() == Qt::TexturePattern) {
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // Optimize pattern filling on mac by using HITheme directly
- // when filling with the standard widget background.
- // Defined in qmacstyle_mac.cpp
- extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
- qt_mac_fill_background(painter, rgn, brush);
-#else
- {
- const QRect rect(rgn.boundingRect());
- painter->setClipRegion(rgn);
- painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
- }
-#endif
-
+ const QRect rect(rgn.boundingRect());
+ painter->setClipRegion(rgn);
+ painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
} else if (brush.gradient()
&& (brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode
|| brush.gradient()->coordinateMode() == QGradient::ObjectMode)) {
@@ -2423,7 +2252,7 @@ bool QWidgetPrivate::updateBrushOrigin(QPainter *painter, const QBrush &brush) c
return true;
}
-void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
+void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, DrawWidgetFlags flags) const
{
Q_Q(const QWidget);
@@ -2466,11 +2295,7 @@ void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int
visible widgets.
*/
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- extern QPointer<QWidget> qt_button_down;
-#else
- extern QWidget *qt_button_down;
-#endif
+extern QWidget *qt_button_down;
void QWidgetPrivate::deactivateWidgetCleanup()
{
@@ -2656,7 +2481,7 @@ WId QWidget::effectiveWinId() const
\since 5.0
- \sa winId()
+ \sa winId(), screen()
*/
QWindow *QWidget::windowHandle() const
{
@@ -2664,6 +2489,29 @@ QWindow *QWidget::windowHandle() const
return d->windowHandle();
}
+/*!
+ Returns the screen the widget is on.
+
+ \since 5.14
+
+ \sa windowHandle()
+*/
+QScreen *QWidget::screen() const
+{
+ Q_D(const QWidget);
+ if (auto associatedScreen = d->associatedScreen())
+ return associatedScreen;
+ if (auto topLevel = window()) {
+ if (auto topData = qt_widget_private(topLevel)->topData()) {
+ if (auto initialScreen = QGuiApplicationPrivate::screen_list.value(topData->initialScreenIndex))
+ return initialScreen;
+ }
+ if (auto screenByPos = QGuiApplication::screenAt(topLevel->geometry().center()))
+ return screenByPos;
+ }
+ return QGuiApplication::primaryScreen();
+}
+
#ifndef QT_NO_STYLE_STYLESHEET
/*!
@@ -2811,7 +2659,7 @@ void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate)
#endif
QEvent e(QEvent::StyleChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
#ifndef QT_NO_STYLE_STYLESHEET
// dereference the old stylesheet style
@@ -3029,7 +2877,7 @@ void QWidget::overrideWindowState(Qt::WindowStates newstate)
{
QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
data->window_state = newstate;
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
/*!
@@ -3066,6 +2914,8 @@ void QWidget::setWindowState(Qt::WindowStates newstate)
{
Q_D(QWidget);
Qt::WindowStates oldstate = windowState();
+ if (newstate.testFlag(Qt::WindowMinimized)) // QTBUG-46763
+ newstate.setFlag(Qt::WindowActive, false);
if (oldstate == newstate)
return;
if (isWindow() && !testAttribute(Qt::WA_WState_Created))
@@ -3091,7 +2941,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate)
activateWindow();
QWindowStateChangeEvent e(oldstate);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
/*!
@@ -3139,15 +2989,6 @@ bool QWidget::isFullScreen() const
*/
void QWidget::showFullScreen()
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // If the unified toolbar is enabled, we have to disable it before going fullscreen.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(false);
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- mainLayout->activateUnifiedToolbarAfterFullScreen = true;
- }
-#endif
ensurePolished();
setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
@@ -3175,18 +3016,6 @@ void QWidget::showMaximized()
setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
| Qt::WindowMaximized);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow)
- {
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(true);
- mainLayout->activateUnifiedToolbarAfterFullScreen = false;
- }
- }
-#endif
setVisible(true);
}
@@ -3204,18 +3033,6 @@ void QWidget::showNormal()
setWindowState(windowState() & ~(Qt::WindowMinimized
| Qt::WindowMaximized
| Qt::WindowFullScreen));
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
- QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
- if (mainWindow)
- {
- QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
- if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
- mainWindow->setUnifiedTitleAndToolBarOnMac(true);
- mainLayout->activateUnifiedToolbarAfterFullScreen = false;
- }
- }
-#endif
setVisible(true);
}
@@ -3317,7 +3134,7 @@ void QWidget::insertAction(QAction *before, QAction *action)
apriv->widgets.append(this);
QActionEvent e(QEvent::ActionAdded, action, before);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
/*!
@@ -3355,7 +3172,7 @@ void QWidget::removeAction(QAction *action)
if (d->actions.removeAll(action)) {
QActionEvent e(QEvent::ActionRemoved, action);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
}
@@ -3431,13 +3248,6 @@ void QWidgetPrivate::setEnabled_helper(bool enable)
if (w && !w->testAttribute(attribute))
w->d_func()->setEnabled_helper(enable);
}
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
- // enforce the windows behavior of clearing the cursor on
- // disabled widgets
- qt_x11_enforce_cursor(q);
- }
-#endif
#ifndef QT_NO_CURSOR
if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
// enforce the windows behavior of clearing the cursor on
@@ -3445,9 +3255,6 @@ void QWidgetPrivate::setEnabled_helper(bool enable)
qt_qpa_set_cursor(q, false);
}
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- setEnabled_helper_sys(enable);
-#endif
#ifndef QT_NO_IM
if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
QWidget *focusWidget = effectiveFocusWidget();
@@ -3462,7 +3269,7 @@ void QWidgetPrivate::setEnabled_helper(bool enable)
}
#endif //QT_NO_IM
QEvent e(QEvent::EnabledChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
/*!
@@ -3928,7 +3735,7 @@ QSize QWidget::sizeIncrement() const
QSize QWidget::baseSize() const
{
Q_D(const QWidget);
- return (d->extra != 0 && d->extra->topextra != 0)
+ return (d->extra && d->extra->topextra)
? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
: QSize(0, 0);
}
@@ -4529,7 +4336,7 @@ void QWidget::setForegroundRole(QPalette::ColorRole role)
the "color", "background-color", "selection-color",
"selection-background-color" and "alternate-background-color".
- \sa QApplication::palette(), QWidget::font(), {Qt Style Sheets}
+ \sa QGuiApplication::palette(), QWidget::font(), {Qt Style Sheets}
*/
const QPalette &QWidget::palette() const
{
@@ -4542,13 +4349,7 @@ const QPalette &QWidget::palette() const
) {
data->pal.setCurrentColorGroup(QPalette::Active);
} else {
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
- if (qt_mac_can_clickThrough(this))
- data->pal.setCurrentColorGroup(QPalette::Active);
- else
-#endif
- data->pal.setCurrentColorGroup(QPalette::Inactive);
+ data->pal.setCurrentColorGroup(QPalette::Inactive);
}
return data->pal;
}
@@ -4592,7 +4393,7 @@ QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
)) {
if (QWidget *p = q->parentWidget()) {
if (!p->testAttribute(Qt::WA_StyleSheet) || useStyleSheetPropagationInWidgetStyles) {
- if (!naturalPalette.isCopyOf(QApplication::palette())) {
+ if (!naturalPalette.isCopyOf(QGuiApplication::palette())) {
QPalette inheritedPalette = p->palette();
inheritedPalette.resolve(inheritedMask);
naturalPalette = inheritedPalette.resolve(naturalPalette);
@@ -4811,10 +4612,7 @@ void QWidgetPrivate::updateFont(const QFont &font)
#endif
data.fnt = QFont(font, q);
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- // make sure the font set on this widget is associated with the correct screen
- data.fnt.x11SetScreen(xinfo.screen());
-#endif
+
// Combine new mask with natural mask and propagate to children.
#if QT_CONFIG(graphicsview)
if (!q->parentWidget() && extra && extra->proxyWidget) {
@@ -4858,7 +4656,7 @@ void QWidgetPrivate::updateFont(const QFont &font)
#endif
QEvent e(QEvent::FontChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
@@ -4876,14 +4674,14 @@ void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
}
}
QEvent e(QEvent::LayoutDirectionChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
void QWidgetPrivate::resolveLayoutDirection()
{
Q_Q(const QWidget);
if (!q->testAttribute(Qt::WA_SetLayoutDirection))
- setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
+ setLayoutDirection_helper(q->isWindow() ? QGuiApplication::layoutDirection() : q->parentWidget()->layoutDirection());
}
/*!
@@ -4988,22 +4786,17 @@ QCursor QWidget::cursor() const
void QWidget::setCursor(const QCursor &cursor)
{
Q_D(QWidget);
-// On Mac we must set the cursor even if it is the ArrowCursor.
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
if (cursor.shape() != Qt::ArrowCursor
|| (d->extra && d->extra->curs))
-#endif
{
d->createExtra();
- QCursor *newCursor = new QCursor(cursor);
- delete d->extra->curs;
- d->extra->curs = newCursor;
+ d->extra->curs = qt_make_unique<QCursor>(cursor);
}
setAttribute(Qt::WA_SetCursor);
d->setCursor_sys(cursor);
QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
@@ -5016,16 +4809,14 @@ void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
void QWidget::unsetCursor()
{
Q_D(QWidget);
- if (d->extra) {
- delete d->extra->curs;
- d->extra->curs = 0;
- }
+ if (d->extra)
+ d->extra->curs.reset();
if (!isWindow())
setAttribute(Qt::WA_SetCursor, false);
d->unsetCursor_sys();
QEvent event(QEvent::CursorChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
void QWidgetPrivate::unsetCursor_sys()
@@ -5223,7 +5014,7 @@ void QWidget::render(QPainter *painter, const QPoint &targetOffset,
static void sendResizeEvents(QWidget *target)
{
QResizeEvent e(target->size(), QSize());
- QApplication::sendEvent(target, &e);
+ QCoreApplication::sendEvent(target, &e);
const QObjectList children = target->children();
for (int i = 0; i < children.size(); ++i) {
@@ -5423,11 +5214,9 @@ void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset
Q_ASSERT(!toBePainted.isEmpty());
Q_Q(QWidget);
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
const QTransform originalTransform = painter->worldTransform();
const bool useDeviceCoordinates = originalTransform.isScaling();
if (!useDeviceCoordinates) {
-#endif
// Render via a pixmap.
const QRect rect = toBePainted.boundingRect();
const QSize size = rect.size();
@@ -5450,7 +5239,6 @@ void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset
if (restore)
painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
} else {
// Render via a pixmap in device coordinates (to avoid pixmap scaling).
QTransform transform = originalTransform;
@@ -5481,26 +5269,29 @@ void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset
painter->drawPixmap(deviceRect.topLeft(), pixmap);
painter->setTransform(originalTransform);
}
-#endif
}
-void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
- QPainter *sharedPainter, QWidgetBackingStore *backingStore)
+void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, DrawWidgetFlags flags,
+ QPainter *sharedPainter, QWidgetRepaintManager *repaintManager)
{
if (rgn.isEmpty())
return;
+ Q_Q(QWidget);
+
+ qCInfo(lcWidgetPainting) << "Drawing" << rgn << "of" << q << "at" << offset
+ << "into paint device" << pdev << "with" << flags;
+
const bool asRoot = flags & DrawAsRoot;
- bool onScreen = paintOnScreen();
+ bool onScreen = shouldPaintOnScreen();
- Q_Q(QWidget);
#if QT_CONFIG(graphicseffect)
if (graphicsEffect && graphicsEffect->isEnabled()) {
QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
(source->d_func());
if (!sourced->context) {
- QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
+ QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, repaintManager);
sourced->context = &context;
if (!sharedPainter) {
setSystemClip(pdev->paintEngine(), pdev->devicePixelRatioF(), rgn.translated(offset));
@@ -5524,10 +5315,8 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
}
sourced->context = 0;
- // Native widgets need to be marked dirty on screen so painting will be done in correct context
- // Same check as in the no effects case below.
- if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
- backingStore->markDirtyOnScreen(rgn, q, offset);
+ if (repaintManager)
+ repaintManager->markNeedsFlush(q, rgn, offset);
return;
}
@@ -5554,22 +5343,10 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
q->setAttribute(Qt::WA_WState_InPaintEvent);
//clip away the new area
-#ifndef QT_NO_PAINT_DEBUG
- bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
-#endif
QPaintEngine *paintEngine = pdev->paintEngine();
if (paintEngine) {
setRedirected(pdev, -offset);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // (Alien support) Special case for Mac when redirecting: If the paint device
- // is of the Widget type we need to set WA_WState_InPaintEvent since painting
- // outside the paint event is not supported on QWidgets. The attributeis
- // restored further down.
- if (pdev->devType() == QInternal::Widget)
- static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
-
-#endif
if (sharedPainter)
setSystemClip(pdev->paintEngine(), pdev->devicePixelRatioF(), toBePainted);
else
@@ -5582,7 +5359,7 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
beginBackingStorePainting();
#endif
QPainter p(q);
- paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
+ paintBackground(&p, toBePainted, (asRoot || onScreen) ? (flags | DrawAsRoot) : DrawWidgetFlags());
#ifndef QT_NO_OPENGL
endBackingStorePainting();
#endif
@@ -5617,11 +5394,11 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
// This widget renders into a texture which is composed later. We just need to
// punch a hole in the backingstore, so the texture will be visible.
beginBackingStorePainting();
- if (!q->testAttribute(Qt::WA_AlwaysStackOnTop) && backingStore) {
+ if (!q->testAttribute(Qt::WA_AlwaysStackOnTop) && repaintManager) {
QPainter p(q);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.fillRect(q->rect(), Qt::transparent);
- } else if (!backingStore) {
+ } else if (!repaintManager) {
// We are not drawing to a backingstore: fall back to QImage
QImage img = grabFramebuffer();
// grabFramebuffer() always sets the format to RGB32
@@ -5645,16 +5422,11 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
sendPaintEvent(toBePainted);
}
- // Native widgets need to be marked dirty on screen so painting will be done in correct context
- if (backingStore && !onScreen && !asRoot && (q->internalWinId() || (q->nativeParentWidget() && !q->nativeParentWidget()->isWindow())))
- backingStore->markDirtyOnScreen(toBePainted, q, offset);
+ if (repaintManager)
+ repaintManager->markNeedsFlush(q, toBePainted, offset);
//restore
if (paintEngine) {
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (pdev->devType() == QInternal::Widget)
- static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
-#endif
restoreRedirected();
if (!sharedPainter)
paintEngine->d_func()->systemRect = QRect();
@@ -5670,11 +5442,6 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
if (paintEngine && paintEngine->autoDestruct()) {
delete paintEngine;
}
-
-#ifndef QT_NO_PAINT_DEBUG
- if (flushed)
- QWidgetBackingStore::unflushPaint(q, toBePainted);
-#endif
} else if (q->isWindow()) {
QPaintEngine *engine = pdev->paintEngine();
if (engine) {
@@ -5693,8 +5460,8 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP
}
if (recursive && !children.isEmpty()) {
- paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
- , sharedPainter, backingStore);
+ paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot,
+ sharedPainter, repaintManager);
}
}
@@ -5725,7 +5492,6 @@ void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
if (paintRegion.isEmpty())
return;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
// Use the target's shared painter if set (typically set when doing
@@ -5738,7 +5504,6 @@ void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
setSharedPainter(targetPainter);
}
}
-#endif
// Use the target's redirected device if set and adjust offset and paint
// region accordingly. This is typically the case when people call render
@@ -5765,7 +5530,7 @@ void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
}
// Set backingstore flags.
- int flags = DrawPaintOnScreen | DrawInvisible;
+ DrawWidgetFlags flags = DrawPaintOnScreen | DrawInvisible;
if (renderFlags & QWidget::DrawWindowBackground)
flags |= DrawAsRoot;
@@ -5785,8 +5550,8 @@ void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
}
void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
- const QPoint &offset, int flags
- , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
+ const QPoint &offset, DrawWidgetFlags flags
+ , QPainter *sharedPainter, QWidgetRepaintManager *repaintManager)
{
QWidget *w = 0;
QRect boundingRect;
@@ -5821,8 +5586,8 @@ void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectLis
QRegion wr(rgn);
if (wd->isOpaque)
wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
- paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
- , sharedPainter, backingStore);
+ paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags,
+ sharedPainter, repaintManager);
}
if (w->updatesEnabled()
@@ -5835,7 +5600,7 @@ void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectLis
wRegion.translate(-widgetPos);
if (hasMask)
wRegion &= wd->extra->mask;
- wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
+ wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, repaintManager);
}
}
@@ -5870,7 +5635,7 @@ void QWidgetEffectSourcePrivate::draw(QPainter *painter)
toBePainted &= wd->extra->mask;
wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
- context->sharedPainter, context->backingStore);
+ context->sharedPainter, context->repaintManager);
}
QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
@@ -5932,7 +5697,7 @@ QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *
QGraphicsProxyWidget *QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
{
if (origin) {
- QWExtra *extra = origin->d_func()->extra;
+ const auto &extra = origin->d_func()->extra;
if (extra && extra->proxyWidget)
return extra->proxyWidget;
return nearestGraphicsProxyWidget(origin->parentWidget());
@@ -5977,7 +5742,7 @@ void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
}
}
QEvent e(QEvent::LocaleChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
void QWidget::setLocale(const QLocale &locale)
@@ -6063,13 +5828,7 @@ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widg
{
Q_ASSERT(widget);
-#ifdef QT_EVAL
- extern QString qt_eval_adapt_window_title(const QString &title);
- QString cap = qt_eval_adapt_window_title(title);
-#else
QString cap = title;
-#endif
-
if (cap.isEmpty())
return cap;
@@ -6158,7 +5917,7 @@ void QWidget::setWindowIconText(const QString &iconText)
d->setWindowIconText_helper(iconText);
QEvent e(QEvent::IconTextChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
emit windowIconTextChanged(iconText);
}
@@ -6182,7 +5941,7 @@ void QWidget::setWindowTitle(const QString &title)
d->setWindowTitle_helper(title);
QEvent e(QEvent::WindowTitleChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
emit windowTitleChanged(title);
}
@@ -6220,11 +5979,11 @@ void QWidgetPrivate::setWindowIcon_helper()
// QWidgetWindow to the top level QWidget ensures that the event reaches
// the top level anyhow
if (!q->windowHandle())
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
for (int i = 0; i < children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(children.at(i));
if (w && !w->isWindow())
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
}
@@ -6245,8 +6004,9 @@ void QWidget::setWindowIcon(const QIcon &icon)
d->createTLExtra();
if (!d->extra->topextra->icon)
- d->extra->topextra->icon = new QIcon();
- *d->extra->topextra->icon = icon;
+ d->extra->topextra->icon = qt_make_unique<QIcon>(icon);
+ else
+ *d->extra->topextra->icon = icon;
d->setWindowIcon_sys();
d->setWindowIcon_helper();
@@ -6460,7 +6220,7 @@ void QWidget::setFocusProxy(QWidget * w)
QWidget *QWidget::focusProxy() const
{
Q_D(const QWidget);
- return d->extra ? (QWidget *)d->extra->focus_proxy : nullptr;
+ return d->extra ? d->extra->focus_proxy.data() : nullptr;
}
@@ -6483,7 +6243,7 @@ bool QWidget::hasFocus() const
w = w->d_func()->extra->focus_proxy;
#if QT_CONFIG(graphicsview)
if (QWidget *window = w->window()) {
- QWExtra *e = window->d_func()->extra;
+ const auto &e = window->d_func()->extra;
if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
return true;
}
@@ -6535,16 +6295,12 @@ void QWidget::setFocus(Qt::FocusReason reason)
if (!f)
f = this;
- if (QApplication::focusWidget() == f
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- && GetFocus() == f->internalWinId()
-#endif
- )
+ if (QApplication::focusWidget() == f)
return;
#if QT_CONFIG(graphicsview)
QWidget *previousProxyFocus = 0;
- if (QWExtra *topData = window()->d_func()->extra) {
+ if (const auto &topData = window()->d_func()->extra) {
if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
if (previousProxyFocus && previousProxyFocus->focusProxy())
@@ -6557,7 +6313,7 @@ void QWidget::setFocus(Qt::FocusReason reason)
#if QT_CONFIG(graphicsview)
// Update proxy state
- if (QWExtra *topData = window()->d_func()->extra) {
+ if (const auto &topData = window()->d_func()->extra) {
if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
f->d_func()->updateFocusChild();
topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
@@ -6577,7 +6333,7 @@ void QWidget::setFocus(Qt::FocusReason reason)
if (reason != Qt::NoFocusReason) {
QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, reason);
- QApplication::sendEvent(prev, &focusAboutToChange);
+ QCoreApplication::sendEvent(prev, &focusAboutToChange);
}
}
@@ -6598,29 +6354,29 @@ void QWidget::setFocus(Qt::FocusReason reason)
}
#endif
#if QT_CONFIG(graphicsview)
- if (QWExtra *topData = window()->d_func()->extra) {
+ if (const auto &topData = window()->d_func()->extra) {
if (topData->proxyWidget) {
if (previousProxyFocus && previousProxyFocus != f) {
// Send event to self
QFocusEvent event(QEvent::FocusOut, reason);
QPointer<QWidget> that = previousProxyFocus;
- QApplication::sendEvent(previousProxyFocus, &event);
+ QCoreApplication::sendEvent(previousProxyFocus, &event);
if (that)
- QApplication::sendEvent(that->style(), &event);
+ QCoreApplication::sendEvent(that->style(), &event);
}
if (!isHidden()) {
#if QT_CONFIG(graphicsview)
// Update proxy state
- if (QWExtra *topData = window()->d_func()->extra)
+ if (const auto &topData = window()->d_func()->extra)
if (topData->proxyWidget && topData->proxyWidget->hasFocus())
topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
#endif
// Send event to self
QFocusEvent event(QEvent::FocusIn, reason);
QPointer<QWidget> that = f;
- QApplication::sendEvent(f, &event);
+ QCoreApplication::sendEvent(f, &event);
if (that)
- QApplication::sendEvent(that->style(), &event);
+ QCoreApplication::sendEvent(that->style(), &event);
}
}
}
@@ -6727,7 +6483,7 @@ void QWidget::clearFocus()
QGuiApplication::inputMethod()->commit();
QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
- QApplication::sendEvent(this, &focusAboutToChange);
+ QCoreApplication::sendEvent(this, &focusAboutToChange);
}
QWidget *w = this;
@@ -6748,7 +6504,7 @@ void QWidget::clearFocus()
}
#if QT_CONFIG(graphicsview)
- QWExtra *topData = d_func()->extra;
+ const auto &topData = d_func()->extra;
if (topData && topData->proxyWidget)
topData->proxyWidget->clearFocus();
#endif
@@ -6756,17 +6512,10 @@ void QWidget::clearFocus()
if (hasFocus()) {
// Update proxy state
QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
- SetFocus(0);
- else
-#endif
- {
#ifndef QT_NO_ACCESSIBILITY
- QAccessibleEvent event(this, QAccessible::Focus);
- QAccessible::updateAccessibility(&event);
+ QAccessibleEvent event(this, QAccessible::Focus);
+ QAccessible::updateAccessibility(&event);
#endif
- }
}
}
@@ -6914,7 +6663,7 @@ bool QWidget::isActiveWindow() const
return true;
#if QT_CONFIG(graphicsview)
- if (QWExtra *tlwExtra = tlw->d_func()->extra) {
+ if (const auto &tlwExtra = tlw->d_func()->extra) {
if (isVisible() && tlwExtra->proxyWidget)
return tlwExtra->proxyWidget->isActiveWindow();
}
@@ -7374,11 +7123,11 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
if (isMove) {
QMoveEvent e(q->pos(), oldPos);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
if (isResize) {
QResizeEvent e(r.size(), olds);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
if (q->windowHandle())
q->update();
}
@@ -7410,18 +7159,6 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
*/
QByteArray QWidget::saveGeometry() const
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // We check if the window was maximized during this invocation. If so, we need to record the
- // starting position as 0,0.
- Q_D(const QWidget);
- QRect newFramePosition = frameGeometry();
- QRect newNormalPosition = normalGeometry();
- if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
- // Change the starting position
- newFramePosition.moveTo(0, 0);
- newNormalPosition.moveTo(0, 0);
- }
-#endif
QByteArray array;
QDataStream stream(&array, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_4_0);
@@ -7436,13 +7173,8 @@ QByteArray QWidget::saveGeometry() const
stream << magicNumber
<< majorVersion
<< minorVersion
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- << newFramePosition
- << newNormalPosition
-#else
<< frameGeometry()
<< normalGeometry()
-#endif
<< qint32(screenNumber)
<< quint8(windowState() & Qt::WindowMaximized)
<< quint8(windowState() & Qt::WindowFullScreen)
@@ -7562,11 +7294,6 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
// that would make the window "lost". This happens if:
// - The restored geometry is completely oustside the available geometry
// - The title bar is outside the available geometry.
- // - (Mac only) The window is higher than the available geometry. It must
- // be possible to bring the size grip on screen by moving the window.
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
-#endif
checkRestoredGeometry(availableGeometry, &restoredGeometry, frameHeight);
checkRestoredGeometry(availableGeometry, &restoredNormalGeometry, frameHeight);
@@ -7623,7 +7350,7 @@ bool QWidget::restoreGeometry(const QByteArray &geometry)
Changing the margins will trigger a resizeEvent().
- \sa contentsRect(), getContentsMargins()
+ \sa contentsRect(), contentsMargins()
*/
void QWidget::setContentsMargins(int left, int top, int right, int bottom)
{
@@ -7653,7 +7380,7 @@ void QWidget::setContentsMargins(int left, int top, int right, int bottom)
Changing the margins will trigger a resizeEvent().
- \sa contentsRect(), getContentsMargins()
+ \sa contentsRect(), contentsMargins()
*/
void QWidget::setContentsMargins(const QMargins &margins)
{
@@ -7673,16 +7400,20 @@ void QWidgetPrivate::updateContentsRect()
if (q->isVisible()) {
q->update();
QResizeEvent e(q->data->crect.size(), q->data->crect.size());
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
} else {
q->setAttribute(Qt::WA_PendingResizeEvent, true);
}
QEvent e(QEvent::ContentsRectChange);
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
}
+#if QT_DEPRECATED_SINCE(5, 14)
/*!
+ \obsolete
+ Use contentsMargins().
+
Returns the widget's contents margins for \a left, \a top, \a
right, and \a bottom.
@@ -7700,6 +7431,7 @@ void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) c
if (bottom)
*bottom = m.bottom();
}
+#endif
// FIXME: Move to qmargins.h for next minor Qt release
QMargins operator|(const QMargins &m1, const QMargins &m2)
@@ -7713,7 +7445,7 @@ QMargins operator|(const QMargins &m1, const QMargins &m2)
\brief The contentsMargins function returns the widget's contents margins.
- \sa getContentsMargins(), setContentsMargins(), contentsRect()
+ \sa setContentsMargins(), contentsRect()
*/
QMargins QWidget::contentsMargins() const
{
@@ -7726,7 +7458,7 @@ QMargins QWidget::contentsMargins() const
/*!
Returns the area inside the widget's margins.
- \sa setContentsMargins(), getContentsMargins()
+ \sa setContentsMargins(), contentsMargins()
*/
QRect QWidget::contentsRect() const
{
@@ -7939,7 +7671,7 @@ void QWidget::show()
else if (defaultState == Qt::WindowMaximized)
showMaximized();
else
- setVisible(true); // FIXME: Why not showNormal(), like QWindow::show()?
+ setVisible(true); // Don't call showNormal() as not to clobber Qt::Window(Max/Min)imized
}
/*! \internal
@@ -7975,13 +7707,13 @@ void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disable
if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
q->setAttribute(Qt::WA_PendingMoveEvent, false);
}
if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
QResizeEvent e(data.crect.size(), QSize());
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
q->setAttribute(Qt::WA_PendingResizeEvent, false);
}
@@ -8081,17 +7813,9 @@ void QWidgetPrivate::show_helper()
Q_UNUSED(isEmbedded);
#endif
- // On Windows, show the popup now so that our own focus handling
- // stores the correct old focus widget even if it's stolen in the
- // showevent
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || 0 /* Used to be included in Qt4 for Q_WS_MAC */
- if (!isEmbedded && q->windowType() == Qt::Popup)
- qApp->d_func()->openPopup(q);
-#endif
-
// send the show event before showing the window
QShowEvent showEvent;
- QApplication::sendEvent(q, &showEvent);
+ QCoreApplication::sendEvent(q, &showEvent);
show_sys();
@@ -8114,7 +7838,7 @@ void QWidgetPrivate::show_helper()
// is spinnning; otherwise it might not show up on particular platforms.
// This makes QSplashScreen behave the same on all platforms.
if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
- QApplication::processEvents();
+ QCoreApplication::processEvents();
data.in_show = false; // reset qws optimization
}
@@ -8123,7 +7847,7 @@ void QWidgetPrivate::show_sys()
{
Q_Q(QWidget);
- QWidgetWindow *window = windowHandle();
+ auto window = qobject_cast<QWidgetWindow *>(windowHandle());
if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
invalidateBackingStore(q->rect());
@@ -8140,9 +7864,9 @@ void QWidgetPrivate::show_sys()
}
if (renderToTexture && !q->isWindow())
- QApplication::postEvent(q->parentWidget(), new QUpdateLaterEvent(q->geometry()));
+ QCoreApplication::postEvent(q->parentWidget(), new QUpdateLaterEvent(q->geometry()));
else
- QApplication::postEvent(q, new QUpdateLaterEvent(q->rect()));
+ QCoreApplication::postEvent(q, new QUpdateLaterEvent(q->rect()));
if ((!q->isWindow() && !q->testAttribute(Qt::WA_NativeWindow))
|| q->testAttribute(Qt::WA_OutsideWSRange)) {
@@ -8213,12 +7937,6 @@ void QWidgetPrivate::hide_helper()
if (!isEmbedded && (q->windowType() == Qt::Popup))
qApp->d_func()->closePopup(q);
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
- && !q->parentWidget()->isHidden() && q->isActiveWindow())
- q->parentWidget()->activateWindow(); // Activate parent
-#endif
-
q->setAttribute(Qt::WA_Mapped, false);
hide_sys();
@@ -8230,7 +7948,7 @@ void QWidgetPrivate::hide_helper()
}
QHideEvent hideEvent;
- QApplication::sendEvent(q, &hideEvent);
+ QCoreApplication::sendEvent(q, &hideEvent);
hideChildren(false);
// next bit tries to move the focus if the focus widget is now
@@ -8247,8 +7965,8 @@ void QWidgetPrivate::hide_helper()
}
}
- if (QWidgetBackingStore *bs = maybeBackingStore())
- bs->removeDirtyWidget(q);
+ if (QWidgetRepaintManager *repaintManager = maybeRepaintManager())
+ repaintManager->removeDirtyWidget(q);
#ifndef QT_NO_ACCESSIBILITY
if (wasVisible) {
@@ -8262,7 +7980,7 @@ void QWidgetPrivate::hide_sys()
{
Q_Q(QWidget);
- QWidgetWindow *window = windowHandle();
+ auto window = qobject_cast<QWidgetWindow *>(windowHandle());
if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
q->setAttribute(Qt::WA_Mapped, false);
@@ -8401,18 +8119,8 @@ void QWidgetPrivate::setVisible(bool visible)
}
QEvent showToParentEvent(QEvent::ShowToParent);
- QApplication::sendEvent(q, &showToParentEvent);
+ QCoreApplication::sendEvent(q, &showToParentEvent);
} else { // hide
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- // reset WS_DISABLED style in a Blocked window
- if(isWindow() && testAttribute(Qt::WA_WState_Created)
- && QApplicationPrivate::isBlockedByModal(this))
- {
- LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
- dwStyle &= ~WS_DISABLED;
- SetWindowLong(winId(), GWL_STYLE, dwStyle);
- }
-#endif
if (QApplicationPrivate::hidden_focus_widget == q)
QApplicationPrivate::hidden_focus_widget = 0;
@@ -8432,11 +8140,11 @@ void QWidgetPrivate::setVisible(bool visible)
if (q->parentWidget()->d_func()->layout)
q->parentWidget()->d_func()->layout->invalidate();
else if (q->parentWidget()->isVisible())
- QApplication::postEvent(q->parentWidget(), new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(q->parentWidget(), new QEvent(QEvent::LayoutRequest));
}
QEvent hideToParentEvent(QEvent::HideToParent);
- QApplication::sendEvent(q, &hideToParentEvent);
+ QCoreApplication::sendEvent(q, &hideToParentEvent);
}
}
@@ -8487,23 +8195,7 @@ void QWidgetPrivate::hideChildren(bool spontaneous)
QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
continue;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
- // When hiding a widget we need to make sure that no mouse_down events are active, because
- // the mouse_up event will never be received by a hidden widget or one of its descendants.
- // The solution is simple, before going through with this we check if there are any mouse_down events in
- // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
- // then we continue.
- // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
- // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
- // mouse release event. There are two ways to interpret this:
- // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
- // might be waiting for a release event that will never arrive.
- // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
- // supposed to trigger because it is not visible.
- if(widget == qt_button_down)
- qt_button_down = 0;
-#endif
+
if (spontaneous)
widget->setAttribute(Qt::WA_Mapped, false);
else
@@ -8513,7 +8205,7 @@ void QWidgetPrivate::hideChildren(bool spontaneous)
if (spontaneous) {
QApplication::sendSpontaneousEvent(widget, &e);
} else {
- QApplication::sendEvent(widget, &e);
+ QCoreApplication::sendEvent(widget, &e);
if (widget->internalWinId()
&& widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
// hide_sys() on an ancestor won't have any affect on this
@@ -8548,7 +8240,7 @@ bool QWidgetPrivate::close_helper(CloseMode mode)
if (mode == CloseWithSpontaneousEvent)
QApplication::sendSpontaneousEvent(q, &e);
else
- QApplication::sendEvent(q, &e);
+ QCoreApplication::sendEvent(q, &e);
if (!that.isNull() && !e.isAccepted()) {
data.is_closing = 0;
return false;
@@ -8738,11 +8430,9 @@ QSize QWidgetPrivate::adjustedSize() const
s.setWidth(qMax(s.width(), 200));
if (exp & Qt::Vertical)
s.setHeight(qMax(s.height(), 100));
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- QRect screen = QDesktopWidgetPrivate::screenGeometry(q->x11Info().screen());
-#else // all others
+
QRect screen = QDesktopWidgetPrivate::screenGeometry(q->pos());
-#endif
+
s.setWidth(qMin(s.width(), screen.width()*2/3));
s.setHeight(qMin(s.height(), screen.height()*2/3));
@@ -8867,26 +8557,6 @@ bool QWidget::isAncestorOf(const QWidget *child) const
return false;
}
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
-inline void setDisabledStyle(QWidget *w, bool setStyle)
-{
- // set/reset WS_DISABLED style.
- if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
- LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
- LONG newStyle = dwStyle;
- if (setStyle)
- newStyle |= WS_DISABLED;
- else
- newStyle &= ~WS_DISABLED;
- if (newStyle != dwStyle) {
- SetWindowLong(w->winId(), GWL_STYLE, newStyle);
- // we might need to repaint in some situations (eg. menu)
- w->repaint();
- }
- }
-}
-#endif
-
/*****************************************************************************
QWidget event handling
*****************************************************************************/
@@ -9063,7 +8733,7 @@ bool QWidget::event(QEvent *event)
setAttribute(Qt::WA_WState_Polished);
if (!QApplication::font(this).isCopyOf(QApplication::font()))
d->resolveFont();
- if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
+ if (!QApplication::palette(this).isCopyOf(QGuiApplication::palette()))
d->resolvePalette();
}
break;
@@ -9087,7 +8757,7 @@ bool QWidget::event(QEvent *event)
#if QT_CONFIG(statustip)
if (d->statusTip.size()) {
QStatusTipEvent tip(d->statusTip);
- QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
+ QCoreApplication::sendEvent(const_cast<QWidget *>(this), &tip);
}
#endif
enterEvent(event);
@@ -9098,7 +8768,7 @@ bool QWidget::event(QEvent *event)
if (d->statusTip.size()) {
QString empty;
QStatusTipEvent tip(empty);
- QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
+ QCoreApplication::sendEvent(const_cast<QWidget *>(this), &tip);
}
#endif
leaveEvent(event);
@@ -9249,7 +8919,7 @@ bool QWidget::event(QEvent *event)
for (int i = 0; i < childList.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(childList.at(i));
if (w && w->isVisible() && !w->isWindow())
- QApplication::sendEvent(w, event);
+ QCoreApplication::sendEvent(w, event);
}
break; }
@@ -9260,7 +8930,7 @@ bool QWidget::event(QEvent *event)
for (int i = 0; i < childList.size(); ++i) {
QObject *o = childList.at(i);
if (o)
- QApplication::sendEvent(o, event);
+ QCoreApplication::sendEvent(o, event);
}
}
update();
@@ -9299,13 +8969,10 @@ bool QWidget::event(QEvent *event)
QWidget *w = static_cast<QWidget *>(o);
// do not forward the event to child windows; QApplication does this for us
if (!w->isWindow())
- QApplication::sendEvent(w, event);
+ QCoreApplication::sendEvent(w, event);
}
}
}
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
-#endif
break;
#ifndef QT_NO_TOOLTIP
case QEvent::ToolTip:
@@ -9330,9 +8997,6 @@ bool QWidget::event(QEvent *event)
case QEvent::EmbeddingControl:
d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
data->fstrut_dirty = false;
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || 0 /* Used to be included in Qt4 for Q_WS_X11 */
- d->topData()->embedded = 1;
-#endif
break;
#ifndef QT_NO_ACTION
case QEvent::ActionAdded:
@@ -9351,15 +9015,10 @@ bool QWidget::event(QEvent *event)
for (int i = 0; i < childList.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(childList.at(i));
if (w && w->isVisible() && !w->isWindow())
- QApplication::sendEvent(w, event);
+ QCoreApplication::sendEvent(w, event);
}
break;
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- case QEvent::MacGLWindowChange:
- d->needWindowChange = false;
- break;
-#endif
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
@@ -9454,8 +9113,8 @@ void QWidget::changeEvent(QEvent * event)
break;
case QEvent::ThemeChange:
- if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
- && qApp && !QApplication::closingDown()) {
+ if (QGuiApplication::desktopSettingsAware() && windowType() != Qt::Desktop
+ && qApp && !QCoreApplication::closingDown()) {
if (testAttribute(Qt::WA_WState_Polished))
QApplication::style()->unpolish(this);
if (testAttribute(Qt::WA_WState_Polished))
@@ -9471,11 +9130,6 @@ void QWidget::changeEvent(QEvent * event)
case QEvent::MacSizeChange:
updateGeometry();
break;
-#elif 0 // Used to be included in Qt4 for Q_WS_MAC
- case QEvent::ToolTipChange:
- case QEvent::MouseTrackingChange:
- qt_mac_update_mouseTracking(this);
- break;
#endif
default:
@@ -9568,9 +9222,11 @@ void QWidget::mouseReleaseEvent(QMouseEvent *event)
The default implementation calls mousePressEvent().
\note The widget will also receive mouse press and mouse release
- events in addition to the double click event. It is up to the
- developer to ensure that the application interprets these events
- correctly.
+ events in addition to the double click event. And if another widget
+ that overlaps this widget disappears in response to press or
+ release events, then this widget will only receive the double click
+ event. It is up to the developer to ensure that the application
+ interprets these events correctly.
\sa mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(),
event(), QMouseEvent
@@ -10182,7 +9838,11 @@ void QWidget::hideEvent(QHideEvent *)
\endtable
*/
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+bool QWidget::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
+#else
bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
+#endif
{
Q_UNUSED(eventType);
Q_UNUSED(message);
@@ -10397,7 +10057,7 @@ void QWidget::setSizePolicy(QSizePolicy policy)
d->size_policy = policy;
#if QT_CONFIG(graphicsview)
- if (QWExtra *extra = d->extra) {
+ if (const auto &extra = d->extra) {
if (extra->proxyWidget)
extra->proxyWidget->setSizePolicy(policy);
}
@@ -10518,7 +10178,7 @@ void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
if (parent->d_func()->layout)
parent->d_func()->layout->invalidate();
else if (parent->isVisible())
- QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
+ QCoreApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
}
}
}
@@ -10672,7 +10332,7 @@ static void sendWindowChangeToTextureChildrenRecursively(QWidget *widget)
QWidgetPrivate *d = QWidgetPrivate::get(widget);
if (d->renderToTexture) {
QEvent e(QEvent::WindowChangeInternal);
- QApplication::sendEvent(widget, &e);
+ QCoreApplication::sendEvent(widget, &e);
}
for (int i = 0; i < d->children.size(); ++i) {
@@ -10692,6 +10352,22 @@ static void sendWindowChangeToTextureChildrenRecursively(QWidget *widget)
void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
{
Q_D(QWidget);
+ Q_ASSERT_X(this != parent, Q_FUNC_INFO, "Cannot parent a QWidget to itself");
+#ifdef QT_DEBUG
+ const auto checkForParentChildLoops = qScopeGuard([&](){
+ int depth = 0;
+ auto p = parentWidget();
+ while (p) {
+ if (++depth == QObjectPrivate::CheckForParentChildLoopsWarnDepth) {
+ qWarning("QWidget %p (class: '%s', object name: '%s') may have a loop in its parent-child chain; "
+ "this is undefined behavior",
+ this, metaObject()->className(), qPrintable(objectName()));
+ }
+ p = p->parentWidget();
+ }
+ });
+#endif
+
bool resized = testAttribute(Qt::WA_Resized);
bool wasCreated = testAttribute(Qt::WA_WState_Created);
QWidget *oldtlw = window();
@@ -10705,7 +10381,7 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
if (newParent && parent && !desktopWidget) {
- if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings))
+ if (testAttribute(Qt::WA_NativeWindow) && !QCoreApplication::testAttribute(Qt::AA_DontCreateNativeWidgetSiblings))
parent->d_func()->enforceNativeChildren();
else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
setAttribute(Qt::WA_NativeWindow);
@@ -10718,22 +10394,14 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
}
if (newParent) {
QEvent e(QEvent::ParentAboutToChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
}
if (newParent && isAncestorOf(focusWidget()))
focusWidget()->clearFocus();
- QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
- QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
-
d->setParent_sys(parent, f);
- QTLWExtra *topExtra = window()->d_func()->maybeTopData();
- QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
- if (oldBsTracker && oldBsTracker != bsTracker)
- oldBsTracker->unregisterWidgetSubtree(this);
-
if (desktopWidget)
parent = 0;
@@ -10744,12 +10412,12 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
}
#endif
- if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
+ if (QWidgetRepaintManager *oldPaintManager = oldtlw->d_func()->maybeRepaintManager()) {
if (newParent)
- oldBs->removeDirtyWidget(this);
+ oldPaintManager->removeDirtyWidget(this);
// Move the widget and all its static children from
// the old backing store to the new one.
- oldBs->moveStaticWidgets(this);
+ oldPaintManager->moveStaticWidgets(this);
}
// ### fixme: Qt 6: Remove AA_ImmediateWidgetCreation.
@@ -10775,7 +10443,7 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
// platforms).
if (newParent
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || defined(QT_OPENGL_ES)
+#if defined(QT_OPENGL_ES)
|| (f & Qt::MSWindowsOwnDC)
#endif
) {
@@ -10791,25 +10459,16 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
// send and post remaining QObject events
if (parent && d->sendChildEvents) {
QChildEvent e(QEvent::ChildAdded, this);
- QApplication::sendEvent(parent, &e);
+ QCoreApplication::sendEvent(parent, &e);
}
-//### already hidden above ---> must probably do something smart on the mac
-// #if 0 // Used to be included in Qt4 for Q_WS_MAC
-// extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
-// if(!qt_mac_is_macdrawer(q)) //special case
-// q->setAttribute(Qt::WA_WState_Hidden);
-// #else
-// q->setAttribute(Qt::WA_WState_Hidden);
-//#endif
-
if (parent && d->sendChildEvents && d->polished) {
QChildEvent e(QEvent::ChildPolished, this);
QCoreApplication::sendEvent(parent, &e);
}
QEvent e(QEvent::ParentChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
#ifndef QT_NO_OPENGL
//renderToTexture widgets also need to know when their top-level window changes
@@ -11103,7 +10762,7 @@ void QWidgetPrivate::repaint(T r)
QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
- tlwExtra->backingStoreTracker->markDirty(r, q, QWidgetBackingStore::UpdateNow);
+ tlwExtra->repaintManager->markDirty(r, q, QWidgetRepaintManager::UpdateNow);
}
/*!
@@ -11172,13 +10831,13 @@ void QWidgetPrivate::update(T r)
return;
if (q->testAttribute(Qt::WA_WState_InPaintEvent)) {
- QApplication::postEvent(q, new QUpdateLaterEvent(clipped));
+ QCoreApplication::postEvent(q, new QUpdateLaterEvent(clipped));
return;
}
QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
- tlwExtra->backingStoreTracker->markDirty(clipped, q);
+ tlwExtra->repaintManager->markDirty(clipped, q);
}
/*!
@@ -11209,7 +10868,7 @@ void QWidgetPrivate::macUpdateSizeAttribute()
{
Q_Q(QWidget);
QEvent event(QEvent::MacSizeChange);
- QApplication::sendEvent(q, &event);
+ QCoreApplication::sendEvent(q, &event);
for (int i = 0; i < children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(children.at(i));
if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
@@ -11265,7 +10924,7 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
setAttribute(Qt::WA_DropSiteRegistered, false);
QEvent e(QEvent::AcceptDropsChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
break;
}
case Qt::WA_DropSiteRegistered: {
@@ -11284,23 +10943,6 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
case Qt::WA_NoChildEventsFromChildren:
d->receiveChildEvents = !on;
break;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- case Qt::WA_MacOpaqueSizeGrip:
- d->macUpdateOpaqueSizeGrip();
- break;
- case Qt::WA_MacShowFocusRect:
- if (hasFocus()) {
- clearFocus();
- setFocus();
- }
- break;
- case Qt::WA_Hover:
- qt_mac_update_mouseTracking(this);
- break;
- case Qt::WA_MacAlwaysShowToolWindow:
- d->macUpdateHideOnSuspend();
- break;
-#endif
case Qt::WA_MacNormalSize:
case Qt::WA_MacSmallSize:
case Qt::WA_MacMiniSize:
@@ -11348,11 +10990,11 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
break;
case Qt::WA_MouseTracking: {
QEvent e(QEvent::MouseTrackingChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
break; }
case Qt::WA_TabletTracking: {
QEvent e(QEvent::TabletTrackingChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
break; }
case Qt::WA_NativeWindow: {
d->createTLExtra();
@@ -11365,7 +11007,7 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
QGuiApplication::inputMethod()->commit();
QGuiApplication::inputMethod()->update(Qt::ImEnabled);
}
- if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget())
+ if (!QCoreApplication::testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget())
parentWidget()->d_func()->enforceNativeChildren();
if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
d->createWinId();
@@ -11378,15 +11020,6 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
}
case Qt::WA_PaintOnScreen:
d->updateIsOpaque();
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || 0 /* Used to be included in Qt4 for Q_WS_X11 */ || 0 /* Used to be included in Qt4 for Q_WS_MAC */
- // Recreate the widget if it's already created as an alien widget and
- // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
- // So must their children.
- if (on) {
- setAttribute(Qt::WA_NativeWindow);
- d->enforceNativeChildren();
- }
-#endif
Q_FALLTHROUGH();
case Qt::WA_OpaquePaintEvent:
d->updateIsOpaque();
@@ -11398,9 +11031,6 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
d->updateSystemBackground();
break;
case Qt::WA_TransparentForMouseEvents:
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- d->macUpdateIgnoreMouseEvents();
-#endif
break;
case Qt::WA_InputMethodEnabled: {
#ifndef QT_NO_IM
@@ -11417,20 +11047,6 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
d->resolveFont();
d->resolveLocale();
break;
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- case Qt::WA_NoX11EventCompression:
- if (!d->extra)
- d->createExtra();
- d->extra->compress_events = on;
- break;
- case Qt::WA_X11OpenGLOverlay:
- d->updateIsOpaque();
- break;
- case Qt::WA_X11DoNotAcceptFocus:
- if (testAttribute(Qt::WA_WState_Created))
- d->updateX11AcceptFocus();
- break;
-#endif
case Qt::WA_DontShowOnScreen: {
if (on && isVisible()) {
// Make sure we keep the current state and only hide the widget
@@ -11459,11 +11075,11 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
break;
case Qt::WA_StaticContents:
- if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
+ if (QWidgetRepaintManager *repaintManager = d->maybeRepaintManager()) {
if (on)
- bs->addStaticWidget(this);
+ repaintManager->addStaticWidget(this);
else
- bs->removeStaticWidget(this);
+ repaintManager->removeStaticWidget(this);
}
break;
case Qt::WA_TranslucentBackground:
@@ -11473,10 +11089,6 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
break;
case Qt::WA_AcceptTouchEvents:
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ || 0 /* Used to be included in Qt4 for Q_WS_MAC */
- if (on)
- d->registerTouchWindow();
-#endif
break;
default:
break;
@@ -11600,7 +11212,7 @@ void QWidget::setWindowModified(bool mod)
d->setWindowModified_helper();
QEvent e(QEvent::ModifiedChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
void QWidgetPrivate::setWindowModified_helper()
@@ -11646,7 +11258,7 @@ void QWidget::setToolTip(const QString &s)
d->toolTip = s;
QEvent event(QEvent::ToolTipChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
QString QWidget::toolTip() const
@@ -11823,7 +11435,7 @@ int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
if (key.isEmpty())
return 0;
setAttribute(Qt::WA_GrabbedShortcut);
- return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
+ return QGuiApplicationPrivate::instance()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
}
/*!
@@ -11845,7 +11457,7 @@ void QWidget::releaseShortcut(int id)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.removeShortcut(id, this, 0);
}
/*!
@@ -11864,7 +11476,7 @@ void QWidget::setShortcutEnabled(int id, bool enable)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
}
/*!
@@ -11879,7 +11491,7 @@ void QWidget::setShortcutAutoRepeat(int id, bool enable)
{
Q_ASSERT(qApp);
if (id)
- qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
+ QGuiApplicationPrivate::instance()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
}
#endif // QT_NO_SHORTCUT
@@ -11934,7 +11546,7 @@ void QWidget::raise()
QWindowContainer::parentWasRaised(this);
QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
void QWidgetPrivate::raise_sys()
@@ -11984,7 +11596,7 @@ void QWidget::lower()
QWindowContainer::parentWasLowered(this);
QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
void QWidgetPrivate::lower_sys()
@@ -12031,7 +11643,7 @@ void QWidget::stackUnder(QWidget* w)
d->stackUnder_sys(w);
QEvent e(QEvent::ZOrderChange);
- QApplication::sendEvent(this, &e);
+ QCoreApplication::sendEvent(this, &e);
}
void QWidgetPrivate::stackUnder_sys(QWidget*)
@@ -12092,10 +11704,8 @@ QRect QWidgetPrivate::frameStrut() const
}
if (data.fstrut_dirty
-#if 1 // Used to be excluded in Qt4 for Q_WS_WIN
// ### Fix properly for 4.3
&& q->isVisible()
-#endif
&& q->testAttribute(Qt::WA_WState_Created))
const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
@@ -12268,14 +11878,14 @@ void QWidget::setBackingStore(QBackingStore *store)
deleteBackingStore(d);
topData->backingStore = store;
- QWidgetBackingStore *bs = d->maybeBackingStore();
- if (!bs)
+ QWidgetRepaintManager *repaintManager = d->maybeRepaintManager();
+ if (!repaintManager)
return;
if (isTopLevel()) {
- if (bs->store != oldStore && bs->store != store)
- delete bs->store;
- bs->store = store;
+ if (repaintManager->backingStore() != oldStore && repaintManager->backingStore() != store)
+ delete repaintManager->backingStore();
+ repaintManager->setBackingStore(store);
}
}
@@ -12291,9 +11901,8 @@ QBackingStore *QWidget::backingStore() const
if (extra && extra->backingStore)
return extra->backingStore;
- QWidgetBackingStore *bs = d->maybeBackingStore();
-
- return bs ? bs->store : 0;
+ QWidgetRepaintManager *repaintManager = d->maybeRepaintManager();
+ return repaintManager ? repaintManager->backingStore() : nullptr;
}
void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
@@ -12366,19 +11975,18 @@ QOpenGLContext *QWidgetPrivate::shareContext() const
#ifdef QT_NO_OPENGL
return 0;
#else
- if (Q_UNLIKELY(!extra || !extra->topextra || !extra->topextra->window))
+ if (!extra || !extra->topextra || !extra->topextra->window)
return 0;
- QWidgetPrivate *that = const_cast<QWidgetPrivate *>(this);
if (!extra->topextra->shareContext) {
- QOpenGLContext *ctx = new QOpenGLContext;
+ auto ctx = qt_make_unique<QOpenGLContext>();
ctx->setShareContext(qt_gl_global_share_context());
ctx->setFormat(extra->topextra->window->format());
ctx->setScreen(extra->topextra->window->screen());
ctx->create();
- that->extra->topextra->shareContext = ctx;
+ extra->topextra->shareContext = std::move(ctx);
}
- return that->extra->topextra->shareContext;
+ return extra->topextra->shareContext.get();
#endif // QT_NO_OPENGL
}
@@ -13024,10 +12632,8 @@ void QWidget::setMask(const QRegion &newMask)
d->extra->mask = newMask;
d->extra->hasMask = !newMask.isEmpty();
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
if (!testAttribute(Qt::WA_WState_Created))
return;
-#endif
d->setMask_sys(newMask);
@@ -13203,7 +12809,7 @@ QDebug operator<<(QDebug debug, const QWidget *widget)
if (widget->isWindow())
debug << ", window";
debug << ", " << geometry.width() << 'x' << geometry.height()
- << forcesign << geometry.x() << geometry.y() << noforcesign;
+ << Qt::forcesign << geometry.x() << geometry.y() << Qt::noforcesign;
if (frameGeometry != geometry) {
const QMargins margins(geometry.x() - frameGeometry.x(),
geometry.y() - frameGeometry.y(),
@@ -13213,7 +12819,7 @@ QDebug operator<<(QDebug debug, const QWidget *widget)
}
debug << ", devicePixelRatio=" << widget->devicePixelRatioF();
if (const WId wid = widget->internalWinId())
- debug << ", winId=0x" << hex << wid << dec;
+ debug << ", winId=0x" << Qt::hex << wid << Qt::dec;
}
debug << ')';
} else {
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index 4e5ef5a111..83a6e6d4b3 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -85,6 +85,7 @@ class QDragEnterEvent;
class QDragMoveEvent;
class QDragLeaveEvent;
class QDropEvent;
+class QScreen;
class QShowEvent;
class QHideEvent;
class QIcon;
@@ -524,7 +525,10 @@ public:
void setContentsMargins(int left, int top, int right, int bottom);
void setContentsMargins(const QMargins &margins);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("use contentsMargins()")
void getContentsMargins(int *left, int *top, int *right, int *bottom) const;
+#endif
QMargins contentsMargins() const;
QRect contentsRect() const;
@@ -555,7 +559,7 @@ public:
void addAction(QAction *action);
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
void addActions(const QList<QAction*> &actions);
- void insertActions(const QAction *before, const QList<QAction*> &actions);
+ void insertActions(QAction *before, const QList<QAction*> &actions);
#else
void addActions(QList<QAction*> actions);
void insertActions(QAction *before, QList<QAction*> actions);
@@ -598,6 +602,7 @@ public:
QBackingStore *backingStore() const;
QWindow *windowHandle() const;
+ QScreen *screen() const;
static QWidget *createWindowContainer(QWindow *window, QWidget *parent=nullptr, Qt::WindowFlags flags=Qt::WindowFlags());
@@ -648,7 +653,12 @@ protected:
virtual void showEvent(QShowEvent *event);
virtual void hideEvent(QHideEvent *event);
+
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result);
+#else
virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result);
+#endif
// Misc. protected functions
virtual void changeEvent(QEvent *);
@@ -689,7 +699,7 @@ private:
QLayout *takeLayout();
friend class QBackingStoreDevice;
- friend class QWidgetBackingStore;
+ friend class QWidgetRepaintManager;
friend class QApplication;
friend class QApplicationPrivate;
friend class QGuiApplication;
diff --git a/src/widgets/kernel/qwidget_p.h b/src/widgets/kernel/qwidget_p.h
index 3dccd00b8b..698928b0b0 100644
--- a/src/widgets/kernel/qwidget_p.h
+++ b/src/widgets/kernel/qwidget_p.h
@@ -75,15 +75,20 @@
#include <private/qgesture_p.h>
#include <qpa/qplatformbackingstore.h>
+#include <vector>
+#include <memory>
+
QT_BEGIN_NAMESPACE
+Q_DECLARE_LOGGING_CATEGORY(lcWidgetPainting);
+
// Extra QWidget data
// - to minimize memory usage for members that are seldom used.
// - top-level widgets have extra extra data to reduce cost further
class QWidgetWindow;
class QPaintEngine;
class QPixmap;
-class QWidgetBackingStore;
+class QWidgetRepaintManager;
class QGraphicsProxyWidget;
class QWidgetItemV2;
class QOpenGLContext;
@@ -113,60 +118,18 @@ protected:
QRegion m_region;
};
-
-
-class Q_AUTOTEST_EXPORT QWidgetBackingStoreTracker
-{
-
-public:
- QWidgetBackingStoreTracker();
- ~QWidgetBackingStoreTracker();
-
- void create(QWidget *tlw);
- void destroy();
-
- void registerWidget(QWidget *w);
- void unregisterWidget(QWidget *w);
- void unregisterWidgetSubtree(QWidget *w);
-
- inline QWidgetBackingStore* data()
- {
- return m_ptr;
- }
-
- inline QWidgetBackingStore* operator->()
- {
- return m_ptr;
- }
-
- inline QWidgetBackingStore& operator*()
- {
- return *m_ptr;
- }
-
- inline operator bool() const
- {
- return (0 != m_ptr);
- }
-
-private:
- Q_DISABLE_COPY_MOVE(QWidgetBackingStoreTracker)
-
-private:
- QWidgetBackingStore* m_ptr;
- QSet<QWidget *> m_widgets;
-};
-
struct QTLWExtra {
// *************************** Cross-platform variables *****************************
// Regular pointers (keep them together to avoid gaps on 64 bits architectures).
- QIcon *icon; // widget icon
- QWidgetBackingStoreTracker backingStoreTracker;
+ std::unique_ptr<QIcon> icon; // widget icon
+ std::unique_ptr<QWidgetRepaintManager> repaintManager;
QBackingStore *backingStore;
QPainter *sharedPainter;
QWidgetWindow *window;
- QOpenGLContext *shareContext;
+#ifndef QT_NO_OPENGL
+ mutable std::unique_ptr<QOpenGLContext> shareContext;
+#endif
// Implicit pointers (shared_null).
QString caption; // widget caption
@@ -184,7 +147,9 @@ struct QTLWExtra {
// ### TODO replace initialScreenIndex with QScreen *, in case the screens change at runtime
int initialScreenIndex; // Screen number when passing a QDesktop[Screen]Widget as parent.
- QVector<QPlatformTextureList *> widgetTextures;
+#ifndef QT_NO_OPENGL
+ std::vector<std::unique_ptr<QPlatformTextureList>> widgetTextures;
+#endif
// *************************** Cross-platform bit fields ****************************
uint opacity : 8;
@@ -192,41 +157,6 @@ struct QTLWExtra {
uint sizeAdjusted : 1;
uint inTopLevelResize : 1;
uint embedded : 1;
-
- // *************************** Platform specific values (bit fields first) **********
-#if 0 /* Used to be included in Qt4 for Q_WS_X11 */ // <----------------------------------------------------------- X11
- uint spont_unmapped: 1; // window was spontaneously unmapped
- uint dnd : 1; // DND properties installed
- uint validWMState : 1; // is WM_STATE valid?
- uint waitingForMapNotify : 1; // show() has been called, haven't got the MapNotify yet
- WId parentWinId; // parent window Id (valid after reparenting)
- WId userTimeWindow; // window id that contains user-time timestamp when WM supports a _NET_WM_USER_TIME_WINDOW atom
- QPoint fullScreenOffset;
-#ifndef QT_NO_XSYNC
- WId syncUpdateCounter;
- ulong syncRequestTimestamp;
- qint32 newCounterValueHi;
- quint32 newCounterValueLo;
-#endif
-#elif 0 /* Used to be included in Qt4 for Q_WS_WIN */ // <--------------------------------------------------------- WIN
- uint hotkeyRegistered: 1; // Hot key from the STARTUPINFO has been registered.
- HICON winIconBig; // internal big Windows icon
- HICON winIconSmall; // internal small Windows icon
-#elif 0 /* Used to be included in Qt4 for Q_WS_MAC */ // <--------------------------------------------------------- MAC
- uint resizer : 4;
- uint isSetGeometry : 1;
- uint isMove : 1;
- quint32 wattr;
- quint32 wclass;
- WindowGroupRef group;
- IconRef windowIcon; // the current window icon, if set with setWindowIcon_sys.
- quint32 savedWindowAttributesFromMaximized; // Saved attributes from when the calling updateMaximizeButton_sys()
- // This value is just to make sure we maximize and restore to the right location, yet we allow apps to be maximized and
- // manually resized.
- // The name is misleading, since this is set when maximizing the window. It is a hint to saveGeometry(..) to record the
- // starting position as 0,0 instead of the normal starting position.
- bool wasMaximized;
-#endif
};
struct QWExtra {
@@ -234,12 +164,12 @@ struct QWExtra {
// Regular pointers (keep them together to avoid gaps on 64 bits architectures).
void *glContext; // if the widget is hijacked by QGLWindowSurface
- QTLWExtra *topextra; // only useful for TLWs
+ std::unique_ptr<QTLWExtra> topextra; // only useful for TLWs
#if QT_CONFIG(graphicsview)
QGraphicsProxyWidget *proxyWidget; // if the widget is embedded
#endif
#ifndef QT_NO_CURSOR
- QCursor *curs;
+ std::unique_ptr<QCursor> curs;
#endif
QPointer<QStyle> style;
QPointer<QWidget> focus_proxy;
@@ -265,21 +195,6 @@ struct QWExtra {
uint inRenderWithPainter : 1;
uint hasMask : 1;
uint hasWindowContainer : 1;
-
- // *************************** Platform specific values (bit fields first) **********
-#if 0 /* Used to be included in Qt4 for Q_WS_WIN */ // <----------------------------------------------------------- WIN
-#if QT_CONFIG(draganddrop)
- QOleDropTarget *dropTarget; // drop target
- QList<QPointer<QWidget> > oleDropWidgets;
-#endif
-#elif 0 /* Used to be included in Qt4 for Q_WS_X11 */ // <--------------------------------------------------------- X11
- uint compress_events : 1;
- WId xDndProxy; // XDND forwarding to embedded windows
-#elif 0 /* Used to be included in Qt4 for Q_WS_MAC */ // <------------------------------------------------------ MAC
- // Cocoa Mask stuff
- QImage maskBits;
- CGImageRef imageMask;
-#endif
};
/*!
@@ -303,10 +218,11 @@ static inline bool bypassGraphicsProxyWidget(const QWidget *p)
class Q_WIDGETS_EXPORT QWidgetPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QWidget)
+ Q_GADGET
public:
// *************************** Cross-platform ***************************************
- enum DrawWidgetFlags {
+ enum DrawWidgetFlag {
DrawAsRoot = 0x01,
DrawPaintOnScreen = 0x02,
DrawRecursive = 0x04,
@@ -316,12 +232,15 @@ public:
DontDrawNativeChildren = 0x40,
DontSetCompositionMode = 0x80
};
+ Q_DECLARE_FLAGS(DrawWidgetFlags, DrawWidgetFlag)
+ Q_FLAG(DrawWidgetFlags)
enum CloseMode {
CloseNoEvent,
CloseWithEvent,
CloseWithSpontaneousEvent
};
+ Q_ENUM(CloseMode)
enum Direction {
DirectionNorth = 0x01,
@@ -329,6 +248,7 @@ public:
DirectionSouth = 0x02,
DirectionWest = 0x20
};
+ Q_ENUM(Direction)
// Functions.
explicit QWidgetPrivate(int version = QObjectPrivateVersion);
@@ -342,8 +262,16 @@ public:
QTLWExtra *maybeTopData() const;
QPainter *sharedPainter() const;
void setSharedPainter(QPainter *painter);
- QWidgetBackingStore *maybeBackingStore() const;
- QWidgetWindow *windowHandle() const;
+ QWidgetRepaintManager *maybeRepaintManager() const;
+
+ enum class WindowHandleMode {
+ Direct,
+ Closest,
+ TopLevel
+ };
+ QWindow *windowHandle(WindowHandleMode mode = WindowHandleMode::Direct) const;
+
+ QScreen *associatedScreen() const;
template <typename T>
void repaint(T t);
@@ -405,38 +333,38 @@ public:
void setUpdatesEnabled_helper(bool );
bool updateBrushOrigin(QPainter *, const QBrush &brush) const;
- void paintBackground(QPainter *, const QRegion &, int flags = DrawAsRoot) const;
+ void paintBackground(QPainter *, const QRegion &, DrawWidgetFlags flags = DrawAsRoot) const;
bool isAboutToShow() const;
QRegion prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags);
void render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &sourceRegion,
QWidget::RenderFlags renderFlags);
void render(QPaintDevice *target, const QPoint &targetOffset, const QRegion &sourceRegion,
QWidget::RenderFlags renderFlags);
- void drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
- QPainter *sharedPainter = 0, QWidgetBackingStore *backingStore = 0);
+ void drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, DrawWidgetFlags flags,
+ QPainter *sharedPainter = nullptr, QWidgetRepaintManager *repaintManager = nullptr);
void sendPaintEvent(const QRegion &toBePainted);
void paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& children, int index,
- const QRegion &rgn, const QPoint &offset, int flags,
- QPainter *sharedPainter, QWidgetBackingStore *backingStore);
+ const QRegion &rgn, const QPoint &offset, DrawWidgetFlags flags,
+ QPainter *sharedPainter, QWidgetRepaintManager *repaintManager);
#if QT_CONFIG(graphicsview)
static QGraphicsProxyWidget * nearestGraphicsProxyWidget(const QWidget *origin);
#endif
- void repaint_sys(const QRegion &rgn);
+ bool shouldPaintOnScreen() const;
+ void paintOnScreen(const QRegion &rgn);
QRect clipRect() const;
QRegion clipRegion() const;
void setSystemClip(QPaintEngine *paintEngine, qreal devicePixelRatio, const QRegion &region);
void subtractOpaqueChildren(QRegion &rgn, const QRect &clipRect) const;
- void subtractOpaqueSiblings(QRegion &source, bool *hasDirtySiblingsAbove = 0,
+ void subtractOpaqueSiblings(QRegion &source, bool *hasDirtySiblingsAbove = nullptr,
bool alsoNonOpaque = false) const;
void clipToEffectiveMask(QRegion &region) const;
void updateIsOpaque();
void setOpaque(bool opaque);
void updateIsTranslucent();
- bool paintOnScreen() const;
#if QT_CONFIG(graphicseffect)
void invalidateGraphicsEffectsRecursively();
#endif // QT_CONFIG(graphicseffect)
@@ -463,6 +391,8 @@ public:
void syncBackingStore();
void syncBackingStore(const QRegion &region);
+ bool shouldDiscardSyncRequest() const;
+
// tells the input method about the widgets transform
void updateWidgetTransform(QEvent *event);
@@ -527,7 +457,7 @@ public:
void getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const;
void setLayoutItemMargins(int left, int top, int right, int bottom);
- void setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt = 0);
+ void setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt = nullptr);
void updateContentsRect();
QMargins safeAreaMargins() const;
@@ -557,7 +487,7 @@ public:
QGraphicsProxyWidget *ancestorProxy = widget->d_func()->nearestGraphicsProxyWidget(widget);
//It's embedded if it has an ancestor
if (ancestorProxy) {
- if (!bypassGraphicsProxyWidget(widget) && ancestorProxy->scene() != 0) {
+ if (!bypassGraphicsProxyWidget(widget) && ancestorProxy->scene() != nullptr) {
// One view, let be smart and return the viewport rect then the popup is aligned
if (ancestorProxy->scene()->views().size() == 1) {
QGraphicsView *view = ancestorProxy->scene()->views().at(0);
@@ -588,7 +518,7 @@ public:
}
inline void restoreRedirected()
- { redirectDev = 0; }
+ { redirectDev = nullptr; }
inline void enforceNativeChildren()
{
@@ -654,7 +584,7 @@ public:
QOpenGLContext *shareContext() const;
- virtual QObject *focusObject() { return 0; }
+ virtual QObject *focusObject() { return nullptr; }
#ifndef QT_NO_OPENGL
virtual GLuint textureId() const { return 0; }
@@ -662,7 +592,7 @@ public:
Q_Q(QWidget);
return q->testAttribute(Qt::WA_AlwaysStackOnTop)
? QPlatformTextureList::StacksOnTop
- : QPlatformTextureList::Flags(0);
+ : QPlatformTextureList::Flags(nullptr);
}
virtual QImage grabFramebuffer() { return QImage(); }
virtual void beginBackingStorePainting() { }
@@ -698,7 +628,7 @@ public:
// Variables.
// Regular pointers (keep them together to avoid gaps on 64 bit architectures).
- QWExtra *extra;
+ std::unique_ptr<QWExtra> extra;
QWidget *focus_next;
QWidget *focus_prev;
QWidget *focus_child;
@@ -792,109 +722,8 @@ public:
// *************************** Platform specific ************************************
#if defined(Q_OS_WIN)
uint noPaintOnScreen : 1; // see qwidget.cpp ::paintEngine()
-#endif
-#if 0 /* Used to be included in Qt4 for Q_WS_X11 */ // <----------------------------------------------------------- X11
- Qt::HANDLE picture;
- static QWidget *mouseGrabber;
- static QWidget *keyboardGrabber;
-
- void setWindowRole();
- void sendStartupMessage(const char *message) const;
- void x11UpdateIsOpaque();
- bool isBackgroundInherited() const;
- void updateX11AcceptFocus();
- QPoint mapToGlobal(const QPoint &pos) const;
- QPoint mapFromGlobal(const QPoint &pos) const;
-#elif 0 /* Used to be included in Qt4 for Q_WS_WIN */ // <--------------------------------------------------------- WIN
-#ifndef QT_NO_GESTURES
- uint nativeGesturePanEnabled : 1;
-#endif
- bool shouldShowMaximizeButton();
- void winUpdateIsOpaque();
- void reparentChildren();
-#if QT_CONFIG(draganddrop)
- QOleDropTarget *registerOleDnd(QWidget *widget);
- void unregisterOleDnd(QWidget *widget, QOleDropTarget *target);
-#endif
- void grabMouseWhileInWindow();
- void registerTouchWindow();
- void winSetupGestures();
-#elif defined(Q_OS_MAC) // <--------------------------------------------------------- MAC
+#elif defined(Q_OS_MAC)
void macUpdateSizeAttribute();
-#elif 0 /* Used to be included in Qt4 for Q_WS_MAC */ // <--------------------------------------------------------- MAC (old stuff)
- // This is new stuff
- uint needWindowChange : 1;
-
- // Each wiget keeps a list of all its child and grandchild OpenGL widgets.
- // This list is used to update the gl context whenever a parent and a granparent
- // moves, and also to check for intersections with gl widgets within the window
- // when a widget moves.
- struct GlWidgetInfo
- {
- GlWidgetInfo(QWidget *widget) : widget(widget), lastUpdateWidget(0) { }
- bool operator==(const GlWidgetInfo &other) const { return (widget == other.widget); }
- QWidget * widget;
- QWidget * lastUpdateWidget;
- };
-
- // dirtyOnWidget contains the areas in the widget that needs to be repained,
- // in the same way as dirtyOnScreen does for the window. Areas are added in
- // dirtyWidget_sys and cleared in the paint event. In scroll_sys we then use
- // this information repaint invalid areas when widgets are scrolled.
- QRegion dirtyOnWidget;
- EventHandlerRef window_event;
- QList<GlWidgetInfo> glWidgets;
-
- //these are here just for code compat (HIViews)
- Qt::HANDLE qd_hd;
-
- void macUpdateHideOnSuspend();
- void macUpdateOpaqueSizeGrip();
- void macUpdateIgnoreMouseEvents();
- void macUpdateMetalAttribute();
- void macUpdateIsOpaque();
- void macSetNeedsDisplay(QRegion region);
- void setEnabled_helper_sys(bool enable);
- bool isRealWindow() const;
- void adjustWithinMaxAndMinSize(int &w, int &h);
- void applyMaxAndMinSizeOnWindow();
- void update_sys(const QRect &rect);
- void update_sys(const QRegion &rgn);
- void setGeometry_sys_helper(int, int, int, int, bool);
- void updateMaximizeButton_sys();
- void createWindow_sys();
- void recreateMacWindow();
- void setSubWindowStacking(bool set);
- void setWindowLevel();
- void finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ windowRef);
- void syncCocoaMask();
- void finishCocoaMaskSetup();
- // Did we add the drawRectOriginal method?
- bool drawRectOriginalAdded;
- // Is the original drawRect method available?
- bool originalDrawMethod;
- // Do we need to change the methods?
- bool changeMethods;
-
- // Unified toolbar variables
- bool isInUnifiedToolbar;
- QUnifiedToolbarSurface *unifiedSurface;
- QPoint toolbar_offset;
- QWidget *toolbar_ancestor;
- bool flushRequested;
- bool touchEventsEnabled;
- void determineWindowClass();
- void transferChildren();
- bool qt_mac_dnd_event(uint, DragRef);
- void toggleDrawers(bool);
- //mac event functions
- static bool qt_create_root_win();
- static void qt_clean_root_win();
- static bool qt_mac_update_sizer(QWidget *, int up = 0);
- static OSStatus qt_window_event(EventHandlerCallRef er, EventRef event, void *);
- static OSStatus qt_widget_event(EventHandlerCallRef er, EventRef event, void *);
- static bool qt_widget_rgn(QWidget *, short, RgnHandle, bool);
- void registerTouchWindow(bool enable = true);
#endif
void setNetWmWindowTypes(bool skipIfMissing = false);
@@ -902,18 +731,20 @@ public:
bool stealMouseGrab(bool grab);
};
+Q_DECLARE_OPERATORS_FOR_FLAGS(QWidgetPrivate::DrawWidgetFlags)
+
struct QWidgetPaintContext
{
- inline QWidgetPaintContext(QPaintDevice *d, const QRegion &r, const QPoint &o, int f,
- QPainter *p, QWidgetBackingStore *b)
- : pdev(d), rgn(r), offset(o), flags(f), sharedPainter(p), backingStore(b), painter(0) {}
+ inline QWidgetPaintContext(QPaintDevice *d, const QRegion &r, const QPoint &o, QWidgetPrivate::DrawWidgetFlags f,
+ QPainter *p, QWidgetRepaintManager *rpm)
+ : pdev(d), rgn(r), offset(o), flags(f), sharedPainter(p), repaintManager(rpm), painter(nullptr) {}
QPaintDevice *pdev;
QRegion rgn;
QPoint offset;
- int flags;
+ QWidgetPrivate::DrawWidgetFlags flags;
QPainter *sharedPainter;
- QWidgetBackingStore *backingStore;
+ QWidgetRepaintManager *repaintManager;
QPainter *painter;
};
@@ -922,14 +753,14 @@ class QWidgetEffectSourcePrivate : public QGraphicsEffectSourcePrivate
{
public:
QWidgetEffectSourcePrivate(QWidget *widget)
- : QGraphicsEffectSourcePrivate(), m_widget(widget), context(0), updateDueToGraphicsEffect(false)
+ : QGraphicsEffectSourcePrivate(), m_widget(widget), context(nullptr), updateDueToGraphicsEffect(false)
{}
void detach() override
- { m_widget->d_func()->graphicsEffect = 0; }
+ { m_widget->d_func()->graphicsEffect = nullptr; }
const QGraphicsItem *graphicsItem() const override
- { return 0; }
+ { return nullptr; }
const QWidget *widget() const override
{ return m_widget; }
@@ -955,7 +786,7 @@ public:
}
const QStyleOption *styleOption() const override
- { return 0; }
+ { return nullptr; }
QRect deviceRect() const override
{ return m_widget->window()->rect(); }
@@ -974,25 +805,25 @@ public:
inline QWExtra *QWidgetPrivate::extraData() const
{
- return extra;
+ return extra.get();
}
inline QTLWExtra *QWidgetPrivate::topData() const
{
const_cast<QWidgetPrivate *>(this)->createTLExtra();
- return extra->topextra;
+ return extra->topextra.get();
}
inline QTLWExtra *QWidgetPrivate::maybeTopData() const
{
- return extra ? extra->topextra : 0;
+ return extra ? extra->topextra.get() : nullptr;
}
inline QPainter *QWidgetPrivate::sharedPainter() const
{
Q_Q(const QWidget);
QTLWExtra *x = q->window()->d_func()->maybeTopData();
- return x ? x->sharedPainter : 0;
+ return x ? x->sharedPainter : nullptr;
}
inline void QWidgetPrivate::setSharedPainter(QPainter *painter)
@@ -1009,18 +840,11 @@ inline bool QWidgetPrivate::pointInsideRectAndMask(const QPoint &p) const
|| extra->mask.contains(p));
}
-inline QWidgetBackingStore *QWidgetPrivate::maybeBackingStore() const
+inline QWidgetRepaintManager *QWidgetPrivate::maybeRepaintManager() const
{
Q_Q(const QWidget);
QTLWExtra *x = q->window()->d_func()->maybeTopData();
- return x ? x->backingStoreTracker.data() : 0;
-}
-
-inline QWidgetWindow *QWidgetPrivate::windowHandle() const
-{
- if (QTLWExtra *x = maybeTopData())
- return x->window;
- return nullptr;
+ return x ? x->repaintManager.get() : nullptr;
}
QT_END_NAMESPACE
diff --git a/src/widgets/kernel/qwidgetbackingstore_p.h b/src/widgets/kernel/qwidgetbackingstore_p.h
deleted file mode 100644
index 4d15ab138e..0000000000
--- a/src/widgets/kernel/qwidgetbackingstore_p.h
+++ /dev/null
@@ -1,311 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWIDGETBACKINGSTORE_P_H
-#define QWIDGETBACKINGSTORE_P_H
-
-//
-// W A R N I N G
-// -------------
-//
-// This file is not part of the Qt API. It exists purely as an
-// implementation detail. This header file may change from version to
-// version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtWidgets/private/qtwidgetsglobal_p.h>
-#include <QDebug>
-#include <QtWidgets/qwidget.h>
-#include <private/qwidget_p.h>
-#include <QtGui/qbackingstore.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPlatformTextureList;
-class QPlatformTextureListWatcher;
-class QWidgetBackingStore;
-
-struct BeginPaintInfo {
- inline BeginPaintInfo() : wasFlushed(0), nothingToPaint(0), backingStoreRecreated(0) {}
- uint wasFlushed : 1;
- uint nothingToPaint : 1;
- uint backingStoreRecreated : 1;
-};
-
-#ifndef QT_NO_OPENGL
-class QPlatformTextureListWatcher : public QObject
-{
- Q_OBJECT
-
-public:
- QPlatformTextureListWatcher(QWidgetBackingStore *backingStore);
- void watch(QPlatformTextureList *textureList);
- bool isLocked() const;
-
-private slots:
- void onLockStatusChanged(bool locked);
-
-private:
- QHash<QPlatformTextureList *, bool> m_locked;
- QWidgetBackingStore *m_backingStore;
-};
-#endif
-
-class Q_AUTOTEST_EXPORT QWidgetBackingStore
-{
-public:
- enum UpdateTime {
- UpdateNow,
- UpdateLater
- };
-
- enum BufferState{
- BufferValid,
- BufferInvalid
- };
-
- QWidgetBackingStore(QWidget *t);
- ~QWidgetBackingStore();
-
- static void showYellowThing(QWidget *widget, const QRegion &rgn, int msec, bool);
-
- void sync(QWidget *exposedWidget, const QRegion &exposedRegion);
- void sync();
- void flush(QWidget *widget = 0);
-
- QBackingStore *backingStore() const { return store; }
-
- inline bool isDirty() const
- {
- return !(dirtyWidgets.isEmpty() && dirty.isEmpty() && dirtyRenderToTextureWidgets.isEmpty());
- }
-
- template <class T>
- void markDirty(const T &r, QWidget *widget, UpdateTime updateTime = UpdateLater,
- BufferState bufferState = BufferValid);
-
-private:
- QWidget *tlw;
- QRegion dirtyOnScreen; // needsFlush
- QRegion dirty; // needsRepaint
- QRegion dirtyFromPreviousSync;
- QVector<QWidget *> dirtyWidgets;
- QVector<QWidget *> dirtyRenderToTextureWidgets;
- QVector<QWidget *> *dirtyOnScreenWidgets;
- QList<QWidget *> staticWidgets;
- QBackingStore *store;
- uint updateRequestSent : 1;
-
- QPlatformTextureListWatcher *textureListWatcher;
- QElapsedTimer perfTime;
- int perfFrames;
-
- void sendUpdateRequest(QWidget *widget, UpdateTime updateTime);
-
- static bool flushPaint(QWidget *widget, const QRegion &rgn);
- static void unflushPaint(QWidget *widget, const QRegion &rgn);
- static void qt_flush(QWidget *widget, const QRegion &region, QBackingStore *backingStore,
- QWidget *tlw,
- QPlatformTextureList *widgetTextures,
- QWidgetBackingStore *widgetBackingStore);
-
- void doSync();
- bool bltRect(const QRect &rect, int dx, int dy, QWidget *widget);
- void releaseBuffer();
-
- void beginPaint(QRegion &toClean, QWidget *widget, QBackingStore *backingStore,
- BeginPaintInfo *returnInfo, bool toCleanIsInTopLevelCoordinates = true);
- void endPaint(const QRegion &cleaned, QBackingStore *backingStore, BeginPaintInfo *beginPaintInfo);
-
- QRegion dirtyRegion(QWidget *widget = 0) const;
- QRegion staticContents(QWidget *widget = 0, const QRect &withinClipRect = QRect()) const;
-
- void markDirtyOnScreen(const QRegion &dirtyOnScreen, QWidget *widget, const QPoint &topLevelOffset);
-
- void removeDirtyWidget(QWidget *w);
-
- void updateLists(QWidget *widget);
-
- bool syncAllowed();
-
- inline void addDirtyWidget(QWidget *widget, const QRegion &rgn)
- {
- if (widget && !widget->d_func()->inDirtyList && !widget->data->in_destructor) {
- QWidgetPrivate *widgetPrivate = widget->d_func();
-#if QT_CONFIG(graphicseffect)
- if (widgetPrivate->graphicsEffect)
- widgetPrivate->dirty = widgetPrivate->effectiveRectFor(rgn.boundingRect());
- else
-#endif // QT_CONFIG(graphicseffect)
- widgetPrivate->dirty = rgn;
- dirtyWidgets.append(widget);
- widgetPrivate->inDirtyList = true;
- }
- }
-
- inline void addDirtyRenderToTextureWidget(QWidget *widget)
- {
- if (widget && !widget->d_func()->inDirtyList && !widget->data->in_destructor) {
- QWidgetPrivate *widgetPrivate = widget->d_func();
- Q_ASSERT(widgetPrivate->renderToTexture);
- dirtyRenderToTextureWidgets.append(widget);
- widgetPrivate->inDirtyList = true;
- }
- }
-
- inline void dirtyWidgetsRemoveAll(QWidget *widget)
- {
- int i = 0;
- while (i < dirtyWidgets.size()) {
- if (dirtyWidgets.at(i) == widget)
- dirtyWidgets.remove(i);
- else
- ++i;
- }
- }
-
- inline void addStaticWidget(QWidget *widget)
- {
- if (!widget)
- return;
-
- Q_ASSERT(widget->testAttribute(Qt::WA_StaticContents));
- if (!staticWidgets.contains(widget))
- staticWidgets.append(widget);
- }
-
- inline void removeStaticWidget(QWidget *widget)
- { staticWidgets.removeAll(widget); }
-
- // Move the reparented widget and all its static children from this backing store
- // to the new backing store if reparented into another top-level / backing store.
- inline void moveStaticWidgets(QWidget *reparented)
- {
- Q_ASSERT(reparented);
- QWidgetBackingStore *newBs = reparented->d_func()->maybeBackingStore();
- if (newBs == this)
- return;
-
- int i = 0;
- while (i < staticWidgets.size()) {
- QWidget *w = staticWidgets.at(i);
- if (reparented == w || reparented->isAncestorOf(w)) {
- staticWidgets.removeAt(i);
- if (newBs)
- newBs->addStaticWidget(w);
- } else {
- ++i;
- }
- }
- }
-
- inline QRect topLevelRect() const
- {
- return tlw->data->crect;
- }
-
- inline void appendDirtyOnScreenWidget(QWidget *widget)
- {
- if (!widget)
- return;
-
- if (!dirtyOnScreenWidgets) {
- dirtyOnScreenWidgets = new QVector<QWidget *>;
- dirtyOnScreenWidgets->append(widget);
- } else if (!dirtyOnScreenWidgets->contains(widget)) {
- dirtyOnScreenWidgets->append(widget);
- }
- }
-
- inline void dirtyOnScreenWidgetsRemoveAll(QWidget *widget)
- {
- if (!widget || !dirtyOnScreenWidgets)
- return;
-
- int i = 0;
- while (i < dirtyOnScreenWidgets->size()) {
- if (dirtyOnScreenWidgets->at(i) == widget)
- dirtyOnScreenWidgets->remove(i);
- else
- ++i;
- }
- }
-
- inline void resetWidget(QWidget *widget)
- {
- if (widget) {
- widget->d_func()->inDirtyList = false;
- widget->d_func()->isScrolled = false;
- widget->d_func()->isMoved = false;
- widget->d_func()->dirty = QRegion();
- }
- }
-
- inline void updateStaticContentsSize()
- {
- for (int i = 0; i < staticWidgets.size(); ++i) {
- QWidgetPrivate *wd = staticWidgets.at(i)->d_func();
- if (!wd->extra)
- wd->createExtra();
- wd->extra->staticContentsSize = wd->data.crect.size();
- }
- }
-
- inline bool hasStaticContents() const
- {
-#if defined(Q_OS_WIN)
- return !staticWidgets.isEmpty();
-#else
- return !staticWidgets.isEmpty() && false;
-#endif
- }
-
- friend QRegion qt_dirtyRegion(QWidget *);
- friend class QWidgetPrivate;
- friend class QWidget;
- friend class QBackingStore;
-
- Q_DISABLE_COPY_MOVE(QWidgetBackingStore)
-};
-
-QT_END_NAMESPACE
-
-#endif // QBACKINGSTORE_P_H
diff --git a/src/widgets/kernel/qwidgetbackingstore.cpp b/src/widgets/kernel/qwidgetrepaintmanager.cpp
index c51527f8bc..c3211e275f 100644
--- a/src/widgets/kernel/qwidgetbackingstore.cpp
+++ b/src/widgets/kernel/qwidgetrepaintmanager.cpp
@@ -40,7 +40,7 @@
#include "qplatformdefs.h"
-#include "qwidgetbackingstore_p.h"
+#include "qwidgetrepaintmanager_p.h"
#include <QtCore/qglobal.h>
#include <QtCore/qdebug.h>
@@ -63,459 +63,138 @@
#include <qpa/qplatformbackingstore.h>
-#if defined(Q_OS_WIN) && !defined(QT_NO_PAINT_DEBUG)
-# include <QtCore/qt_windows.h>
-# include <qpa/qplatformnativeinterface.h>
-#endif
+#include <private/qmemory_p.h>
QT_BEGIN_NAMESPACE
-extern QRegion qt_dirtyRegion(QWidget *);
-
#ifndef QT_NO_OPENGL
Q_GLOBAL_STATIC(QPlatformTextureList, qt_dummy_platformTextureList)
-#endif
-static bool hasPlatformWindow(QWidget *widget)
-{
- return widget && widget->windowHandle() && widget->windowHandle()->handle();
-}
-
-/**
- * Flushes the contents of the \a backingStore into the screen area of \a widget.
- * \a region is the region to be updated in \a widget coordinates.
- */
-void QWidgetBackingStore::qt_flush(QWidget *widget, const QRegion &region, QBackingStore *backingStore,
- QWidget *tlw, QPlatformTextureList *widgetTextures,
- QWidgetBackingStore *widgetBackingStore)
+// Watches one or more QPlatformTextureLists for changes in the lock state and
+// triggers a backingstore sync when all the registered lists turn into
+// unlocked state. This is essential when a custom composeAndFlush()
+// implementation in a platform plugin is not synchronous and keeps
+// holding on to the textures for some time even after returning from there.
+class QPlatformTextureListWatcher : public QObject
{
-#ifdef QT_NO_OPENGL
- Q_UNUSED(widgetTextures);
- Q_ASSERT(!region.isEmpty());
-#else
- Q_ASSERT(!region.isEmpty() || widgetTextures);
-#endif
- Q_ASSERT(widget);
- Q_ASSERT(backingStore);
- Q_ASSERT(tlw);
-#if !defined(QT_NO_PAINT_DEBUG)
- static int flushUpdate = qEnvironmentVariableIntValue("QT_FLUSH_UPDATE");
- if (flushUpdate > 0)
- QWidgetBackingStore::showYellowThing(widget, region, flushUpdate * 10, false);
-#endif
-
- if (tlw->testAttribute(Qt::WA_DontShowOnScreen) || widget->testAttribute(Qt::WA_DontShowOnScreen))
- return;
-
- // Foreign Windows do not have backing store content and must not be flushed
- if (QWindow *widgetWindow = widget->windowHandle()) {
- if (widgetWindow->type() == Qt::ForeignWindow)
- return;
+ Q_OBJECT
+public:
+ QPlatformTextureListWatcher(QWidgetRepaintManager *repaintManager)
+ : m_repaintManager(repaintManager) {}
+
+ void watch(QPlatformTextureList *textureList) {
+ connect(textureList, SIGNAL(locked(bool)), SLOT(onLockStatusChanged(bool)));
+ m_locked[textureList] = textureList->isLocked();
}
- static bool fpsDebug = qEnvironmentVariableIntValue("QT_DEBUG_FPS");
- if (fpsDebug) {
- if (!widgetBackingStore->perfFrames++)
- widgetBackingStore->perfTime.start();
- if (widgetBackingStore->perfTime.elapsed() > 5000) {
- double fps = double(widgetBackingStore->perfFrames * 1000) / widgetBackingStore->perfTime.restart();
- qDebug("FPS: %.1f\n", fps);
- widgetBackingStore->perfFrames = 0;
+ bool isLocked() const {
+ foreach (bool v, m_locked) {
+ if (v)
+ return true;
}
+ return false;
}
- QPoint offset;
- if (widget != tlw)
- offset += widget->mapTo(tlw, QPoint());
-
- QRegion effectiveRegion = region;
-#ifndef QT_NO_OPENGL
- const bool compositionWasActive = widget->d_func()->renderToTextureComposeActive;
- if (!widgetTextures) {
- widget->d_func()->renderToTextureComposeActive = false;
- // Detect the case of falling back to the normal flush path when no
- // render-to-texture widgets are visible anymore. We will force one
- // last flush to go through the OpenGL-based composition to prevent
- // artifacts. The next flush after this one will use the normal path.
- if (compositionWasActive)
- widgetTextures = qt_dummy_platformTextureList;
- } else {
- widget->d_func()->renderToTextureComposeActive = true;
- }
- // When changing the composition status, make sure the dirty region covers
- // the entire widget. Just having e.g. the shown/hidden render-to-texture
- // widget's area marked as dirty is incorrect when changing flush paths.
- if (compositionWasActive != widget->d_func()->renderToTextureComposeActive)
- effectiveRegion = widget->rect();
-
- // re-test since we may have been forced to this path via the dummy texture list above
- if (widgetTextures) {
- qt_window_private(tlw->windowHandle())->compositing = true;
- widget->window()->d_func()->sendComposeStatus(widget->window(), false);
- // A window may have alpha even when the app did not request
- // WA_TranslucentBackground. Therefore the compositor needs to know whether the app intends
- // to rely on translucency, in order to decide if it should clear to transparent or opaque.
- const bool translucentBackground = widget->testAttribute(Qt::WA_TranslucentBackground);
- backingStore->handle()->composeAndFlush(widget->windowHandle(), effectiveRegion, offset,
- widgetTextures, translucentBackground);
- widget->window()->d_func()->sendComposeStatus(widget->window(), true);
- } else
-#endif
- backingStore->flush(effectiveRegion, widget->windowHandle(), offset);
-}
-
-#ifndef QT_NO_PAINT_DEBUG
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-
-static void showYellowThing_win(QWidget *widget, const QRegion &region, int msec)
-{
- // We expect to be passed a native parent.
- QWindow *nativeWindow = widget->windowHandle();
- if (!nativeWindow)
- return;
- void *hdcV = QGuiApplication::platformNativeInterface()->nativeResourceForWindow(QByteArrayLiteral("getDC"), nativeWindow);
- if (!hdcV)
- return;
- const HDC hdc = reinterpret_cast<HDC>(hdcV);
-
- static const COLORREF colors[] = {RGB(255, 255, 0), RGB(255, 200, 55), RGB(200, 255, 55), RGB(200, 200, 0)};
-
- static size_t i = 0;
- const HBRUSH brush = CreateSolidBrush(colors[i]);
- i = (i + 1) % (sizeof(colors) / sizeof(colors[0]));
-
- for (const QRect &rect : region) {
- RECT winRect;
- SetRect(&winRect, rect.left(), rect.top(), rect.right(), rect.bottom());
- FillRect(hdc, &winRect, brush);
- }
- DeleteObject(brush);
- QGuiApplication::platformNativeInterface()->nativeResourceForWindow(QByteArrayLiteral("releaseDC"), nativeWindow);
- ::Sleep(msec);
-}
-#endif // defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
-
-void QWidgetBackingStore::showYellowThing(QWidget *widget, const QRegion &toBePainted, int msec, bool unclipped)
-{
-#ifdef Q_OS_WINRT
- Q_UNUSED(msec)
+private slots:
+ void onLockStatusChanged(bool locked) {
+ QPlatformTextureList *tl = static_cast<QPlatformTextureList *>(sender());
+ m_locked[tl] = locked;
+ if (!isLocked())
+ m_repaintManager->sync();
+ }
+
+private:
+ QHash<QPlatformTextureList *, bool> m_locked;
+ QWidgetRepaintManager *m_repaintManager;
+};
#endif
- QRegion paintRegion = toBePainted;
- QRect widgetRect = widget->rect();
-
- if (!hasPlatformWindow(widget)) {
- QWidget *nativeParent = widget->nativeParentWidget();
- const QPoint offset = widget->mapTo(nativeParent, QPoint(0, 0));
- paintRegion.translate(offset);
- widgetRect.translate(offset);
- widget = nativeParent;
- }
-
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- Q_UNUSED(unclipped);
- showYellowThing_win(widget, paintRegion, msec);
-#else
- //flags to fool painter
- bool paintUnclipped = widget->testAttribute(Qt::WA_PaintUnclipped);
- if (unclipped && !widget->d_func()->paintOnScreen())
- widget->setAttribute(Qt::WA_PaintUnclipped);
-
- const bool setFlag = !widget->testAttribute(Qt::WA_WState_InPaintEvent);
- if (setFlag)
- widget->setAttribute(Qt::WA_WState_InPaintEvent);
-
- //setup the engine
- QPaintEngine *pe = widget->paintEngine();
- if (pe) {
- pe->setSystemClip(paintRegion);
- {
- QPainter p(widget);
- p.setClipRegion(paintRegion);
- static int i = 0;
- switch (i) {
- case 0:
- p.fillRect(widgetRect, QColor(255,255,0));
- break;
- case 1:
- p.fillRect(widgetRect, QColor(255,200,55));
- break;
- case 2:
- p.fillRect(widgetRect, QColor(200,255,55));
- break;
- case 3:
- p.fillRect(widgetRect, QColor(200,200,0));
- break;
- }
- i = (i+1) & 3;
- p.end();
- }
- }
- if (setFlag)
- widget->setAttribute(Qt::WA_WState_InPaintEvent, false);
-
- //restore
- widget->setAttribute(Qt::WA_PaintUnclipped, paintUnclipped);
-
- if (pe)
- pe->setSystemClip(QRegion());
-
-#if defined(Q_OS_UNIX)
- ::usleep(1000 * msec);
-#endif
-#endif // !Q_OS_WIN
-}
+// ---------------------------------------------------------------------------
-bool QWidgetBackingStore::flushPaint(QWidget *widget, const QRegion &rgn)
+QWidgetRepaintManager::QWidgetRepaintManager(QWidget *topLevel)
+ : tlw(topLevel), store(tlw->backingStore())
{
- if (!widget)
- return false;
-
- int delay = 0;
- if (widget->testAttribute(Qt::WA_WState_InPaintEvent)) {
- static int flushPaintEvent = qEnvironmentVariableIntValue("QT_FLUSH_PAINT_EVENT");
- if (!flushPaintEvent)
- return false;
- delay = flushPaintEvent;
- } else {
- static int flushPaint = qEnvironmentVariableIntValue("QT_FLUSH_PAINT");
- if (!flushPaint)
- return false;
- delay = flushPaint;
- }
+ Q_ASSERT(store);
- QWidgetBackingStore::showYellowThing(widget, rgn, delay * 10, true);
- return true;
+ // Ensure all existing subsurfaces and static widgets are added to their respective lists.
+ updateLists(topLevel);
}
-void QWidgetBackingStore::unflushPaint(QWidget *widget, const QRegion &rgn)
+void QWidgetRepaintManager::updateLists(QWidget *cur)
{
- if (widget->d_func()->paintOnScreen() || rgn.isEmpty())
- return;
-
- QWidget *tlw = widget->window();
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (!tlwExtra)
+ if (!cur)
return;
- qt_flush(widget, rgn, tlwExtra->backingStoreTracker->store, tlw, 0, tlw->d_func()->maybeBackingStore());
-}
-#endif // QT_NO_PAINT_DEBUG
-
-/*
- Moves the whole rect by (dx, dy) in widget's coordinate system.
- Doesn't generate any updates.
-*/
-bool QWidgetBackingStore::bltRect(const QRect &rect, int dx, int dy, QWidget *widget)
-{
- const QPoint pos(widget->mapTo(tlw, rect.topLeft()));
- const QRect tlwRect(QRect(pos, rect.size()));
- if (dirty.intersects(tlwRect))
- return false; // We don't want to scroll junk.
- return store->scroll(tlwRect, dx, dy);
-}
-
-void QWidgetBackingStore::releaseBuffer()
-{
- if (store)
- store->resize(QSize());
-}
-
-/*!
- Prepares the window surface to paint a\ toClean region of the \a widget and
- updates the BeginPaintInfo struct accordingly.
-
- The \a toClean region might be clipped by the window surface.
-*/
-void QWidgetBackingStore::beginPaint(QRegion &toClean, QWidget *widget, QBackingStore *backingStore,
- BeginPaintInfo *returnInfo, bool toCleanIsInTopLevelCoordinates)
-{
- Q_UNUSED(widget);
- Q_UNUSED(toCleanIsInTopLevelCoordinates);
-
- // Always flush repainted areas.
- dirtyOnScreen += toClean;
-
-#ifdef QT_NO_PAINT_DEBUG
- backingStore->beginPaint(toClean);
-#else
- returnInfo->wasFlushed = QWidgetBackingStore::flushPaint(tlw, toClean);
- // Avoid deadlock with QT_FLUSH_PAINT: the server will wait for
- // the BackingStore lock, so if we hold that, the server will
- // never release the Communication lock that we are waiting for in
- // sendSynchronousCommand
- if (!returnInfo->wasFlushed)
- backingStore->beginPaint(toClean);
-#endif
-
- Q_UNUSED(returnInfo);
-}
+ QList<QObject*> children = cur->children();
+ for (int i = 0; i < children.size(); ++i) {
+ QWidget *child = qobject_cast<QWidget*>(children.at(i));
+ if (!child || child->isWindow())
+ continue;
-void QWidgetBackingStore::endPaint(const QRegion &cleaned, QBackingStore *backingStore,
- BeginPaintInfo *beginPaintInfo)
-{
-#ifndef QT_NO_PAINT_DEBUG
- if (!beginPaintInfo->wasFlushed)
- backingStore->endPaint();
- else
- QWidgetBackingStore::unflushPaint(tlw, cleaned);
-#else
- Q_UNUSED(beginPaintInfo);
- Q_UNUSED(cleaned);
- backingStore->endPaint();
-#endif
+ updateLists(child);
+ }
- flush();
+ if (cur->testAttribute(Qt::WA_StaticContents))
+ addStaticWidget(cur);
}
-/*!
- Returns the region (in top-level coordinates) that needs repaint and/or flush.
-
- If the widget is non-zero, only the dirty region for the widget is returned
- and the region will be in widget coordinates.
-*/
-QRegion QWidgetBackingStore::dirtyRegion(QWidget *widget) const
+QWidgetRepaintManager::~QWidgetRepaintManager()
{
- const bool widgetDirty = widget && widget != tlw;
- const QRect tlwRect(topLevelRect());
- const QRect surfaceGeometry(tlwRect.topLeft(), store->size());
- if (surfaceGeometry != tlwRect && surfaceGeometry.size() != tlwRect.size()) {
- if (widgetDirty) {
- const QRect dirtyTlwRect = QRect(QPoint(), tlwRect.size());
- const QPoint offset(widget->mapTo(tlw, QPoint()));
- const QRect dirtyWidgetRect(dirtyTlwRect & widget->rect().translated(offset));
- return dirtyWidgetRect.translated(-offset);
- }
- return QRect(QPoint(), tlwRect.size());
- }
-
- // Calculate the region that needs repaint.
- QRegion r(dirty);
- for (int i = 0; i < dirtyWidgets.size(); ++i) {
- QWidget *w = dirtyWidgets.at(i);
- if (widgetDirty && w != widget && !widget->isAncestorOf(w))
- continue;
- r += w->d_func()->dirty.translated(w->mapTo(tlw, QPoint()));
- }
-
- // Append the region that needs flush.
- r += dirtyOnScreen;
-
- if (dirtyOnScreenWidgets) { // Only in use with native child widgets.
- for (int i = 0; i < dirtyOnScreenWidgets->size(); ++i) {
- QWidget *w = dirtyOnScreenWidgets->at(i);
- if (widgetDirty && w != widget && !widget->isAncestorOf(w))
- continue;
- QWidgetPrivate *wd = w->d_func();
- Q_ASSERT(wd->needsFlush);
- r += wd->needsFlush->translated(w->mapTo(tlw, QPoint()));
- }
- }
-
- if (widgetDirty) {
- // Intersect with the widget geometry and translate to its coordinates.
- const QPoint offset(widget->mapTo(tlw, QPoint()));
- r &= widget->rect().translated(offset);
- r.translate(-offset);
- }
- return r;
+ for (int c = 0; c < dirtyWidgets.size(); ++c)
+ resetWidget(dirtyWidgets.at(c));
+ for (int c = 0; c < dirtyRenderToTextureWidgets.size(); ++c)
+ resetWidget(dirtyRenderToTextureWidgets.at(c));
}
/*!
- Returns the static content inside the \a parent if non-zero; otherwise the static content
- for the entire backing store is returned. The content will be clipped to \a withinClipRect
- if non-empty.
+ \internal
+ Invalidates the \a r (in widget's coordinates) of the backing store, i.e.
+ all widgets intersecting with the region will be repainted when the backing
+ store is synced.
*/
-QRegion QWidgetBackingStore::staticContents(QWidget *parent, const QRect &withinClipRect) const
+template <class T>
+void QWidgetPrivate::invalidateBackingStore(const T &r)
{
- if (!parent && tlw->testAttribute(Qt::WA_StaticContents)) {
- const QSize surfaceGeometry(store->size());
- QRect surfaceRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
- if (!withinClipRect.isEmpty())
- surfaceRect &= withinClipRect;
- return QRegion(surfaceRect);
- }
-
- QRegion region;
- if (parent && parent->d_func()->children.isEmpty())
- return region;
-
- const bool clipToRect = !withinClipRect.isEmpty();
- const int count = staticWidgets.count();
- for (int i = 0; i < count; ++i) {
- QWidget *w = staticWidgets.at(i);
- QWidgetPrivate *wd = w->d_func();
- if (!wd->isOpaque || !wd->extra || wd->extra->staticContentsSize.isEmpty()
- || !w->isVisible() || (parent && !parent->isAncestorOf(w))) {
- continue;
- }
-
- QRect rect(0, 0, wd->extra->staticContentsSize.width(), wd->extra->staticContentsSize.height());
- const QPoint offset = w->mapTo(parent ? parent : tlw, QPoint());
- if (clipToRect)
- rect &= withinClipRect.translated(-offset);
- if (rect.isEmpty())
- continue;
-
- rect &= wd->clipRect();
- if (rect.isEmpty())
- continue;
+ if (r.isEmpty())
+ return;
- QRegion visible(rect);
- wd->clipToEffectiveMask(visible);
- if (visible.isEmpty())
- continue;
- wd->subtractOpaqueSiblings(visible, 0, /*alsoNonOpaque=*/true);
+ if (QCoreApplication::closingDown())
+ return;
- visible.translate(offset);
- region += visible;
- }
+ Q_Q(QWidget);
+ if (!q->isVisible() || !q->updatesEnabled())
+ return;
- return region;
-}
+ QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
+ if (!tlwExtra || tlwExtra->inTopLevelResize || !tlwExtra->backingStore)
+ return;
-void QWidgetBackingStore::sendUpdateRequest(QWidget *widget, UpdateTime updateTime)
-{
- if (!widget)
+ T clipped(r);
+ clipped &= clipRect();
+ if (clipped.isEmpty())
return;
-#ifndef QT_NO_OPENGL
- // Having every repaint() leading to a sync/flush is bad as it causes
- // compositing and waiting for vsync each and every time. Change to
- // UpdateLater, except for approx. once per frame to prevent starvation in
- // case the control does not get back to the event loop.
- QWidget *w = widget->window();
- if (updateTime == UpdateNow && w && w->windowHandle() && QWindowPrivate::get(w->windowHandle())->compositing) {
- int refresh = 60;
- QScreen *ws = w->windowHandle()->screen();
- if (ws)
- refresh = ws->refreshRate();
- QWindowPrivate *wd = QWindowPrivate::get(w->windowHandle());
- if (wd->lastComposeTime.isValid()) {
- const qint64 elapsed = wd->lastComposeTime.elapsed();
- if (elapsed <= qint64(1000.0f / refresh))
- updateTime = UpdateLater;
- }
- }
-#endif
+ if (!graphicsEffect && extra && extra->hasMask) {
+ QRegion masked(extra->mask);
+ masked &= clipped;
+ if (masked.isEmpty())
+ return;
- switch (updateTime) {
- case UpdateLater:
- updateRequestSent = true;
- QApplication::postEvent(widget, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority);
- break;
- case UpdateNow: {
- QEvent event(QEvent::UpdateRequest);
- QApplication::sendEvent(widget, &event);
- break;
- }
+ tlwExtra->repaintManager->markDirty(masked, q,
+ QWidgetRepaintManager::UpdateLater, QWidgetRepaintManager::BufferInvalid);
+ } else {
+ tlwExtra->repaintManager->markDirty(clipped, q,
+ QWidgetRepaintManager::UpdateLater, QWidgetRepaintManager::BufferInvalid);
}
}
+// Needed by tst_QWidget
+template Q_AUTOTEST_EXPORT void QWidgetPrivate::invalidateBackingStore<QRect>(const QRect &r);
static inline QRect widgetRectFor(QWidget *, const QRect &r) { return r; }
static inline QRect widgetRectFor(QWidget *widget, const QRegion &) { return widget->rect(); }
/*!
+ \internal
Marks the region of the widget as dirty (if not already marked as dirty) and
posts an UpdateRequest event to the top-level widget (if not already posted).
@@ -527,8 +206,11 @@ static inline QRect widgetRectFor(QWidget *widget, const QRegion &) { return wid
instead of the top-level widget, and bufferState is completely ignored.
*/
template <class T>
-void QWidgetBackingStore::markDirty(const T &r, QWidget *widget, UpdateTime updateTime, BufferState bufferState)
+void QWidgetRepaintManager::markDirty(const T &r, QWidget *widget, UpdateTime updateTime, BufferState bufferState)
{
+ qCInfo(lcWidgetPainting) << "Marking" << r << "of" << widget << "dirty"
+ << "with" << updateTime;
+
Q_ASSERT(tlw->d_func()->extra);
Q_ASSERT(tlw->d_func()->extra->topextra);
Q_ASSERT(!tlw->d_func()->extra->topextra->inTopLevelResize);
@@ -544,7 +226,7 @@ void QWidgetBackingStore::markDirty(const T &r, QWidget *widget, UpdateTime upda
// ---------------------------------------------------------------------------
- if (widget->d_func()->paintOnScreen()) {
+ if (widget->d_func()->shouldPaintOnScreen()) {
if (widget->d_func()->dirty.isEmpty()) {
widget->d_func()->dirty = r;
sendUpdateRequest(widget, updateTime);
@@ -631,70 +313,35 @@ void QWidgetBackingStore::markDirty(const T &r, QWidget *widget, UpdateTime upda
if (updateTime == UpdateNow)
sendUpdateRequest(tlw, updateTime);
}
-template void QWidgetBackingStore::markDirty<QRect>(const QRect &, QWidget *, UpdateTime, BufferState);
-template void QWidgetBackingStore::markDirty<QRegion>(const QRegion &, QWidget *, UpdateTime, BufferState);
+template void QWidgetRepaintManager::markDirty<QRect>(const QRect &, QWidget *, UpdateTime, BufferState);
+template void QWidgetRepaintManager::markDirty<QRegion>(const QRegion &, QWidget *, UpdateTime, BufferState);
-/*!
- Marks the \a region of the \a widget as dirty on screen. The \a region will be copied from
- the backing store to the \a widget's native parent next time flush() is called.
-
- Paint on screen widgets are ignored.
-*/
-void QWidgetBackingStore::markDirtyOnScreen(const QRegion &region, QWidget *widget, const QPoint &topLevelOffset)
+void QWidgetRepaintManager::addDirtyWidget(QWidget *widget, const QRegion &rgn)
{
- if (!widget || widget->d_func()->paintOnScreen() || region.isEmpty())
- return;
-
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region.translated(topLevelOffset);
- return;
-#endif
-
- // Top-level.
- if (widget == tlw) {
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region;
- return;
- }
-
- // Alien widgets.
- if (!hasPlatformWindow(widget) && !widget->isWindow()) {
- QWidget *nativeParent = widget->nativeParentWidget(); // Alien widgets with the top-level as the native parent (common case).
- if (nativeParent == tlw) {
- if (!widget->testAttribute(Qt::WA_WState_InPaintEvent))
- dirtyOnScreen += region.translated(topLevelOffset);
- return;
- }
-
- // Alien widgets with native parent != tlw.
- QWidgetPrivate *nativeParentPrivate = nativeParent->d_func();
- if (!nativeParentPrivate->needsFlush)
- nativeParentPrivate->needsFlush = new QRegion;
- const QPoint nativeParentOffset = widget->mapTo(nativeParent, QPoint());
- *nativeParentPrivate->needsFlush += region.translated(nativeParentOffset);
- appendDirtyOnScreenWidget(nativeParent);
- return;
+ if (widget && !widget->d_func()->inDirtyList && !widget->data->in_destructor) {
+ QWidgetPrivate *widgetPrivate = widget->d_func();
+#if QT_CONFIG(graphicseffect)
+ if (widgetPrivate->graphicsEffect)
+ widgetPrivate->dirty = widgetPrivate->effectiveRectFor(rgn.boundingRect());
+ else
+#endif // QT_CONFIG(graphicseffect)
+ widgetPrivate->dirty = rgn;
+ dirtyWidgets.append(widget);
+ widgetPrivate->inDirtyList = true;
}
-
- // Native child widgets.
- QWidgetPrivate *widgetPrivate = widget->d_func();
- if (!widgetPrivate->needsFlush)
- widgetPrivate->needsFlush = new QRegion;
- *widgetPrivate->needsFlush += region;
- appendDirtyOnScreenWidget(widget);
}
-void QWidgetBackingStore::removeDirtyWidget(QWidget *w)
+void QWidgetRepaintManager::removeDirtyWidget(QWidget *w)
{
if (!w)
return;
- dirtyWidgetsRemoveAll(w);
- dirtyOnScreenWidgetsRemoveAll(w);
+ dirtyWidgets.removeAll(w);
dirtyRenderToTextureWidgets.removeAll(w);
resetWidget(w);
+ needsFlushWidgets.removeAll(w);
+
QWidgetPrivate *wd = w->d_func();
const int n = wd->children.count();
for (int i = 0; i < n; ++i) {
@@ -703,46 +350,71 @@ void QWidgetBackingStore::removeDirtyWidget(QWidget *w)
}
}
-void QWidgetBackingStore::updateLists(QWidget *cur)
+void QWidgetRepaintManager::resetWidget(QWidget *widget)
{
- if (!cur)
- return;
-
- QList<QObject*> children = cur->children();
- for (int i = 0; i < children.size(); ++i) {
- QWidget *child = qobject_cast<QWidget*>(children.at(i));
- if (!child || child->isWindow())
- continue;
-
- updateLists(child);
+ if (widget) {
+ widget->d_func()->inDirtyList = false;
+ widget->d_func()->isScrolled = false;
+ widget->d_func()->isMoved = false;
+ widget->d_func()->dirty = QRegion();
}
+}
- if (cur->testAttribute(Qt::WA_StaticContents))
- addStaticWidget(cur);
+void QWidgetRepaintManager::addDirtyRenderToTextureWidget(QWidget *widget)
+{
+ if (widget && !widget->d_func()->inDirtyList && !widget->data->in_destructor) {
+ QWidgetPrivate *widgetPrivate = widget->d_func();
+ Q_ASSERT(widgetPrivate->renderToTexture);
+ dirtyRenderToTextureWidgets.append(widget);
+ widgetPrivate->inDirtyList = true;
+ }
}
-QWidgetBackingStore::QWidgetBackingStore(QWidget *topLevel)
- : tlw(topLevel),
- dirtyOnScreenWidgets(0),
- updateRequestSent(0),
- textureListWatcher(0),
- perfFrames(0)
+void QWidgetRepaintManager::sendUpdateRequest(QWidget *widget, UpdateTime updateTime)
{
- store = tlw->backingStore();
- Q_ASSERT(store);
+ if (!widget)
+ return;
- // Ensure all existing subsurfaces and static widgets are added to their respective lists.
- updateLists(topLevel);
+ qCInfo(lcWidgetPainting) << "Sending update request to" << widget << "with" << updateTime;
+
+#ifndef QT_NO_OPENGL
+ // Having every repaint() leading to a sync/flush is bad as it causes
+ // compositing and waiting for vsync each and every time. Change to
+ // UpdateLater, except for approx. once per frame to prevent starvation in
+ // case the control does not get back to the event loop.
+ QWidget *w = widget->window();
+ if (updateTime == UpdateNow && w && w->windowHandle() && QWindowPrivate::get(w->windowHandle())->compositing) {
+ int refresh = 60;
+ QScreen *ws = w->windowHandle()->screen();
+ if (ws)
+ refresh = ws->refreshRate();
+ QWindowPrivate *wd = QWindowPrivate::get(w->windowHandle());
+ if (wd->lastComposeTime.isValid()) {
+ const qint64 elapsed = wd->lastComposeTime.elapsed();
+ if (elapsed <= qint64(1000.0f / refresh))
+ updateTime = UpdateLater;
+ }
+ }
+#endif
+
+ switch (updateTime) {
+ case UpdateLater:
+ updateRequestSent = true;
+ QCoreApplication::postEvent(widget, new QEvent(QEvent::UpdateRequest), Qt::LowEventPriority);
+ break;
+ case UpdateNow: {
+ QEvent event(QEvent::UpdateRequest);
+ QCoreApplication::sendEvent(widget, &event);
+ break;
+ }
+ }
}
-QWidgetBackingStore::~QWidgetBackingStore()
-{
- for (int c = 0; c < dirtyWidgets.size(); ++c)
- resetWidget(dirtyWidgets.at(c));
- for (int c = 0; c < dirtyRenderToTextureWidgets.size(); ++c)
- resetWidget(dirtyRenderToTextureWidgets.at(c));
+// ---------------------------------------------------------------------------
- delete dirtyOnScreenWidgets;
+static bool hasPlatformWindow(QWidget *widget)
+{
+ return widget && widget->windowHandle() && widget->windowHandle()->handle();
}
static QVector<QRect> getSortedRectsToScroll(const QRegion &region, int dx, int dy)
@@ -810,7 +482,7 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
invalidateBackingStore((newRect & clipR).translated(-data.crect.topLeft()));
} else {
- QWidgetBackingStore *wbs = x->backingStoreTracker.data();
+ QWidgetRepaintManager *repaintManager = x->repaintManager.get();
QRegion childExpose(newRect & clipR);
QRegion overlappedExpose;
@@ -822,7 +494,7 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
const QVector<QRect> rectsToScroll
= getSortedRectsToScroll(QRegion(sourceRect) - overlappedExpose, dx, dy);
for (QRect rect : rectsToScroll) {
- if (wbs->bltRect(rect, dx, dy, pw)) {
+ if (repaintManager->bltRect(rect, dx, dy, pw)) {
childExpose -= rect.translated(dx, dy);
}
}
@@ -842,7 +514,7 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
}
if (!childExpose.isEmpty()) {
childExpose.translate(-data.crect.topLeft());
- wbs->markDirty(childExpose, q);
+ repaintManager->markDirty(childExpose, q);
isMoved = true;
}
}
@@ -853,14 +525,14 @@ void QWidgetPrivate::moveRect(const QRect &rect, int dx, int dy)
parentExpose += QRegion(newRect) - extra->mask.translated(data.crect.topLeft());
if (!parentExpose.isEmpty()) {
- wbs->markDirty(parentExpose, pw);
+ repaintManager->markDirty(parentExpose, pw);
pd->isMoved = true;
}
if (childUpdatesEnabled) {
QRegion needsFlush(sourceRect);
needsFlush += destRect;
- wbs->markDirtyOnScreen(needsFlush, pw, toplevelOffset);
+ repaintManager->markNeedsFlush(pw, needsFlush, toplevelOffset);
}
}
}
@@ -874,8 +546,8 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
if (x->inTopLevelResize)
return;
- QWidgetBackingStore *wbs = x->backingStoreTracker.data();
- if (!wbs)
+ QWidgetRepaintManager *repaintManager = x->repaintManager.get();
+ if (!repaintManager)
return;
static const bool accelEnv = qEnvironmentVariableIntValue("QT_NO_FAST_SCROLL") == 0;
@@ -906,7 +578,7 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
const QVector<QRect> rectsToScroll
= getSortedRectsToScroll(QRegion(sourceRect) - overlappedExpose, dx, dy);
for (const QRect &rect : rectsToScroll) {
- if (wbs->bltRect(rect, dx, dy, q)) {
+ if (repaintManager->bltRect(rect, dx, dy, q)) {
childExpose -= rect.translated(dx, dy);
}
}
@@ -933,17 +605,32 @@ void QWidgetPrivate::scrollRect(const QRect &rect, int dx, int dy)
if (!overlappedExpose.isEmpty())
invalidateBackingStore(overlappedExpose);
if (!childExpose.isEmpty()) {
- wbs->markDirty(childExpose, q);
+ repaintManager->markDirty(childExpose, q);
isScrolled = true;
}
// Instead of using native scroll-on-screen, we copy from
// backingstore, giving only one screen update for each
// scroll, and a solid appearance
- wbs->markDirtyOnScreen(destRect, q, toplevelOffset);
+ repaintManager->markNeedsFlush(q, destRect, toplevelOffset);
}
}
+/*
+ Moves the whole rect by (dx, dy) in widget's coordinate system.
+ Doesn't generate any updates.
+*/
+bool QWidgetRepaintManager::bltRect(const QRect &rect, int dx, int dy, QWidget *widget)
+{
+ const QPoint pos(widget->mapTo(tlw, rect.topLeft()));
+ const QRect tlwRect(QRect(pos, rect.size()));
+ if (dirty.intersects(tlwRect))
+ return false; // We don't want to scroll junk.
+ return store->scroll(tlwRect, dx, dy);
+}
+
+// ---------------------------------------------------------------------------
+
#ifndef QT_NO_OPENGL
static void findTextureWidgetsRecursively(QWidget *tlw, QWidget *widget, QPlatformTextureList *widgetTextures, QVector<QWidget *> *nativeChildren)
{
@@ -969,15 +656,15 @@ static void findAllTextureWidgetsRecursively(QWidget *tlw, QWidget *widget)
// textureChildSeen does not take native child widgets into account and that's good.
if (QWidgetPrivate::get(widget)->textureChildSeen) {
QVector<QWidget *> nativeChildren;
- QScopedPointer<QPlatformTextureList> tl(new QPlatformTextureList);
+ auto tl = qt_make_unique<QPlatformTextureList>();
// Look for texture widgets (incl. widget itself) from 'widget' down,
// but skip subtrees with a parent of a native child widget.
- findTextureWidgetsRecursively(tlw, widget, tl.data(), &nativeChildren);
+ findTextureWidgetsRecursively(tlw, widget, tl.get(), &nativeChildren);
// tl may be empty regardless of textureChildSeen if we have native or hidden children.
if (!tl->isEmpty())
- QWidgetPrivate::get(tlw)->topData()->widgetTextures.append(tl.take());
+ QWidgetPrivate::get(tlw)->topData()->widgetTextures.push_back(std::move(tl));
// Native child widgets, if there was any, get their own separate QPlatformTextureList.
- foreach (QWidget *ncw, nativeChildren) {
+ for (QWidget *ncw : qAsConst(nativeChildren)) {
if (QWidgetPrivate::get(ncw)->textureChildSeen)
findAllTextureWidgetsRecursively(tlw, ncw);
}
@@ -986,12 +673,12 @@ static void findAllTextureWidgetsRecursively(QWidget *tlw, QWidget *widget)
static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
{
- foreach (QPlatformTextureList *tl, QWidgetPrivate::get(tlw)->topData()->widgetTextures) {
+ for (const auto &tl : QWidgetPrivate::get(tlw)->topData()->widgetTextures) {
Q_ASSERT(!tl->isEmpty());
for (int i = 0; i < tl->count(); ++i) {
QWidget *w = static_cast<QWidget *>(tl->source(i));
if ((hasPlatformWindow(w) && w == widget) || (!hasPlatformWindow(w) && w->nativeParentWidget() == widget))
- return tl;
+ return tl.get();
}
}
@@ -1011,39 +698,6 @@ static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
return 0;
}
-// Watches one or more QPlatformTextureLists for changes in the lock state and
-// triggers a backingstore sync when all the registered lists turn into
-// unlocked state. This is essential when a custom composeAndFlush()
-// implementation in a platform plugin is not synchronous and keeps
-// holding on to the textures for some time even after returning from there.
-QPlatformTextureListWatcher::QPlatformTextureListWatcher(QWidgetBackingStore *backingStore)
- : m_backingStore(backingStore)
-{
-}
-
-void QPlatformTextureListWatcher::watch(QPlatformTextureList *textureList)
-{
- connect(textureList, SIGNAL(locked(bool)), SLOT(onLockStatusChanged(bool)));
- m_locked[textureList] = textureList->isLocked();
-}
-
-bool QPlatformTextureListWatcher::isLocked() const
-{
- foreach (bool v, m_locked) {
- if (v)
- return true;
- }
- return false;
-}
-
-void QPlatformTextureListWatcher::onLockStatusChanged(bool locked)
-{
- QPlatformTextureList *tl = static_cast<QPlatformTextureList *>(sender());
- m_locked[tl] = locked;
- if (!isLocked())
- m_backingStore->sync();
-}
-
#else
static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
@@ -1055,48 +709,19 @@ static QPlatformTextureList *widgetTexturesFor(QWidget *tlw, QWidget *widget)
#endif // QT_NO_OPENGL
-static inline bool discardSyncRequest(QWidget *tlw, QTLWExtra *tlwExtra)
-{
- if (!tlw || !tlwExtra || !tlw->testAttribute(Qt::WA_Mapped) || !tlw->isVisible())
- return true;
-
- return false;
-}
-
-bool QWidgetBackingStore::syncAllowed()
-{
-#ifndef QT_NO_OPENGL
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (textureListWatcher && !textureListWatcher->isLocked()) {
- textureListWatcher->deleteLater();
- textureListWatcher = 0;
- } else if (!tlwExtra->widgetTextures.isEmpty()) {
- bool skipSync = false;
- foreach (QPlatformTextureList *tl, tlwExtra->widgetTextures) {
- if (tl->isLocked()) {
- if (!textureListWatcher)
- textureListWatcher = new QPlatformTextureListWatcher(this);
- if (!textureListWatcher->isLocked())
- textureListWatcher->watch(tl);
- skipSync = true;
- }
- }
- if (skipSync) // cannot compose due to widget textures being in use
- return false;
- }
-#endif
- return true;
-}
+// ---------------------------------------------------------------------------
/*!
Synchronizes the \a exposedRegion of the \a exposedWidget with the backing store.
- If there's nothing to repaint, the area is flushed and painting does not occur;
- otherwise the area is marked as dirty on screen and will be flushed right after
- we are done with all painting.
+ If there are dirty widgets, including but not limited to the \a exposedWidget,
+ these will be repainted first. The backingstore is then flushed to the screen,
+ regardless of whether or not there were any repaints.
*/
-void QWidgetBackingStore::sync(QWidget *exposedWidget, const QRegion &exposedRegion)
+void QWidgetRepaintManager::sync(QWidget *exposedWidget, const QRegion &exposedRegion)
{
+ qCInfo(lcWidgetPainting) << "Syncing" << exposedRegion << "of" << exposedWidget;
+
QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
if (!tlw->isVisible() || !tlwExtra || tlwExtra->inTopLevelResize)
return;
@@ -1109,28 +734,30 @@ void QWidgetBackingStore::sync(QWidget *exposedWidget, const QRegion &exposedReg
// Nothing to repaint.
if (!isDirty() && store->size().isValid()) {
- QPlatformTextureList *tl = widgetTexturesFor(tlw, exposedWidget);
- qt_flush(exposedWidget, tl ? QRegion() : exposedRegion, store, tlw, tl, this);
+ QPlatformTextureList *widgetTextures = widgetTexturesFor(tlw, exposedWidget);
+ flush(exposedWidget, widgetTextures ? QRegion() : exposedRegion, widgetTextures);
return;
}
- if (exposedWidget != tlw)
- markDirtyOnScreen(exposedRegion, exposedWidget, exposedWidget->mapTo(tlw, QPoint()));
- else
- markDirtyOnScreen(exposedRegion, exposedWidget, QPoint());
+ // As requests to sync a specific widget typically comes from an expose event
+ // we can't rely solely on our own dirty tracking to decide what to flush, and
+ // need to respect the platform's request to at least flush the entire widget,
+ QPoint offset = exposedWidget != tlw ? exposedWidget->mapTo(tlw, QPoint()) : QPoint();
+ markNeedsFlush(exposedWidget, exposedRegion, offset);
if (syncAllowed())
- doSync();
+ paintAndFlush();
}
/*!
Synchronizes the backing store, i.e. dirty areas are repainted and flushed.
*/
-void QWidgetBackingStore::sync()
+void QWidgetRepaintManager::sync()
{
+ qCInfo(lcWidgetPainting) << "Syncing dirty widgets";
+
updateRequestSent = false;
- QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
- if (discardSyncRequest(tlw, tlwExtra)) {
+ if (qt_widget_private(tlw)->shouldDiscardSyncRequest()) {
// If the top-level is minimized, it's not visible on the screen so we can delay the
// update until it's shown again. In order to do that we must keep the dirty states.
// These will be cleared when we receive the first expose after showNormal().
@@ -1146,16 +773,50 @@ void QWidgetBackingStore::sync()
}
if (syncAllowed())
- doSync();
+ paintAndFlush();
}
-void QWidgetBackingStore::doSync()
+bool QWidgetPrivate::shouldDiscardSyncRequest() const
{
+ Q_Q(const QWidget);
+ return !maybeTopData() || !q->testAttribute(Qt::WA_Mapped) || !q->isVisible();
+}
+
+bool QWidgetRepaintManager::syncAllowed()
+{
+#ifndef QT_NO_OPENGL
+ QTLWExtra *tlwExtra = tlw->d_func()->maybeTopData();
+ if (textureListWatcher && !textureListWatcher->isLocked()) {
+ textureListWatcher->deleteLater();
+ textureListWatcher = 0;
+ } else if (!tlwExtra->widgetTextures.empty()) {
+ bool skipSync = false;
+ for (const auto &tl : tlwExtra->widgetTextures) {
+ if (tl->isLocked()) {
+ if (!textureListWatcher)
+ textureListWatcher = new QPlatformTextureListWatcher(this);
+ if (!textureListWatcher->isLocked())
+ textureListWatcher->watch(tl.get());
+ skipSync = true;
+ }
+ }
+ if (skipSync) // cannot compose due to widget textures being in use
+ return false;
+ }
+#endif
+ return true;
+}
+
+void QWidgetRepaintManager::paintAndFlush()
+{
+ qCInfo(lcWidgetPainting) << "Painting and flushing dirty"
+ << "top level" << dirty << "and dirty widgets" << dirtyWidgets;
+
const bool updatesDisabled = !tlw->updatesEnabled();
bool repaintAllWidgets = false;
const bool inTopLevelResize = tlw->d_func()->maybeTopData()->inTopLevelResize;
- const QRect tlwRect(topLevelRect());
+ const QRect tlwRect = tlw->data->crect;
const QRect surfaceGeometry(tlwRect.topLeft(), store->size());
if ((inTopLevelResize || surfaceGeometry.size() != tlwRect.size()) && !updatesDisabled) {
if (hasStaticContents() && !store->size().isEmpty() ) {
@@ -1249,10 +910,9 @@ void QWidgetBackingStore::doSync()
// The search is cut at native widget boundaries, meaning that each native child widget
// has its own list for the subtree below it.
QTLWExtra *tlwExtra = tlw->d_func()->topData();
- qDeleteAll(tlwExtra->widgetTextures);
tlwExtra->widgetTextures.clear();
findAllTextureWidgetsRecursively(tlw, tlw);
- qt_window_private(tlw->windowHandle())->compositing = false; // will get updated in qt_flush()
+ qt_window_private(tlw->windowHandle())->compositing = false; // will get updated in flush()
#endif
if (toClean.isEmpty()) {
@@ -1278,10 +938,7 @@ void QWidgetBackingStore::doSync()
if (hasPlatformWindow(w) || (npw && npw != tlw)) {
if (!hasPlatformWindow(w))
w = npw;
- QWidgetPrivate *wPrivate = w->d_func();
- if (!wPrivate->needsFlush)
- wPrivate->needsFlush = new QRegion;
- appendDirtyOnScreenWidget(w);
+ markNeedsFlush(w);
}
}
}
@@ -1295,7 +952,7 @@ void QWidgetBackingStore::doSync()
}
#ifndef QT_NO_OPENGL
- foreach (QPlatformTextureList *tl, tlwExtra->widgetTextures) {
+ for (const auto &tl : tlwExtra->widgetTextures) {
for (int i = 0; i < tl->count(); ++i) {
QWidget *w = static_cast<QWidget *>(tl->source(i));
if (dirtyRenderToTextureWidgets.contains(w)) {
@@ -1324,15 +981,7 @@ void QWidgetBackingStore::doSync()
}
#endif
- BeginPaintInfo beginPaintInfo;
- beginPaint(toClean, tlw, store, &beginPaintInfo);
- if (beginPaintInfo.nothingToPaint) {
- for (int i = 0; i < opaqueNonOverlappedWidgets.size(); ++i)
- resetWidget(opaqueNonOverlappedWidgets[i]);
- dirty = QRegion();
- updateRequestSent = false;
- return;
- }
+ store->beginPaint(toClean);
// Must do this before sending any paint events because
// the size may change in the paint event.
@@ -1346,7 +995,7 @@ void QWidgetBackingStore::doSync()
QWidget *w = opaqueNonOverlappedWidgets[i];
QWidgetPrivate *wd = w->d_func();
- int flags = QWidgetPrivate::DrawRecursive;
+ QWidgetPrivate::DrawWidgetFlags flags = QWidgetPrivate::DrawRecursive;
// Scrolled and moved widgets must draw all children.
if (!wd->isScrolled && !wd->isMoved)
flags |= QWidgetPrivate::DontDrawOpaqueChildren;
@@ -1364,56 +1013,301 @@ void QWidgetBackingStore::doSync()
// Paint the rest with composition.
if (repaintAllWidgets || !dirtyCopy.isEmpty()) {
- const int flags = QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawRecursive;
+ QWidgetPrivate::DrawWidgetFlags flags = QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawRecursive;
tlw->d_func()->drawWidget(store->paintDevice(), dirtyCopy, QPoint(), flags, 0, this);
}
- endPaint(toClean, store, &beginPaintInfo);
+ store->endPaint();
+
+ flush();
+}
+
+/*!
+ Marks the \a region of the \a widget as needing a flush. The \a region will be copied from
+ the backing store to the \a widget's native parent next time flush() is called.
+
+ Paint on screen widgets are ignored.
+*/
+void QWidgetRepaintManager::markNeedsFlush(QWidget *widget, const QRegion &region, const QPoint &topLevelOffset)
+{
+ if (!widget || widget->d_func()->shouldPaintOnScreen() || region.isEmpty())
+ return;
+
+ if (widget == tlw) {
+ // Top-level (native)
+ qCInfo(lcWidgetPainting) << "Marking" << region << "of top level"
+ << widget << "as needing flush";
+ topLevelNeedsFlush += region;
+ } else if (!hasPlatformWindow(widget) && !widget->isWindow()) {
+ QWidget *nativeParent = widget->nativeParentWidget();
+ qCInfo(lcWidgetPainting) << "Marking" << region << "of"
+ << widget << "as needing flush in" << nativeParent
+ << "at offset" << topLevelOffset;
+ if (nativeParent == tlw) {
+ // Alien widgets with the top-level as the native parent (common case)
+ topLevelNeedsFlush += region.translated(topLevelOffset);
+ } else {
+ // Alien widgets with native parent != tlw
+ const QPoint nativeParentOffset = widget->mapTo(nativeParent, QPoint());
+ markNeedsFlush(nativeParent, region.translated(nativeParentOffset));
+ }
+ } else {
+ // Native child widgets
+ qCInfo(lcWidgetPainting) << "Marking" << region
+ << "of native child" << widget << "as needing flush";
+ markNeedsFlush(widget, region);
+ }
+}
+
+void QWidgetRepaintManager::markNeedsFlush(QWidget *widget, const QRegion &region)
+{
+ if (!widget)
+ return;
+
+ auto *widgetPrivate = qt_widget_private(widget);
+ if (!widgetPrivate->needsFlush)
+ widgetPrivate->needsFlush = new QRegion;
+
+ *widgetPrivate->needsFlush += region;
+
+ if (!needsFlushWidgets.contains(widget))
+ needsFlushWidgets.append(widget);
}
/*!
Flushes the contents of the backing store into the top-level widget.
- If the \a widget is non-zero, the content is flushed to the \a widget.
- If the \a surface is non-zero, the content of the \a surface is flushed.
*/
-void QWidgetBackingStore::flush(QWidget *widget)
+void QWidgetRepaintManager::flush()
{
- const bool hasDirtyOnScreenWidgets = dirtyOnScreenWidgets && !dirtyOnScreenWidgets->isEmpty();
+ qCInfo(lcWidgetPainting) << "Flushing top level"
+ << topLevelNeedsFlush << "and children" << needsFlushWidgets;
+
+ const bool hasNeedsFlushWidgets = !needsFlushWidgets.isEmpty();
bool flushed = false;
- // Flush the region in dirtyOnScreen.
- if (!dirtyOnScreen.isEmpty()) {
- QWidget *target = widget ? widget : tlw;
- qt_flush(target, dirtyOnScreen, store, tlw, widgetTexturesFor(tlw, tlw), this);
- dirtyOnScreen = QRegion();
+ // Flush the top level widget
+ if (!topLevelNeedsFlush.isEmpty()) {
+ flush(tlw, topLevelNeedsFlush, widgetTexturesFor(tlw, tlw));
+ topLevelNeedsFlush = QRegion();
flushed = true;
}
- // Render-to-texture widgets are not in dirtyOnScreen so flush if we have not done it above.
- if (!flushed && !hasDirtyOnScreenWidgets) {
+ // Render-to-texture widgets are not in topLevelNeedsFlush so flush if we have not done it above.
+ if (!flushed && !hasNeedsFlushWidgets) {
#ifndef QT_NO_OPENGL
- if (!tlw->d_func()->topData()->widgetTextures.isEmpty()) {
- QPlatformTextureList *tl = widgetTexturesFor(tlw, tlw);
- if (tl) {
- QWidget *target = widget ? widget : tlw;
- qt_flush(target, QRegion(), store, tlw, tl, this);
- }
+ if (!tlw->d_func()->topData()->widgetTextures.empty()) {
+ if (QPlatformTextureList *widgetTextures = widgetTexturesFor(tlw, tlw))
+ flush(tlw, QRegion(), widgetTextures);
}
#endif
}
- if (!hasDirtyOnScreenWidgets)
+ if (!hasNeedsFlushWidgets)
return;
- for (int i = 0; i < dirtyOnScreenWidgets->size(); ++i) {
- QWidget *w = dirtyOnScreenWidgets->at(i);
+ for (QWidget *w : qExchange(needsFlushWidgets, {})) {
QWidgetPrivate *wd = w->d_func();
Q_ASSERT(wd->needsFlush);
QPlatformTextureList *widgetTexturesForNative = wd->textureChildSeen ? widgetTexturesFor(tlw, w) : 0;
- qt_flush(w, *wd->needsFlush, store, tlw, widgetTexturesForNative, this);
+ flush(w, *wd->needsFlush, widgetTexturesForNative);
*wd->needsFlush = QRegion();
}
- dirtyOnScreenWidgets->clear();
+}
+
+/*
+ Flushes the contents of the backingstore into the screen area of \a widget.
+
+ \a region is the region to be updated in \a widget coordinates.
+ */
+void QWidgetRepaintManager::flush(QWidget *widget, const QRegion &region, QPlatformTextureList *widgetTextures)
+{
+#ifdef QT_NO_OPENGL
+ Q_UNUSED(widgetTextures);
+ Q_ASSERT(!region.isEmpty());
+#else
+ Q_ASSERT(!region.isEmpty() || widgetTextures);
+#endif
+ Q_ASSERT(widget);
+ Q_ASSERT(tlw);
+
+ if (tlw->testAttribute(Qt::WA_DontShowOnScreen) || widget->testAttribute(Qt::WA_DontShowOnScreen))
+ return;
+
+ // Foreign Windows do not have backing store content and must not be flushed
+ if (QWindow *widgetWindow = widget->windowHandle()) {
+ if (widgetWindow->type() == Qt::ForeignWindow)
+ return;
+ }
+
+ qCInfo(lcWidgetPainting) << "Flushing" << region << "of" << widget;
+
+ static bool fpsDebug = qEnvironmentVariableIntValue("QT_DEBUG_FPS");
+ if (fpsDebug) {
+ if (!perfFrames++)
+ perfTime.start();
+ if (perfTime.elapsed() > 5000) {
+ double fps = double(perfFrames * 1000) / perfTime.restart();
+ qDebug("FPS: %.1f\n", fps);
+ perfFrames = 0;
+ }
+ }
+
+ QPoint offset;
+ if (widget != tlw)
+ offset += widget->mapTo(tlw, QPoint());
+
+ QRegion effectiveRegion = region;
+#ifndef QT_NO_OPENGL
+ const bool compositionWasActive = widget->d_func()->renderToTextureComposeActive;
+ if (!widgetTextures) {
+ widget->d_func()->renderToTextureComposeActive = false;
+ // Detect the case of falling back to the normal flush path when no
+ // render-to-texture widgets are visible anymore. We will force one
+ // last flush to go through the OpenGL-based composition to prevent
+ // artifacts. The next flush after this one will use the normal path.
+ if (compositionWasActive)
+ widgetTextures = qt_dummy_platformTextureList;
+ } else {
+ widget->d_func()->renderToTextureComposeActive = true;
+ }
+ // When changing the composition status, make sure the dirty region covers
+ // the entire widget. Just having e.g. the shown/hidden render-to-texture
+ // widget's area marked as dirty is incorrect when changing flush paths.
+ if (compositionWasActive != widget->d_func()->renderToTextureComposeActive)
+ effectiveRegion = widget->rect();
+
+ // re-test since we may have been forced to this path via the dummy texture list above
+ if (widgetTextures) {
+ qt_window_private(tlw->windowHandle())->compositing = true;
+ widget->window()->d_func()->sendComposeStatus(widget->window(), false);
+ // A window may have alpha even when the app did not request
+ // WA_TranslucentBackground. Therefore the compositor needs to know whether the app intends
+ // to rely on translucency, in order to decide if it should clear to transparent or opaque.
+ const bool translucentBackground = widget->testAttribute(Qt::WA_TranslucentBackground);
+ store->handle()->composeAndFlush(widget->windowHandle(), effectiveRegion, offset,
+ widgetTextures, translucentBackground);
+ widget->window()->d_func()->sendComposeStatus(widget->window(), true);
+ } else
+#endif
+ store->flush(effectiveRegion, widget->windowHandle(), offset);
+}
+
+// ---------------------------------------------------------------------------
+
+void QWidgetRepaintManager::addStaticWidget(QWidget *widget)
+{
+ if (!widget)
+ return;
+
+ Q_ASSERT(widget->testAttribute(Qt::WA_StaticContents));
+ if (!staticWidgets.contains(widget))
+ staticWidgets.append(widget);
+}
+
+// Move the reparented widget and all its static children from this backing store
+// to the new backing store if reparented into another top-level / backing store.
+void QWidgetRepaintManager::moveStaticWidgets(QWidget *reparented)
+{
+ Q_ASSERT(reparented);
+ QWidgetRepaintManager *newPaintManager = reparented->d_func()->maybeRepaintManager();
+ if (newPaintManager == this)
+ return;
+
+ int i = 0;
+ while (i < staticWidgets.size()) {
+ QWidget *w = staticWidgets.at(i);
+ if (reparented == w || reparented->isAncestorOf(w)) {
+ staticWidgets.removeAt(i);
+ if (newPaintManager)
+ newPaintManager->addStaticWidget(w);
+ } else {
+ ++i;
+ }
+ }
+}
+
+void QWidgetRepaintManager::removeStaticWidget(QWidget *widget)
+{
+ staticWidgets.removeAll(widget);
+}
+
+bool QWidgetRepaintManager::hasStaticContents() const
+{
+#if defined(Q_OS_WIN)
+ return !staticWidgets.isEmpty();
+#else
+ return !staticWidgets.isEmpty() && false;
+#endif
+}
+
+/*!
+ Returns the static content inside the \a parent if non-zero; otherwise the static content
+ for the entire backing store is returned. The content will be clipped to \a withinClipRect
+ if non-empty.
+*/
+QRegion QWidgetRepaintManager::staticContents(QWidget *parent, const QRect &withinClipRect) const
+{
+ if (!parent && tlw->testAttribute(Qt::WA_StaticContents)) {
+ const QSize surfaceGeometry(store->size());
+ QRect surfaceRect(0, 0, surfaceGeometry.width(), surfaceGeometry.height());
+ if (!withinClipRect.isEmpty())
+ surfaceRect &= withinClipRect;
+ return QRegion(surfaceRect);
+ }
+
+ QRegion region;
+ if (parent && parent->d_func()->children.isEmpty())
+ return region;
+
+ const bool clipToRect = !withinClipRect.isEmpty();
+ const int count = staticWidgets.count();
+ for (int i = 0; i < count; ++i) {
+ QWidget *w = staticWidgets.at(i);
+ QWidgetPrivate *wd = w->d_func();
+ if (!wd->isOpaque || !wd->extra || wd->extra->staticContentsSize.isEmpty()
+ || !w->isVisible() || (parent && !parent->isAncestorOf(w))) {
+ continue;
+ }
+
+ QRect rect(0, 0, wd->extra->staticContentsSize.width(), wd->extra->staticContentsSize.height());
+ const QPoint offset = w->mapTo(parent ? parent : tlw, QPoint());
+ if (clipToRect)
+ rect &= withinClipRect.translated(-offset);
+ if (rect.isEmpty())
+ continue;
+
+ rect &= wd->clipRect();
+ if (rect.isEmpty())
+ continue;
+
+ QRegion visible(rect);
+ wd->clipToEffectiveMask(visible);
+ if (visible.isEmpty())
+ continue;
+ wd->subtractOpaqueSiblings(visible, 0, /*alsoNonOpaque=*/true);
+
+ visible.translate(offset);
+ region += visible;
+ }
+
+ return region;
+}
+
+void QWidgetRepaintManager::updateStaticContentsSize()
+{
+ for (int i = 0; i < staticWidgets.size(); ++i) {
+ QWidgetPrivate *wd = staticWidgets.at(i)->d_func();
+ if (!wd->extra)
+ wd->createExtra();
+ wd->extra->staticContentsSize = wd->data.crect.size();
+ }
+}
+
+// ---------------------------------------------------------------------------
+
+bool QWidgetRepaintManager::isDirty() const
+{
+ return !(dirtyWidgets.isEmpty() && dirty.isEmpty() && dirtyRenderToTextureWidgets.isEmpty());
}
/*!
@@ -1437,8 +1331,8 @@ void QWidgetPrivate::invalidateBackingStore_resizeHelper(const QPoint &oldPos, c
if (!staticContents || graphicsEffect) {
QRegion staticChildren;
- QWidgetBackingStore *bs = 0;
- if (offset.isNull() && (bs = maybeBackingStore()))
+ QWidgetRepaintManager *bs = 0;
+ if (offset.isNull() && (bs = maybeRepaintManager()))
staticChildren = bs->staticContents(q, oldWidgetRect);
const bool hasStaticChildren = !staticChildren.isEmpty();
@@ -1508,101 +1402,6 @@ void QWidgetPrivate::invalidateBackingStore_resizeHelper(const QPoint &oldPos, c
}
}
-/*!
- Invalidates the \a r (in widget's coordinates) of the backing store, i.e.
- all widgets intersecting with the region will be repainted when the backing
- store is synced.
-*/
-template <class T>
-void QWidgetPrivate::invalidateBackingStore(const T &r)
-{
- if (r.isEmpty())
- return;
-
- if (QApplication::closingDown())
- return;
-
- Q_Q(QWidget);
- if (!q->isVisible() || !q->updatesEnabled())
- return;
-
- QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
- if (!tlwExtra || tlwExtra->inTopLevelResize || !tlwExtra->backingStore)
- return;
-
- T clipped(r);
- clipped &= clipRect();
- if (clipped.isEmpty())
- return;
-
- if (!graphicsEffect && extra && extra->hasMask) {
- QRegion masked(extra->mask);
- masked &= clipped;
- if (masked.isEmpty())
- return;
-
- tlwExtra->backingStoreTracker->markDirty(masked, q,
- QWidgetBackingStore::UpdateLater, QWidgetBackingStore::BufferInvalid);
- } else {
- tlwExtra->backingStoreTracker->markDirty(clipped, q,
- QWidgetBackingStore::UpdateLater, QWidgetBackingStore::BufferInvalid);
- }
-}
-// Needed by tst_QWidget
-template Q_AUTOTEST_EXPORT void QWidgetPrivate::invalidateBackingStore<QRect>(const QRect &r);
-
-void QWidgetPrivate::repaint_sys(const QRegion &rgn)
-{
- if (data.in_destructor)
- return;
-
- Q_Q(QWidget);
- if (discardSyncRequest(q, maybeTopData()))
- return;
-
- if (q->testAttribute(Qt::WA_StaticContents)) {
- if (!extra)
- createExtra();
- extra->staticContentsSize = data.crect.size();
- }
-
- QPaintEngine *engine = q->paintEngine();
-
- // QGLWidget does not support partial updates if:
- // 1) The context is double buffered
- // 2) The context is single buffered and auto-fill background is enabled.
- const bool noPartialUpdateSupport = (engine && (engine->type() == QPaintEngine::OpenGL
- || engine->type() == QPaintEngine::OpenGL2))
- && (usesDoubleBufferedGLContext || q->autoFillBackground());
- QRegion toBePainted(noPartialUpdateSupport ? q->rect() : rgn);
-
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // No difference between update() and repaint() on the Mac.
- update_sys(toBePainted);
- return;
-#endif
-
- toBePainted &= clipRect();
- clipToEffectiveMask(toBePainted);
- if (toBePainted.isEmpty())
- return; // Nothing to repaint.
-
-#ifndef QT_NO_PAINT_DEBUG
- bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
-#endif
-
- drawWidget(q, toBePainted, QPoint(), QWidgetPrivate::DrawAsRoot | QWidgetPrivate::DrawPaintOnScreen, 0);
-
-#ifndef QT_NO_PAINT_DEBUG
- if (flushed)
- QWidgetBackingStore::unflushPaint(q, toBePainted);
-#endif
-
- if (Q_UNLIKELY(q->paintingActive()))
- qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
-}
-
-
QT_END_NAMESPACE
-#include "moc_qwidgetbackingstore_p.cpp"
+#include "qwidgetrepaintmanager.moc"
diff --git a/src/widgets/kernel/qwidgetrepaintmanager_p.h b/src/widgets/kernel/qwidgetrepaintmanager_p.h
new file mode 100644
index 0000000000..58687383f4
--- /dev/null
+++ b/src/widgets/kernel/qwidgetrepaintmanager_p.h
@@ -0,0 +1,153 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtWidgets module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QWIDGETREPAINTMANAGER_P_H
+#define QWIDGETREPAINTMANAGER_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include <QDebug>
+#include <QtWidgets/qwidget.h>
+#include <private/qwidget_p.h>
+#include <QtGui/qbackingstore.h>
+
+QT_BEGIN_NAMESPACE
+
+class QPlatformTextureList;
+class QPlatformTextureListWatcher;
+class QWidgetRepaintManager;
+
+class Q_AUTOTEST_EXPORT QWidgetRepaintManager
+{
+ Q_GADGET
+public:
+ enum UpdateTime {
+ UpdateNow,
+ UpdateLater
+ };
+ Q_ENUM(UpdateTime)
+
+ enum BufferState{
+ BufferValid,
+ BufferInvalid
+ };
+ Q_ENUM(BufferState)
+
+ QWidgetRepaintManager(QWidget *t);
+ ~QWidgetRepaintManager();
+
+ QBackingStore *backingStore() const { return store; }
+ void setBackingStore(QBackingStore *backingStore) { store = backingStore; }
+
+ template <class T>
+ void markDirty(const T &r, QWidget *widget, UpdateTime updateTime = UpdateLater,
+ BufferState bufferState = BufferValid);
+
+ void removeDirtyWidget(QWidget *w);
+
+ void sync(QWidget *exposedWidget, const QRegion &exposedRegion);
+ void sync();
+
+ void markNeedsFlush(QWidget *widget, const QRegion &region, const QPoint &topLevelOffset);
+
+ void addStaticWidget(QWidget *widget);
+ void moveStaticWidgets(QWidget *reparented);
+ void removeStaticWidget(QWidget *widget);
+ QRegion staticContents(QWidget *widget = nullptr, const QRect &withinClipRect = QRect()) const;
+
+ bool bltRect(const QRect &rect, int dx, int dy, QWidget *widget);
+
+private:
+ void updateLists(QWidget *widget);
+
+ void addDirtyWidget(QWidget *widget, const QRegion &rgn);
+ void resetWidget(QWidget *widget);
+
+ void addDirtyRenderToTextureWidget(QWidget *widget);
+
+ void sendUpdateRequest(QWidget *widget, UpdateTime updateTime);
+
+ bool syncAllowed();
+ void paintAndFlush();
+
+ void markNeedsFlush(QWidget *widget, const QRegion &region = QRegion());
+
+ void flush();
+ void flush(QWidget *widget, const QRegion &region, QPlatformTextureList *widgetTextures);
+
+ bool isDirty() const;
+
+ bool hasStaticContents() const;
+ void updateStaticContentsSize();
+
+ QWidget *tlw = nullptr;
+ QBackingStore *store = nullptr;
+
+ QRegion dirty; // needsRepaint
+ QVector<QWidget *> dirtyWidgets;
+ QVector<QWidget *> dirtyRenderToTextureWidgets;
+
+ QRegion topLevelNeedsFlush;
+ QVector<QWidget *> needsFlushWidgets;
+
+ QList<QWidget *> staticWidgets;
+
+ QPlatformTextureListWatcher *textureListWatcher = nullptr;
+
+ bool updateRequestSent = false;
+
+ QElapsedTimer perfTime;
+ int perfFrames = 0;
+
+ Q_DISABLE_COPY_MOVE(QWidgetRepaintManager)
+};
+
+QT_END_NAMESPACE
+
+#endif // QWIDGETREPAINTMANAGER_P_H
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 878e484ab8..596343c52f 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -46,7 +46,7 @@
#ifndef QT_NO_ACCESSIBILITY
#include <QtGui/qaccessible.h>
#endif
-#include <private/qwidgetbackingstore_p.h>
+#include <private/qwidgetrepaintmanager_p.h>
#include <qpa/qwindowsysteminterface_p.h>
#include <qpa/qplatformtheme.h>
#include <qpa/qplatformwindow.h>
@@ -114,6 +114,7 @@ public:
if (QWidget *widget = q->widget())
QWidgetPrivate::get(widget)->updateContentsRect();
}
+ bool allowClickThrough(const QPoint &) const override;
};
QRectF QWidgetWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
@@ -162,7 +163,7 @@ QWidgetWindow::QWidgetWindow(QWidget *widget)
// Enable QOpenGLWidget/QQuickWidget children if the platform plugin supports it,
// and the application developer has not explicitly disabled it.
if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RasterGLSurface)
- && !QApplication::testAttribute(Qt::AA_ForceRasterWidgets)) {
+ && !QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets)) {
setSurfaceType(QSurface::RasterGLSurface);
}
connect(widget, &QObject::objectNameChanged, this, &QWidgetWindow::updateObjectName);
@@ -229,6 +230,11 @@ static inline bool shouldBePropagatedToWidget(QEvent *event)
}
}
+bool QWidgetWindowPrivate::allowClickThrough(const QPoint &) const
+{
+ return true;
+}
+
bool QWidgetWindow::event(QEvent *event)
{
if (!m_widget)
@@ -498,8 +504,8 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
static const QEvent::Type contextMenuTrigger =
QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ContextMenuOnMouseRelease).toBool() ?
QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
- if (qApp->d_func()->inPopupMode()) {
- QWidget *activePopupWidget = qApp->activePopupWidget();
+ if (QApplicationPrivate::inPopupMode()) {
+ QWidget *activePopupWidget = QApplication::activePopupWidget();
QPoint mapped = event->pos();
if (activePopupWidget != m_widget)
mapped = activePopupWidget->mapFromGlobal(event->globalPos());
@@ -579,7 +585,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
}
}
- if (qApp->activePopupWidget() != activePopupWidget
+ if (QApplication::activePopupWidget() != activePopupWidget
&& qt_replay_popup_mouse_event
&& QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::ReplayMousePressOutsidePopup).toBool()) {
if (m_widget->windowType() != Qt::Popup)
@@ -594,10 +600,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
w->window()->raise();
}
- QWindow *win = w->windowHandle();
- if (!win)
- win = w->nativeParentWidget()->windowHandle();
- if (win) {
+ if (auto win = qt_widget_private(w)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest)) {
const QRect globalGeometry = win->isTopLevel()
? win->geometry()
: QRect(win->mapToGlobal(QPoint(0, 0)), win->size());
@@ -685,7 +688,7 @@ void QWidgetWindow::handleTouchEvent(QTouchEvent *event)
if (event->type() == QEvent::TouchCancel) {
QApplicationPrivate::translateTouchCancel(event->device(), event->timestamp());
event->accept();
- } else if (qApp->d_func()->inPopupMode()) {
+ } else if (QApplicationPrivate::inPopupMode()) {
// Ignore touch events for popups. This will cause QGuiApplication to synthesise mouse
// events instead, which QWidgetWindow::handleMouseEvent will forward correctly:
event->ignore();
@@ -749,7 +752,7 @@ void QWidgetWindow::updateMargins()
static void sendScreenChangeRecursively(QWidget *widget)
{
QEvent e(QEvent::ScreenChangeInternal);
- QApplication::sendEvent(widget, &e);
+ QCoreApplication::sendEvent(widget, &e);
QWidgetPrivate *d = QWidgetPrivate::get(widget);
for (int i = 0; i < d->children.size(); ++i) {
QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
@@ -775,8 +778,8 @@ void QWidgetWindow::repaintWindow()
QTLWExtra *tlwExtra = m_widget->window()->d_func()->maybeTopData();
if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
- tlwExtra->backingStoreTracker->markDirty(m_widget->rect(), m_widget,
- QWidgetBackingStore::UpdateNow, QWidgetBackingStore::BufferInvalid);
+ tlwExtra->repaintManager->markDirty(m_widget->rect(), m_widget,
+ QWidgetRepaintManager::UpdateNow, QWidgetRepaintManager::BufferInvalid);
}
// Store normal geometry used for saving application settings.
@@ -808,7 +811,7 @@ void QWidgetWindow::handleResizeEvent(QResizeEvent *event)
if (updateSize()) {
QGuiApplication::forwardEvent(m_widget, event);
- if (m_widget->d_func()->paintOnScreen()) {
+ if (m_widget->d_func()->shouldPaintOnScreen()) {
QRegion updateRegion(geometry());
if (m_widget->testAttribute(Qt::WA_StaticContents))
updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
@@ -833,14 +836,14 @@ void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
return;
QWidget *rootWidget = m_widget;
- QPoint pos = event->pos();
+ QPoint pos = event->position().toPoint();
// Use proper popup window for wheel event. Some QPA sends the wheel
// event to the root menu, so redirect it to the proper popup window.
QWidget *activePopupWidget = QApplication::activePopupWidget();
if (activePopupWidget && activePopupWidget != m_widget) {
rootWidget = activePopupWidget;
- pos = rootWidget->mapFromGlobal(event->globalPos());
+ pos = rootWidget->mapFromGlobal(event->globalPosition().toPoint());
}
// which child should have it?
@@ -851,7 +854,12 @@ void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
QPoint mapped = widget->mapFrom(rootWidget, pos);
+#if QT_DEPRECATED_SINCE(5, 0)
QWheelEvent translated(mapped, event->globalPos(), event->pixelDelta(), event->angleDelta(), event->delta(), event->orientation(), event->buttons(), event->modifiers(), event->phase(), event->source(), event->inverted());
+#else
+ QWheelEvent translated(QPointF(mapped), event->globalPosition(), event->pixelDelta(), event->angleDelta(),
+ event->buttons(), event->modifiers(), event->phase(), event->inverted(), event->source());
+#endif
translated.setTimestamp(event->timestamp());
QGuiApplication::forwardEvent(widget, &translated, event);
}
@@ -1030,7 +1038,11 @@ void QWidgetWindow::handleWindowStateChangedEvent(QWindowStateChangeEvent *event
}
}
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
+#else
bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
+#endif
{
return m_widget->nativeEvent(eventType, message, result);
}
@@ -1108,7 +1120,7 @@ void QWidgetWindow::handleContextMenuEvent(QContextMenuEvent *e)
}
}
if (fw && fw->isEnabled()) {
- QPoint pos = fw->inputMethodQuery(Qt::ImMicroFocus).toRect().center();
+ QPoint pos = fw->inputMethodQuery(Qt::ImCursorRectangle).toRect().center();
QContextMenuEvent widgetEvent(QContextMenuEvent::Keyboard, pos, fw->mapToGlobal(pos),
e->modifiers());
QGuiApplication::forwardEvent(fw, &widgetEvent, e);
diff --git a/src/widgets/kernel/qwidgetwindow_p.h b/src/widgets/kernel/qwidgetwindow_p.h
index 0728135467..80a345465d 100644
--- a/src/widgets/kernel/qwidgetwindow_p.h
+++ b/src/widgets/kernel/qwidgetwindow_p.h
@@ -103,7 +103,11 @@ protected:
#endif
void handleExposeEvent(QExposeEvent *);
void handleWindowStateChangedEvent(QWindowStateChangeEvent *event);
+#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
+ bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
+#else
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
+#endif
#if QT_CONFIG(tabletevent)
void handleTabletEvent(QTabletEvent *);
#endif
diff --git a/src/widgets/kernel/qwindowcontainer.cpp b/src/widgets/kernel/qwindowcontainer.cpp
index 4b289d2d33..fd8581edbb 100644
--- a/src/widgets/kernel/qwindowcontainer.cpp
+++ b/src/widgets/kernel/qwindowcontainer.cpp
@@ -223,7 +223,7 @@ QWindowContainer::QWindowContainer(QWindow *embeddedWindow, QWidget *parent, Qt:
// Otherwise we may end up with BadMatch failures on X11.
if (embeddedWindow->surfaceType() == QSurface::RasterSurface
&& QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RasterGLSurface)
- && !QApplication::testAttribute(Qt::AA_ForceRasterWidgets))
+ && !QCoreApplication::testAttribute(Qt::AA_ForceRasterWidgets))
embeddedWindow->setSurfaceType(QSurface::RasterGLSurface);
d->window = embeddedWindow;
diff --git a/src/widgets/kernel/qwindowcontainer_p.h b/src/widgets/kernel/qwindowcontainer_p.h
index a8754232a8..c6de168c10 100644
--- a/src/widgets/kernel/qwindowcontainer_p.h
+++ b/src/widgets/kernel/qwindowcontainer_p.h
@@ -64,7 +64,7 @@ class Q_WIDGETS_EXPORT QWindowContainer : public QWidget
Q_DECLARE_PRIVATE(QWindowContainer)
public:
- explicit QWindowContainer(QWindow *embeddedWindow, QWidget *parent = 0, Qt::WindowFlags f = 0);
+ explicit QWindowContainer(QWindow *embeddedWindow, QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
~QWindowContainer();
QWindow *containedWindow() const;
diff --git a/src/widgets/kernel/win.pri b/src/widgets/kernel/win.pri
index f6877b02db..3b3170beb1 100644
--- a/src/widgets/kernel/win.pri
+++ b/src/widgets/kernel/win.pri
@@ -2,4 +2,7 @@
# --------------------------------------------------------------------
INCLUDEPATH += ../3rdparty/wintab
-!winrt: LIBS_PRIVATE *= -lshell32 -luxtheme -ldwmapi
+!winrt {
+ LIBS_PRIVATE *= -luxtheme -ldwmapi
+ QMAKE_USE_PRIVATE += shell32
+}
diff --git a/src/widgets/statemachine/qbasickeyeventtransition_p.h b/src/widgets/statemachine/qbasickeyeventtransition_p.h
index 7e1b978bba..f23c078570 100644
--- a/src/widgets/statemachine/qbasickeyeventtransition_p.h
+++ b/src/widgets/statemachine/qbasickeyeventtransition_p.h
@@ -63,11 +63,11 @@ class Q_AUTOTEST_EXPORT QBasicKeyEventTransition : public QAbstractTransition
{
Q_OBJECT
public:
- QBasicKeyEventTransition(QState *sourceState = 0);
- QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = 0);
+ QBasicKeyEventTransition(QState *sourceState = nullptr);
+ QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = nullptr);
QBasicKeyEventTransition(QEvent::Type type, int key,
Qt::KeyboardModifiers modifierMask,
- QState *sourceState = 0);
+ QState *sourceState = nullptr);
~QBasicKeyEventTransition();
QEvent::Type eventType() const;
diff --git a/src/widgets/statemachine/qbasicmouseeventtransition_p.h b/src/widgets/statemachine/qbasicmouseeventtransition_p.h
index 132e223535..dd619d189c 100644
--- a/src/widgets/statemachine/qbasicmouseeventtransition_p.h
+++ b/src/widgets/statemachine/qbasicmouseeventtransition_p.h
@@ -65,9 +65,9 @@ class Q_AUTOTEST_EXPORT QBasicMouseEventTransition : public QAbstractTransition
{
Q_OBJECT
public:
- QBasicMouseEventTransition(QState *sourceState = 0);
+ QBasicMouseEventTransition(QState *sourceState = nullptr);
QBasicMouseEventTransition(QEvent::Type type, Qt::MouseButton button,
- QState *sourceState = 0);
+ QState *sourceState = nullptr);
~QBasicMouseEventTransition();
QEvent::Type eventType() const;
diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp
index 35b630cde2..271b43fe89 100644
--- a/src/widgets/styles/qcommonstyle.cpp
+++ b/src/widgets/styles/qcommonstyle.cpp
@@ -116,10 +116,7 @@
#include <limits.h>
-#if QT_CONFIG(itemviews)
-# include "private/qtextengine_p.h"
-#endif
-
+#include <private/qtextengine_p.h>
#include <private/qstylehelper_p.h>
QT_BEGIN_NAMESPACE
@@ -1256,12 +1253,12 @@ void QCommonStylePrivate::tabLayout(const QStyleOptionTab *opt, const QWidget *w
*iconRect = QRect(tr.left() + offsetX, tr.center().y() - tabIconSize.height() / 2,
tabIconSize.width(), tabIconSize.height());
if (!verticalTabs)
- *iconRect = proxyStyle->visualRect(opt->direction, opt->rect, *iconRect);
+ *iconRect = QStyle::visualRect(opt->direction, opt->rect, *iconRect);
tr.setLeft(tr.left() + tabIconSize.width() + 4);
}
if (!verticalTabs)
- tr = proxyStyle->visualRect(opt->direction, opt->rect, tr);
+ tr = QStyle::visualRect(opt->direction, opt->rect, tr);
*textRect = tr;
}
@@ -4250,10 +4247,11 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
#if QT_CONFIG(combobox)
case CC_ComboBox:
if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
+ const qreal dpi = QStyleHelper::dpi(opt);
const int x = cb->rect.x(), y = cb->rect.y(), wi = cb->rect.width(), he = cb->rect.height();
- const int margin = cb->frame ? qRound(QStyleHelper::dpiScaled(3)) : 0;
- const int bmarg = cb->frame ? qRound(QStyleHelper::dpiScaled(2)) : 0;
- const int xpos = x + wi - bmarg - qRound(QStyleHelper::dpiScaled(16));
+ const int margin = cb->frame ? qRound(QStyleHelper::dpiScaled(3, dpi)) : 0;
+ const int bmarg = cb->frame ? qRound(QStyleHelper::dpiScaled(2, dpi)) : 0;
+ const int xpos = x + wi - bmarg - qRound(QStyleHelper::dpiScaled(16, dpi));
switch (sc) {
@@ -4261,10 +4259,10 @@ QRect QCommonStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex
ret = cb->rect;
break;
case SC_ComboBoxArrow:
- ret.setRect(xpos, y + bmarg, qRound(QStyleHelper::dpiScaled(16)), he - 2*bmarg);
+ ret.setRect(xpos, y + bmarg, qRound(QStyleHelper::dpiScaled(16, opt)), he - 2*bmarg);
break;
case SC_ComboBoxEditField:
- ret.setRect(x + margin, y + margin, wi - 2 * margin - qRound(QStyleHelper::dpiScaled(16)), he - 2 * margin);
+ ret.setRect(x + margin, y + margin, wi - 2 * margin - qRound(QStyleHelper::dpiScaled(16, dpi)), he - 2 * margin);
break;
case SC_ComboBoxListBoxPopup:
ret = cb->rect;
@@ -4508,13 +4506,13 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
ret = 0;
break;
case PM_DialogButtonsSeparator:
- ret = int(QStyleHelper::dpiScaled(5.));
+ ret = int(QStyleHelper::dpiScaled(5, opt));
break;
case PM_DialogButtonsButtonWidth:
- ret = int(QStyleHelper::dpiScaled(70.));
+ ret = int(QStyleHelper::dpiScaled(70, opt));
break;
case PM_DialogButtonsButtonHeight:
- ret = int(QStyleHelper::dpiScaled(30.));
+ ret = int(QStyleHelper::dpiScaled(30, opt));
break;
case PM_TitleBarHeight: {
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
@@ -4522,33 +4520,33 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
ret = qMax(widget ? widget->fontMetrics().height() : opt->fontMetrics.height(), 16);
#if QT_CONFIG(dockwidget)
} else if (qobject_cast<const QDockWidget*>(widget)) {
- ret = qMax(widget->fontMetrics().height(), int(QStyleHelper::dpiScaled(13)));
+ ret = qMax(widget->fontMetrics().height(), int(QStyleHelper::dpiScaled(13, opt)));
#endif
} else {
ret = qMax(widget ? widget->fontMetrics().height() : opt->fontMetrics.height(), 18);
}
} else {
- ret = int(QStyleHelper::dpiScaled(18.));
+ ret = int(QStyleHelper::dpiScaled(18., opt));
}
break; }
case PM_TitleBarButtonSize:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16., opt));
break;
case PM_TitleBarButtonIconSize:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16., opt));
break;
case PM_ScrollBarSliderMin:
- ret = int(QStyleHelper::dpiScaled(9.));
+ ret = int(QStyleHelper::dpiScaled(9., opt));
break;
case PM_ButtonMargin:
- ret = int(QStyleHelper::dpiScaled(6.));
+ ret = int(QStyleHelper::dpiScaled(6., opt));
break;
case PM_DockWidgetTitleBarButtonMargin:
- ret = int(QStyleHelper::dpiScaled(2.));
+ ret = int(QStyleHelper::dpiScaled(2., opt));
break;
case PM_ButtonDefaultIndicator:
@@ -4556,7 +4554,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_MenuButtonIndicator:
- ret = int(QStyleHelper::dpiScaled(12.));
+ ret = int(QStyleHelper::dpiScaled(12, opt));
break;
case PM_ButtonShiftHorizontal:
@@ -4571,15 +4569,15 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
case PM_MenuPanelWidth:
case PM_TabBarBaseOverlap:
case PM_TabBarBaseHeight:
- ret = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
+ ret = proxy()->pixelMetric(PM_DefaultFrameWidth, opt);
break;
case PM_MdiSubWindowFrameWidth:
- ret = int(QStyleHelper::dpiScaled(4.));
+ ret = int(QStyleHelper::dpiScaled(4, opt));
break;
case PM_MdiSubWindowMinimizedWidth:
- ret = int(QStyleHelper::dpiScaled(196.));
+ ret = int(QStyleHelper::dpiScaled(196, opt));
break;
#if QT_CONFIG(scrollbar)
@@ -4590,7 +4588,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
: QApplication::globalStrut().width();
ret = qMax(16, s);
} else {
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
}
break;
#endif
@@ -4600,7 +4598,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
#if QT_CONFIG(slider)
case PM_SliderThickness:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
break;
case PM_SliderTickmarkOffset:
@@ -4634,11 +4632,11 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
#endif // QT_CONFIG(slider)
#if QT_CONFIG(dockwidget)
case PM_DockWidgetSeparatorExtent:
- ret = int(QStyleHelper::dpiScaled(6.));
+ ret = int(QStyleHelper::dpiScaled(6, opt));
break;
case PM_DockWidgetHandleExtent:
- ret = int(QStyleHelper::dpiScaled(8.));
+ ret = int(QStyleHelper::dpiScaled(8, opt));
break;
case PM_DockWidgetTitleMargin:
ret = 0;
@@ -4667,19 +4665,19 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_ToolBarItemSpacing:
- ret = int(QStyleHelper::dpiScaled(4.));
+ ret = int(QStyleHelper::dpiScaled(4, opt));
break;
case PM_ToolBarHandleExtent:
- ret = int(QStyleHelper::dpiScaled(8.));
+ ret = int(QStyleHelper::dpiScaled(8, opt));
break;
case PM_ToolBarSeparatorExtent:
- ret = int(QStyleHelper::dpiScaled(6.));
+ ret = int(QStyleHelper::dpiScaled(6, opt));
break;
case PM_ToolBarExtensionExtent:
- ret = int(QStyleHelper::dpiScaled(12.));
+ ret = int(QStyleHelper::dpiScaled(12, opt));
break;
#endif // QT_CONFIG(toolbar)
@@ -4689,7 +4687,7 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_TabBarTabHSpace:
- ret = int(QStyleHelper::dpiScaled(24.));
+ ret = int(QStyleHelper::dpiScaled(24, opt));
break;
case PM_TabBarTabShiftHorizontal:
@@ -4718,27 +4716,27 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_IndicatorWidth:
- ret = int(QStyleHelper::dpiScaled(13.));
+ ret = int(QStyleHelper::dpiScaled(13, opt));
break;
case PM_IndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(13.));
+ ret = int(QStyleHelper::dpiScaled(13, opt));
break;
case PM_ExclusiveIndicatorWidth:
- ret = int(QStyleHelper::dpiScaled(12.));
+ ret = int(QStyleHelper::dpiScaled(12, opt));
break;
case PM_ExclusiveIndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(12.));
+ ret = int(QStyleHelper::dpiScaled(12, opt));
break;
case PM_MenuTearoffHeight:
- ret = int(QStyleHelper::dpiScaled(10.));
+ ret = int(QStyleHelper::dpiScaled(10, opt));
break;
case PM_MenuScrollerHeight:
- ret = int(QStyleHelper::dpiScaled(10.));
+ ret = int(QStyleHelper::dpiScaled(10, opt));
break;
case PM_MenuDesktopFrameWidth:
@@ -4748,22 +4746,22 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_HeaderMargin:
- ret = int(QStyleHelper::dpiScaled(4.));
+ ret = int(QStyleHelper::dpiScaled(4, opt));
break;
case PM_HeaderMarkSize:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
break;
case PM_HeaderGripMargin:
- ret = int(QStyleHelper::dpiScaled(4.));
+ ret = int(QStyleHelper::dpiScaled(4, opt));
break;
case PM_HeaderDefaultSectionSizeHorizontal:
- ret = int(QStyleHelper::dpiScaled(100.));
+ ret = int(QStyleHelper::dpiScaled(100, opt));
break;
case PM_HeaderDefaultSectionSizeVertical:
- ret = int(QStyleHelper::dpiScaled(30.));
+ ret = int(QStyleHelper::dpiScaled(30, opt));
break;
case PM_TabBarScrollButtonWidth:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
break;
case PM_LayoutLeftMargin:
case PM_LayoutTopMargin:
@@ -4785,13 +4783,13 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_DefaultTopLevelMargin:
- ret = int(QStyleHelper::dpiScaled(11.));
+ ret = int(QStyleHelper::dpiScaled(11, opt));
break;
case PM_DefaultChildMargin:
- ret = int(QStyleHelper::dpiScaled(9.));
+ ret = int(QStyleHelper::dpiScaled(9, opt));
break;
case PM_DefaultLayoutSpacing:
- ret = int(QStyleHelper::dpiScaled(6.));
+ ret = int(QStyleHelper::dpiScaled(6, opt));
break;
case PM_ToolBarIconSize:
@@ -4799,31 +4797,31 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
ret = theme->themeHint(QPlatformTheme::ToolBarIconSize).toInt();
if (ret <= 0)
- ret = int(QStyleHelper::dpiScaled(24.));
+ ret = int(QStyleHelper::dpiScaled(24, opt));
break;
case PM_TabBarIconSize:
- ret = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
+ ret = proxy()->pixelMetric(PM_SmallIconSize, opt);
break;
case PM_ListViewIconSize:
#if QT_CONFIG(filedialog)
if (qobject_cast<const QSidebar *>(widget))
- ret = int(QStyleHelper::dpiScaled(24.));
+ ret = int(QStyleHelper::dpiScaled(24., opt));
else
#endif
- ret = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
+ ret = proxy()->pixelMetric(PM_SmallIconSize, opt);
break;
case PM_ButtonIconSize:
case PM_SmallIconSize:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
break;
case PM_IconViewIconSize:
- ret = proxy()->pixelMetric(PM_LargeIconSize, opt, widget);
+ ret = proxy()->pixelMetric(PM_LargeIconSize, opt);
break;
case PM_LargeIconSize:
- ret = int(QStyleHelper::dpiScaled(32.));
+ ret = int(QStyleHelper::dpiScaled(32, opt));
break;
case PM_ToolTipLabelFrameWidth:
@@ -4831,19 +4829,19 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_CheckBoxLabelSpacing:
case PM_RadioButtonLabelSpacing:
- ret = int(QStyleHelper::dpiScaled(6.));
+ ret = int(QStyleHelper::dpiScaled(6, opt));
break;
case PM_SizeGripSize:
- ret = int(QStyleHelper::dpiScaled(13.));
+ ret = int(QStyleHelper::dpiScaled(13, opt));
break;
case PM_MessageBoxIconSize:
#ifdef Q_OS_MAC
- if (QApplication::desktopSettingsAware()) {
+ if (QGuiApplication::desktopSettingsAware()) {
ret = 64; // No DPI scaling, it's handled elsewhere.
} else
#endif
{
- ret = int(QStyleHelper::dpiScaled(32.));
+ ret = int(QStyleHelper::dpiScaled(32, opt));
}
break;
case PM_TextCursorWidth:
@@ -4854,19 +4852,19 @@ int QCommonStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWid
break;
case PM_TabCloseIndicatorWidth:
case PM_TabCloseIndicatorHeight:
- ret = int(QStyleHelper::dpiScaled(16.));
+ ret = int(QStyleHelper::dpiScaled(16, opt));
break;
case PM_ScrollView_ScrollBarSpacing:
- ret = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
+ ret = 2 * proxy()->pixelMetric(PM_DefaultFrameWidth, opt);
break;
case PM_ScrollView_ScrollBarOverlap:
ret = 0;
break;
case PM_SubMenuOverlap:
- ret = -proxy()->pixelMetric(QStyle::PM_MenuPanelWidth, opt, widget);
+ ret = -proxy()->pixelMetric(QStyle::PM_MenuPanelWidth, opt);
break;
case PM_TreeViewIndentation:
- ret = int(QStyleHelper::dpiScaled(20.));
+ ret = int(QStyleHelper::dpiScaled(20, opt));
break;
default:
ret = 0;
@@ -5463,14 +5461,14 @@ static QIcon clearTextIcon(bool rtl)
QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *option,
const QWidget *widget) const
{
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QApplication::isRightToLeft());
+ const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QGuiApplication::isRightToLeft());
#ifdef QT_NO_IMAGEFORMAT_PNG
Q_UNUSED(widget);
Q_UNUSED(sp);
#else
QPixmap pixmap;
- if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
+ if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
switch (sp) {
case SP_DialogYesButton:
case SP_DialogOkButton:
@@ -5832,7 +5830,7 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
const QWidget *widget) const
{
QIcon icon;
- const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QApplication::isRightToLeft());
+ const bool rtl = (option && option->direction == Qt::RightToLeft) || (!option && QGuiApplication::isRightToLeft());
#ifdef Q_OS_WIN
switch (standardIcon) {
@@ -5884,7 +5882,7 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
#endif
- if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
+ if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty()) {
switch (standardIcon) {
case SP_DirHomeIcon:
icon = QIcon::fromTheme(QLatin1String("user-home"));
@@ -5969,6 +5967,7 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
case SP_ArrowLeft:
icon = QIcon::fromTheme(QLatin1String("go-previous"));
break;
+ case SP_DialogNoButton:
case SP_DialogCancelButton:
icon = QIcon::fromTheme(QLatin1String("dialog-cancel"),
QIcon::fromTheme(QLatin1String("process-stop")));
@@ -6060,13 +6059,13 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
default:
break;
}
- } // if (QApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty())
+ } // if (QGuiApplication::desktopSettingsAware() && !QIcon::themeName().isEmpty())
if (!icon.isNull())
return icon;
#if defined(Q_OS_MAC)
- if (QApplication::desktopSettingsAware()) {
+ if (QGuiApplication::desktopSettingsAware()) {
switch (standardIcon) {
case SP_DirIcon: {
// A rather special case
@@ -6132,7 +6131,7 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption
default:
break;
}
- } // if (QApplication::desktopSettingsAware())
+ } // if (QGuiApplication::desktopSettingsAware())
#endif // Q_OS_MAC
switch (standardIcon) {
diff --git a/src/widgets/styles/qcommonstyle_p.h b/src/widgets/styles/qcommonstyle_p.h
index 296f89ce5f..4860dfe4c9 100644
--- a/src/widgets/styles/qcommonstyle_p.h
+++ b/src/widgets/styles/qcommonstyle_p.h
@@ -71,7 +71,7 @@ class Q_WIDGETS_EXPORT QCommonStylePrivate : public QStylePrivate
public:
inline QCommonStylePrivate() :
#if QT_CONFIG(itemviews)
- cachedOption(0),
+ cachedOption(nullptr),
#endif
animationFps(30)
{ }
diff --git a/src/widgets/styles/qfusionstyle.cpp b/src/widgets/styles/qfusionstyle.cpp
index 34cc3c93db..b58dc1660a 100644
--- a/src/widgets/styles/qfusionstyle.cpp
+++ b/src/widgets/styles/qfusionstyle.cpp
@@ -88,6 +88,7 @@
#include <private/qstylehelper_p.h>
#include <private/qdrawhelper_p.h>
#include <private/qapplication_p.h>
+#include <private/qwidget_p.h>
QT_BEGIN_NAMESPACE
@@ -250,8 +251,9 @@ static void qt_fusion_draw_arrow(Qt::ArrowType type, QPainter *painter, const QS
if (rect.isEmpty())
return;
- const int arrowWidth = QStyleHelper::dpiScaled(14);
- const int arrowHeight = QStyleHelper::dpiScaled(8);
+ const qreal dpi = QStyleHelper::dpi(option);
+ const int arrowWidth = int(QStyleHelper::dpiScaled(14, dpi));
+ const int arrowHeight = int(QStyleHelper::dpiScaled(8, dpi));
const int arrowMax = qMin(arrowHeight, arrowWidth);
const int rectMax = qMin(rect.height(), rect.width());
@@ -363,6 +365,11 @@ static void qt_fusion_draw_mdibutton(QPainter *painter, const QStyleOptionTitleB
painter->drawPoint(tmp.right() , tmp.bottom() - 1);
}
+static QWindow *qt_getWindow(const QWidget *widget)
+{
+ return widget ? QWidgetPrivate::get(widget)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest) : nullptr;
+}
+
/*
\internal
*/
@@ -465,15 +472,24 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
switch (elem) {
+#if QT_CONFIG(groupbox)
// No frame drawn
case PE_FrameGroupBox:
{
QPixmap pixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/fusion_groupbox.png"));
- int topMargin = qMax(pixelMetric(PM_ExclusiveIndicatorHeight), option->fontMetrics.height()) + groupBoxTopMargin;
+ int topMargin = 0;
+ auto control = dynamic_cast<const QGroupBox *>(widget);
+ if (control && !control->isCheckable() && control->title().isEmpty()) {
+ // Shrinking the topMargin if Not checkable AND title is empty
+ topMargin = groupBoxTopMargin;
+ } else {
+ topMargin = qMax(pixelMetric(PM_ExclusiveIndicatorHeight), option->fontMetrics.height()) + groupBoxTopMargin;
+ }
QRect frame = option->rect.adjusted(0, topMargin, 0, 0);
qDrawBorderPixmap(painter, frame, QMargins(6, 6, 6, 6), pixmap);
break;
}
+#endif // QT_CONFIG(groupbox)
case PE_IndicatorBranch: {
if (!(option->state & State_Children))
break;
@@ -779,12 +795,13 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
painter->drawRect(rect.adjusted(checkMarkPadding, checkMarkPadding, -checkMarkPadding, -checkMarkPadding));
} else if (checkbox->state & State_On) {
- qreal penWidth = QStyleHelper::dpiScaled(1.5);
+ const qreal dpi = QStyleHelper::dpi(option);
+ qreal penWidth = QStyleHelper::dpiScaled(1.5, dpi);
penWidth = qMax<qreal>(penWidth, 0.13 * rect.height());
penWidth = qMin<qreal>(penWidth, 0.20 * rect.height());
QPen checkPen = QPen(checkMarkColor, penWidth);
checkMarkColor.setAlpha(210);
- painter->translate(dpiScaled(-0.8), dpiScaled(0.5));
+ painter->translate(dpiScaled(-0.8, dpi), dpiScaled(0.5, dpi));
painter->setPen(checkPen);
painter->setBrush(Qt::NoBrush);
@@ -984,7 +1001,7 @@ void QFusionStyle::drawPrimitive(PrimitiveElement elem,
d->tabBarcloseButtonIcon = proxy()->standardIcon(SP_DialogCloseButton, option, widget);
if ((option->state & State_Enabled) && (option->state & State_MouseOver))
proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
- QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(QSize(16, 16), QIcon::Normal, QIcon::On);
+ QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(qt_getWindow(widget), QSize(16, 16), QIcon::Normal, QIcon::On);
proxy()->drawItemPixmap(painter, option->rect, Qt::AlignCenter, pixmap);
}
break;
@@ -1024,7 +1041,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
if (!cb->currentIcon.isNull()) {
QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
: QIcon::Disabled;
- QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
+ QPixmap pixmap = cb->currentIcon.pixmap(qt_getWindow(widget), cb->iconSize, mode);
QRect iconRect(editRect);
iconRect.setWidth(cb->iconSize.width() + 4);
iconRect = alignedRect(cb->direction,
@@ -1535,7 +1552,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
QColor highlight = option->palette.highlight().color();
if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
int w = 0;
- const int margin = QStyleHelper::dpiScaled(5);
+ const int margin = int(QStyleHelper::dpiScaled(5, option));
if (!menuItem->text.isEmpty()) {
painter->setFont(menuItem->font);
proxy()->drawItemText(painter, menuItem->rect.adjusted(margin, 0, -margin, 0), Qt::AlignLeft | Qt::AlignVCenter,
@@ -1565,7 +1582,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
bool ignoreCheckMark = false;
const int checkColHOffset = windowsItemHMargin + windowsItemFrame - 1;
int checkcol = qMax<int>(menuItem->rect.height() * 0.79,
- qMax<int>(menuItem->maxIconWidth, dpiScaled(21))); // icon checkbox's highlight column width
+ qMax<int>(menuItem->maxIconWidth, dpiScaled(21, option))); // icon checkbox's highlight column width
if (
#if QT_CONFIG(combobox)
qobject_cast<const QComboBox*>(widget) ||
@@ -1575,7 +1592,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
if (!ignoreCheckMark) {
// Check, using qreal and QRectF to avoid error accumulation
- const qreal boxMargin = dpiScaled(3.5);
+ const qreal boxMargin = dpiScaled(3.5, option);
const qreal boxWidth = checkcol - 2 * boxMargin;
QRectF checkRectF(option->rect.left() + boxMargin + checkColHOffset, option->rect.center().y() - boxWidth/2 + 1, boxWidth, boxWidth);
QRect checkRect = checkRectF.toRect();
@@ -1636,9 +1653,9 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
iconSize = combo->iconSize();
#endif
if (checked)
- pixmap = menuItem->icon.pixmap(iconSize, mode, QIcon::On);
+ pixmap = menuItem->icon.pixmap(qt_getWindow(widget), iconSize, mode, QIcon::On);
else
- pixmap = menuItem->icon.pixmap(iconSize, mode);
+ pixmap = menuItem->icon.pixmap(qt_getWindow(widget), iconSize, mode);
const int pixw = pixmap.width() / pixmap.devicePixelRatio();
const int pixh = pixmap.height() / pixmap.devicePixelRatio();
@@ -1772,7 +1789,7 @@ void QFusionStyle::drawControl(ControlElement element, const QStyleOption *optio
if (button->state & State_On)
state = QIcon::On;
- QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
+ QPixmap pixmap = button->icon.pixmap(qt_getWindow(widget), button->iconSize, mode, state);
int w = pixmap.width() / pixmap.devicePixelRatio();
int h = pixmap.height() / pixmap.devicePixelRatio();
@@ -3175,7 +3192,7 @@ int QFusionStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, co
default:
return QCommonStyle::pixelMetric(metric, option, widget);
}
- return QStyleHelper::dpiScaled(val);
+ return QStyleHelper::dpiScaled(val, option);
}
/*!
@@ -3227,7 +3244,7 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
if (menuItem->text.contains(QLatin1Char('\t')))
w += tabSpacing;
else if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu)
- w += 2 * QStyleHelper::dpiScaled(QFusionStylePrivate::menuArrowHMargin);
+ w += 2 * QStyleHelper::dpiScaled(QFusionStylePrivate::menuArrowHMargin, option);
else if (menuItem->menuItemType == QStyleOptionMenuItem::DefaultItem) {
QFontMetrics fm(menuItem->font);
QFont fontBold = menuItem->font;
@@ -3235,9 +3252,10 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
QFontMetrics fmBold(fontBold);
w += fmBold.horizontalAdvance(menuItem->text) - fm.horizontalAdvance(menuItem->text);
}
- const int checkcol = qMax<int>(maxpmw, QStyleHelper::dpiScaled(QFusionStylePrivate::menuCheckMarkWidth)); // Windows always shows a check column
+ const qreal dpi = QStyleHelper::dpi(option);
+ const int checkcol = qMax<int>(maxpmw, QStyleHelper::dpiScaled(QFusionStylePrivate::menuCheckMarkWidth, dpi)); // Windows always shows a check column
w += checkcol;
- w += QStyleHelper::dpiScaled(int(QFusionStylePrivate::menuRightBorder) + 10);
+ w += QStyleHelper::dpiScaled(int(QFusionStylePrivate::menuRightBorder) + 10, dpi);
newSize.setWidth(w);
if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
if (!menuItem->text.isEmpty()) {
@@ -3251,8 +3269,8 @@ QSize QFusionStyle::sizeFromContents(ContentsType type, const QStyleOption *opti
}
#endif
}
- newSize.setWidth(newSize.width() + QStyleHelper::dpiScaled(12));
- newSize.setWidth(qMax<int>(newSize.width(), QStyleHelper::dpiScaled(120)));
+ newSize.setWidth(newSize.width() + int(QStyleHelper::dpiScaled(12, dpi)));
+ newSize.setWidth(qMax<int>(newSize.width(), int(QStyleHelper::dpiScaled(120, dpi))));
}
break;
case CT_SizeGrip:
@@ -3400,7 +3418,7 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
break;
case SC_SliderGroove: {
QPoint grooveCenter = slider->rect.center();
- const int grooveThickness = QStyleHelper::dpiScaled(7);
+ const int grooveThickness = QStyleHelper::dpiScaled(7, option);
if (slider->orientation == Qt::Horizontal) {
rect.setHeight(grooveThickness);
if (slider->tickPosition & QSlider::TicksAbove)
@@ -3429,7 +3447,7 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
int center = spinbox->rect.height() / 2;
int fw = spinbox->frame ? 3 : 0; // Is drawn with 3 pixels width in drawComplexControl, independently from PM_SpinBoxFrameWidth
int y = fw;
- const int buttonWidth = QStyleHelper::dpiScaled(14);
+ const int buttonWidth = QStyleHelper::dpiScaled(14, option);
int x, lx, rx;
x = spinbox->rect.width() - y - buttonWidth + 2;
lx = fw;
@@ -3513,17 +3531,19 @@ QRect QFusionStyle::subControlRect(ComplexControl control, const QStyleOptionCom
case CC_ComboBox:
switch (subControl) {
- case SC_ComboBoxArrow:
+ case SC_ComboBoxArrow: {
+ const qreal dpi = QStyleHelper::dpi(option);
rect = visualRect(option->direction, option->rect, rect);
- rect.setRect(rect.right() - QStyleHelper::dpiScaled(18), rect.top() - 2,
- QStyleHelper::dpiScaled(19), rect.height() + 4);
+ rect.setRect(rect.right() - int(QStyleHelper::dpiScaled(18, dpi)), rect.top() - 2,
+ int(QStyleHelper::dpiScaled(19, dpi)), rect.height() + 4);
rect = visualRect(option->direction, option->rect, rect);
+ }
break;
case SC_ComboBoxEditField: {
int frameWidth = 2;
rect = visualRect(option->direction, option->rect, rect);
rect.setRect(option->rect.left() + frameWidth, option->rect.top() + frameWidth,
- option->rect.width() - int(QStyleHelper::dpiScaled(19)) - 2 * frameWidth,
+ option->rect.width() - int(QStyleHelper::dpiScaled(19, option)) - 2 * frameWidth,
option->rect.height() - 2 * frameWidth);
if (const QStyleOptionComboBox *box = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
if (!box->editable) {
diff --git a/src/widgets/styles/qfusionstyle_p.h b/src/widgets/styles/qfusionstyle_p.h
index e67e792727..cbefe3e1af 100644
--- a/src/widgets/styles/qfusionstyle_p.h
+++ b/src/widgets/styles/qfusionstyle_p.h
@@ -72,28 +72,28 @@ public:
QPalette standardPalette () const override;
void drawPrimitive(PrimitiveElement elem,
const QStyleOption *option,
- QPainter *painter, const QWidget *widget = 0) const override;
+ QPainter *painter, const QWidget *widget = nullptr) const override;
void drawControl(ControlElement ce, const QStyleOption *option, QPainter *painter,
const QWidget *widget) const override;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const override;
+ int pixelMetric(PixelMetric metric, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const override;
void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
QPainter *painter, const QWidget *widget) const override;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const override;
+ QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = nullptr) const override;
QSize sizeFromContents(ContentsType type, const QStyleOption *option,
const QSize &size, const QWidget *widget) const override;
SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const override;
+ const QPoint &pt, const QWidget *w = nullptr) const override;
QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
SubControl sc, const QWidget *widget) const override;
QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
const QStyleOption *opt) const override;
- int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const override;
+ int styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr,
+ QStyleHintReturn *returnData = nullptr) const override;
QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const override;
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0,
- const QWidget *widget = 0) const override;
+ QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = nullptr,
+ const QWidget *widget = nullptr) const override;
QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const override;
+ const QWidget *widget = nullptr) const override;
void drawItemPixmap(QPainter *painter, const QRect &rect,
int alignment, const QPixmap &pixmap) const override;
void drawItemText(QPainter *painter, const QRect &rect,
diff --git a/src/widgets/styles/qpixmapstyle.cpp b/src/widgets/styles/qpixmapstyle.cpp
index 976bd2630e..05e8467528 100644
--- a/src/widgets/styles/qpixmapstyle.cpp
+++ b/src/widgets/styles/qpixmapstyle.cpp
@@ -122,9 +122,6 @@ QPixmapStyle::~QPixmapStyle()
void QPixmapStyle::polish(QApplication *application)
{
QCommonStyle::polish(application);
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
-#endif
}
/*!
@@ -188,11 +185,6 @@ void QPixmapStyle::polish(QWidget *widget)
frame->setContentsMargins(pix.margins.left(), desc.margins.top(),
pix.margins.right(), desc.margins.bottom());
frame->setAttribute(Qt::WA_TranslucentBackground);
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- // FramelessWindowHint is needed on windows to make
- // WA_TranslucentBackground work properly
- frame->setWindowFlags(widget->windowFlags() | Qt::FramelessWindowHint);
-#endif
}
}
#endif // QT_CONFIG(combobox)
diff --git a/src/widgets/styles/qpixmapstyle_p.h b/src/widgets/styles/qpixmapstyle_p.h
index 590434d95e..d32631a527 100644
--- a/src/widgets/styles/qpixmapstyle_p.h
+++ b/src/widgets/styles/qpixmapstyle_p.h
@@ -147,7 +147,7 @@ public:
void drawControl(ControlElement element, const QStyleOption *option,
QPainter *painter, const QWidget *widget = nullptr) const override;
void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *option,
- QPainter *painter, const QWidget *widget=0) const override;
+ QPainter *painter, const QWidget *widget=nullptr) const override;
QSize sizeFromContents(ContentsType type, const QStyleOption *option,
const QSize &contentsSize, const QWidget *widget = nullptr) const override;
diff --git a/src/widgets/styles/qproxystyle_p.h b/src/widgets/styles/qproxystyle_p.h
index 2343a03e2a..2321f0fed0 100644
--- a/src/widgets/styles/qproxystyle_p.h
+++ b/src/widgets/styles/qproxystyle_p.h
@@ -67,7 +67,7 @@ public:
void ensureBaseStyle() const;
private:
QProxyStylePrivate() :
- QCommonStylePrivate(), baseStyle(0) {}
+ QCommonStylePrivate(), baseStyle(nullptr) {}
mutable QPointer <QStyle> baseStyle;
};
diff --git a/src/widgets/styles/qstyle.cpp b/src/widgets/styles/qstyle.cpp
index ec5b6df6b3..6cbed34c3a 100644
--- a/src/widgets/styles/qstyle.cpp
+++ b/src/widgets/styles/qstyle.cpp
@@ -560,7 +560,7 @@ QRect QStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pi
x += w - pixmapWidth;
else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
x += w/2 - pixmapWidth/2;
- else if ((alignment & Qt::AlignLeft) != Qt::AlignLeft && QApplication::isRightToLeft())
+ else if ((alignment & Qt::AlignLeft) != Qt::AlignLeft && QGuiApplication::isRightToLeft())
x += w - pixmapWidth;
result = QRect(x, y, pixmapWidth, pixmapHeight);
return result;
@@ -624,7 +624,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
const QPixmap &pixmap) const
{
qreal scale = pixmap.devicePixelRatio();
- QRect aligned = alignedRect(QApplication::layoutDirection(), QFlag(alignment), pixmap.size() / scale, rect);
+ QRect aligned = alignedRect(QGuiApplication::layoutDirection(), QFlag(alignment), pixmap.size() / scale, rect);
QRect inter = aligned.intersected(rect);
painter->drawPixmap(inter.x(), inter.y(), pixmap, inter.x() - aligned.x(), inter.y() - aligned.y(), inter.width() * scale, inter.height() *scale);
@@ -2101,6 +2101,20 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SP_MediaVolume Icon indicating a volume control.
\value SP_MediaVolumeMuted Icon indicating a muted volume control.
\value SP_LineEditClearButton Icon for a standard clear button in a QLineEdit. This enum value was added in Qt 5.2.
+ \value SP_DialogYesToAllButton Icon for a standard YesToAll button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_DialogNoToAllButton Icon for a standard NoToAll button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_DialogSaveAllButton Icon for a standard SaveAll button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_DialogAbortButton Icon for a standard Abort button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_DialogRetryButton Icon for a standard Retry button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_DialogIgnoreButton Icon for a standard Ignore button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
+ \value SP_RestoreDefaultsButton Icon for a standard RestoreDefaults button in a QDialogButtonBox.
+ This enum value was added in Qt 5.14.
\value SP_CustomBase Base value for custom standard pixmaps;
custom values must be greater than this value.
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index 5ee37bd8e9..ee234457f5 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -832,6 +832,13 @@ public:
SP_MediaVolume,
SP_MediaVolumeMuted,
SP_LineEditClearButton,
+ SP_DialogYesToAllButton,
+ SP_DialogNoToAllButton,
+ SP_DialogSaveAllButton,
+ SP_DialogAbortButton,
+ SP_DialogRetryButton,
+ SP_DialogIgnoreButton,
+ SP_RestoreDefaultsButton,
// do not add any values below/greater than this
SP_CustomBase = 0xf0000000
};
diff --git a/src/widgets/styles/qstyle_p.h b/src/widgets/styles/qstyle_p.h
index 5bbde5fe17..7942cafaf7 100644
--- a/src/widgets/styles/qstyle_p.h
+++ b/src/widgets/styles/qstyle_p.h
@@ -66,7 +66,7 @@ class QStylePrivate: public QObjectPrivate
Q_DECLARE_PUBLIC(QStyle)
public:
inline QStylePrivate()
- : layoutSpacingIndex(-1), proxyStyle(0) {}
+ : layoutSpacingIndex(-1), proxyStyle(nullptr) {}
static bool useFullScreenForPopup();
diff --git a/src/widgets/styles/qstylehelper.cpp b/src/widgets/styles/qstylehelper.cpp
index 0b910d46df..4e61b2d1ec 100644
--- a/src/widgets/styles/qstylehelper.cpp
+++ b/src/widgets/styles/qstylehelper.cpp
@@ -40,6 +40,8 @@
#include <qstyleoption.h>
#include <qpainter.h>
#include <qpixmapcache.h>
+#include <private/qhighdpiscaling_p.h>
+#include <private/qguiapplication_p.h>
#include <private/qmath_p.h>
#include <private/qstyle_p.h>
#include <qmath.h>
@@ -49,6 +51,7 @@
#include <qabstractscrollarea.h>
#include <qwindow.h>
+#include <qmetaobject.h>
#include "qstylehelper_p.h"
#include <qstringbuilder.h>
@@ -79,15 +82,41 @@ QString uniqueName(const QString &key, const QStyleOption *option, const QSize &
return tmp;
}
-qreal dpiScaled(qreal value)
-{
-#ifdef Q_OS_MAC
- // On mac the DPI is always 72 so we should not scale it
- return value;
+#ifdef Q_OS_DARWIN
+static const qreal qstyleBaseDpi = 72;
#else
- static const qreal scale = qreal(qt_defaultDpiX()) / 96.0;
- return value * scale;
+static const qreal qstyleBaseDpi = 96;
+#endif
+
+Q_WIDGETS_EXPORT qreal dpi(const QStyleOption *option)
+{
+#ifndef Q_OS_DARWIN
+ // Prioritize the application override, except for on macOS where
+ // we have historically not supported the AA_Use96Dpi flag.
+ if (QCoreApplication::testAttribute(Qt::AA_Use96Dpi))
+ return 96;
#endif
+
+ // Expect that QStyleOption::QFontMetrics::QFont has the correct DPI set
+ if (option)
+ return option->fontMetrics.fontDpi();
+
+ return qstyleBaseDpi;
+}
+
+Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, qreal dpi)
+{
+ return value * dpi / qstyleBaseDpi;
+}
+
+Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, const QPaintDevice *device)
+{
+ return dpiScaled(value, device->logicalDpiX());
+}
+
+Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, const QStyleOption *option)
+{
+ return dpiScaled(value, dpi(option));
}
#ifndef QT_NO_ACCESSIBILITY
diff --git a/src/widgets/styles/qstylehelper_p.h b/src/widgets/styles/qstylehelper_p.h
index d79dfe4288..165608257a 100644
--- a/src/widgets/styles/qstylehelper_p.h
+++ b/src/widgets/styles/qstylehelper_p.h
@@ -40,6 +40,7 @@
#include <QtWidgets/private/qtwidgetsglobal_p.h>
#include <QtCore/qpoint.h>
#include <QtCore/qstring.h>
+#include <QtGui/qpaintdevice.h>
#include <QtGui/qpolygon.h>
#include <QtCore/qstringbuilder.h>
#include <QtGui/qaccessible.h>
@@ -75,7 +76,13 @@ class QWindow;
namespace QStyleHelper
{
QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size);
- Q_WIDGETS_EXPORT qreal dpiScaled(qreal value);
+
+ Q_WIDGETS_EXPORT qreal dpi(const QStyleOption *option);
+
+ Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, qreal dpi);
+ Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, const QPaintDevice *device);
+ Q_WIDGETS_EXPORT qreal dpiScaled(qreal value, const QStyleOption *option);
+
#if QT_CONFIG(dial)
qreal angle(const QPointF &p1, const QPointF &p2);
QPolygonF calcLines(const QStyleOptionSlider *dial);
@@ -89,11 +96,11 @@ namespace QStyleHelper
Q_WIDGETS_EXPORT bool isInstanceOf(QObject *obj, QAccessible::Role role);
Q_WIDGETS_EXPORT bool hasAncestor(QObject *obj, QAccessible::Role role);
#endif
- Q_WIDGETS_EXPORT QColor backgroundColor(const QPalette &pal, const QWidget* widget = 0);
+ Q_WIDGETS_EXPORT QColor backgroundColor(const QPalette &pal, const QWidget* widget = nullptr);
enum WidgetSizePolicy { SizeLarge = 0, SizeSmall = 1, SizeMini = 2, SizeDefault = -1 };
- Q_WIDGETS_EXPORT WidgetSizePolicy widgetSizePolicy(const QWidget *w, const QStyleOption *opt = 0);
+ Q_WIDGETS_EXPORT WidgetSizePolicy widgetSizePolicy(const QWidget *w, const QStyleOption *opt = nullptr);
}
diff --git a/src/widgets/styles/qstyleoption.cpp b/src/widgets/styles/qstyleoption.cpp
index 88031a9f1e..01cadd9a86 100644
--- a/src/widgets/styles/qstyleoption.cpp
+++ b/src/widgets/styles/qstyleoption.cpp
@@ -151,7 +151,7 @@ QT_BEGIN_NAMESPACE
QStyleOption::QStyleOption(int version, int type)
: version(version), type(type), state(QStyle::State_None),
- direction(QApplication::layoutDirection()), fontMetrics(QFont()), styleObject(0)
+ direction(QGuiApplication::layoutDirection()), fontMetrics(QFont()), styleObject(0)
{
}
@@ -198,11 +198,6 @@ void QStyleOption::init(const QWidget *widget)
state |= QStyle::State_Active;
if (widget->isWindow())
state |= QStyle::State_Window;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- extern bool qt_mac_can_clickThrough(const QWidget *w); //qwidget_mac.cpp
- if (!(state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget))
- state &= ~QStyle::State_Enabled;
-#endif
switch (QStyleHelper::widgetSizePolicy(widget)) {
case QStyleHelper::SizeSmall:
state |= QStyle::State_Small;
@@ -1765,7 +1760,7 @@ QStyleOptionMenuItem::QStyleOptionMenuItem(int version)
\value Exclusive The item is an exclusive check item (like a radio button).
\value NonExclusive The item is a non-exclusive check item (like a check box).
- \sa checkType, QAction::checkable, QAction::checked, QActionGroup::exclusive
+ \sa checkType, QAction::checkable, QAction::checked, QActionGroup::exclusionPolicy
*/
/*!
diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp
index 98a9f74f5b..3f57992311 100644
--- a/src/widgets/styles/qstylesheetstyle.cpp
+++ b/src/widgets/styles/qstylesheetstyle.cpp
@@ -615,7 +615,7 @@ public:
public:
int features;
QBrush defaultBackground;
- QFont font;
+ QFont font; // Be careful using this font directly. Prefer using font.resolve( )
bool hasFont;
QHash<QString, QVariant> styleHints;
@@ -851,7 +851,7 @@ QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget
info.rule = subRule;
info.offset = offsets[where];
info.where = where;
- infos.append(qMove(info));
+ infos.append(std::move(info));
offsets[where] += info.width;
}
@@ -909,7 +909,7 @@ static QStyle::StandardPixmap subControlIcon(int pe)
QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject *object)
: features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0)
{
- QPalette palette = QApplication::palette(); // ###: ideally widget's palette
+ QPalette palette = QGuiApplication::palette(); // ###: ideally widget's palette
ValueExtractor v(declarations, palette);
features = v.extractStyleFeatures();
@@ -2734,7 +2734,7 @@ static void updateObjects(const QList<const QObject *>& objects)
for (const QObject *object : objects) {
if (auto widget = qobject_cast<QWidget*>(const_cast<QObject*>(object))) {
widget->style()->polish(widget);
- QApplication::sendEvent(widget, &event);
+ QCoreApplication::sendEvent(widget, &event);
QList<const QObject *> children;
children.reserve(widget->children().size() + 1);
for (auto child: qAsConst(widget->children()))
@@ -3216,7 +3216,7 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC
rule.drawRule(p, opt->rect);
toolOpt.rect = rule.contentsRect(opt->rect);
if (rule.hasFont)
- toolOpt.font = rule.font;
+ toolOpt.font = rule.font.resolve(toolOpt.font);
drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
}
@@ -3451,7 +3451,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
case CE_ToolButtonLabel:
if (const QStyleOptionToolButton *btn = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
if (rule.hasBox() || btn->features & QStyleOptionToolButton::Arrow) {
- QCommonStyle::drawControl(ce, opt, p, w);
+ QWindowsStyle::drawControl(ce, opt, p, w);
} else {
QStyleOptionToolButton butOpt(*btn);
rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
@@ -3519,7 +3519,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
const QFont oldFont = p->font();
if (rule.hasFont)
- p->setFont(rule.font);
+ p->setFont(rule.font.resolve(p->font()));
if (rule.hasPosition() && rule.position()->textAlignment != 0) {
Qt::Alignment textAlignment = rule.position()->textAlignment;
@@ -3683,7 +3683,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
subRule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
QFont oldFont = p->font();
if (subRule.hasFont)
- p->setFont(subRule.font.resolve(p->font()));
+ p->setFont(subRule.font.resolve(mi.font));
else
p->setFont(mi.font);
@@ -3825,7 +3825,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
- QCommonStyle::drawControl(ce, &mi, p, w);
+ QCommonStyle::drawControl(ce, &mi, p, w); // deliberate bypass of the base
} else {
if (rule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
// So that the menu bar background is not hidden by the items
@@ -4089,8 +4089,13 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
subRule.configurePalette(&boxCopy.palette, QPalette::ButtonText, QPalette::Button);
QFont oldFont = p->font();
if (subRule.hasFont)
- p->setFont(subRule.font);
+ p->setFont(subRule.font.resolve(p->font()));
boxCopy.rect = subRule.contentsRect(opt->rect);
+ if (subRule.hasImage()) {
+ // the image is already drawn with CE_ToolBoxTabShape, adjust rect here
+ const int iconExtent = proxy()->pixelMetric(QStyle::PM_SmallIconSize, box, w);
+ boxCopy.rect.setLeft(boxCopy.rect.left() + iconExtent);
+ }
QWindowsStyle::drawControl(ce, &boxCopy, p , w);
if (subRule.hasFont)
p->setFont(oldFont);
@@ -4171,7 +4176,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q
subRule.configurePalette(&tabCopy.palette, QPalette::WindowText, QPalette::Base);
QFont oldFont = p->font();
if (subRule.hasFont)
- p->setFont(subRule.font);
+ p->setFont(subRule.font.resolve(p->font()));
if (subRule.hasBox() || !subRule.hasNativeBorder()) {
tabCopy.rect = ce == CE_TabBarTabShape ? subRule.borderRect(r)
: subRule.contentsRect(r);
@@ -5030,13 +5035,25 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
sz = subRule.adjustSize(csz);
+ if (!sz.isValid()) {
+ // Try to set the missing values based on the base style.
+ const auto baseSize = baseStyle()->sizeFromContents(ct, opt, sz, w);
+ if (sz.width() < 0)
+ sz.setWidth(baseSize.width());
+ if (sz.height() < 0)
+ sz.setHeight(baseSize.height());
+ }
if (!subRule.hasGeometry()) {
QSize nativeContentsSize;
bool nullIcon = hdr->icon.isNull();
const int margin = pixelMetric(QStyle::PM_HeaderMargin, hdr, w);
int iconSize = nullIcon ? 0 : pixelMetric(QStyle::PM_SmallIconSize, hdr, w);
- const QSize txt = subRule.hasFont ? QFontMetrics(subRule.font).size(0, hdr->text)
- : hdr->fontMetrics.size(0, hdr->text);
+ QFontMetrics fm = hdr->fontMetrics;
+ if (subRule.hasFont) {
+ QFont styleFont = w ? subRule.font.resolve(w->font()) : subRule.font;
+ fm = QFontMetrics(styleFont);
+ }
+ const QSize txt = fm.size(0, hdr->text);
nativeContentsSize.setHeight(margin + qMax(iconSize, txt.height()) + margin);
nativeContentsSize.setWidth((nullIcon ? 0 : margin) + iconSize
+ (hdr->text.isNull() ? 0 : margin) + txt.width() + margin);
@@ -5153,13 +5170,6 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op
sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
return subRule.boxSize(subRule.adjustSize(sz));
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (baseStyle()->inherits("QMacStyle")) {
- //adjust the size after the call to the style because the mac style ignore the size arguments anyway.
- //this might cause the (max-){width,height} property to include the native style border while they should not.
- return subRule.adjustSize(baseStyle()->sizeFromContents(ct, opt, csz, w));
- }
-#endif
sz = subRule.adjustSize(csz);
break;
}
@@ -6073,7 +6083,7 @@ void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
w->d_func()->directFontResolveMask = font.resolve();
QEvent e(QEvent::FontChange);
- QApplication::sendEvent(w, &e);
+ QCoreApplication::sendEvent(w, &e);
}
}
diff --git a/src/widgets/styles/qstylesheetstyle_p.h b/src/widgets/styles/qstylesheetstyle_p.h
index 9c4b87fc32..c5266558af 100644
--- a/src/widgets/styles/qstylesheetstyle_p.h
+++ b/src/widgets/styles/qstylesheetstyle_p.h
@@ -82,40 +82,40 @@ public:
~QStyleSheetStyle();
void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const override;
void drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal,
bool enabled, const QString& text, QPalette::ColorRole textRole = QPalette::NoRole) const override;
void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
const QStyleOption *option) const override;
SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
- const QPoint &pt, const QWidget *w = 0) const override;
+ const QPoint &pt, const QWidget *w = nullptr) const override;
QRect itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const override;
QRect itemTextRect(const QFontMetrics &metrics, const QRect &rect, int alignment, bool enabled,
const QString &text) const override;
- int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const override;
+ int pixelMetric(PixelMetric metric, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const override;
void polish(QWidget *widget) override;
void polish(QApplication *app) override;
void polish(QPalette &pal) override;
QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const override;
+ const QSize &contentsSize, const QWidget *widget = nullptr) const override;
QPalette standardPalette() const override;
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *opt = 0,
- const QWidget *widget = 0) const override;
- QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option = 0,
- const QWidget *w = 0 ) const override;
+ QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *opt = nullptr,
+ const QWidget *widget = nullptr) const override;
+ QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *option = nullptr,
+ const QWidget *w = nullptr ) const override;
int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
- Qt::Orientation orientation, const QStyleOption *option = 0,
- const QWidget *widget = 0) const override;
- int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
- QStyleHintReturn *shret = 0) const override;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const override;
+ Qt::Orientation orientation, const QStyleOption *option = nullptr,
+ const QWidget *widget = nullptr) const override;
+ int styleHint(StyleHint sh, const QStyleOption *opt = nullptr, const QWidget *w = nullptr,
+ QStyleHintReturn *shret = nullptr) const override;
+ QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = nullptr) const override;
QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
// These functions are called from QApplication/QWidget. Be careful.
QStyle *baseStyle() const;
diff --git a/src/widgets/styles/qwindowsstyle.cpp b/src/widgets/styles/qwindowsstyle.cpp
index 4e450813cb..8496a2c223 100644
--- a/src/widgets/styles/qwindowsstyle.cpp
+++ b/src/widgets/styles/qwindowsstyle.cpp
@@ -84,6 +84,7 @@
#include <qpa/qplatformscreen.h>
#include <private/qguiapplication_p.h>
#include <private/qhighdpiscaling_p.h>
+#include <private/qwidget_p.h>
#include <private/qstylehelper_p.h>
#if QT_CONFIG(animation)
@@ -119,10 +120,7 @@ enum QSliderDirection { SlUp, SlDown, SlLeft, SlRight };
\internal
*/
-QWindowsStylePrivate::QWindowsStylePrivate()
- : alt_down(false), menuBarTimer(0)
-{
-}
+QWindowsStylePrivate::QWindowsStylePrivate() = default;
qreal QWindowsStylePrivate::appDevicePixelRatio()
{
@@ -156,7 +154,7 @@ bool QWindowsStyle::eventFilter(QObject *o, QEvent *e)
QList<QWidget *> l = widget->findChildren<QWidget *>();
auto ignorable = [](QWidget *w) {
return w->isWindow() || !w->isVisible()
- || w->style()->styleHint(SH_UnderlineShortcut, 0, w);
+ || w->style()->styleHint(SH_UnderlineShortcut, nullptr, w);
};
l.erase(std::remove_if(l.begin(), l.end(), ignorable), l.end());
// Update states before repainting
@@ -241,14 +239,15 @@ void QWindowsStyle::polish(QApplication *app)
QCommonStyle::polish(app);
QWindowsStylePrivate *d = const_cast<QWindowsStylePrivate*>(d_func());
// We only need the overhead when shortcuts are sometimes hidden
- if (!proxy()->styleHint(SH_UnderlineShortcut, 0) && app)
+ if (!proxy()->styleHint(SH_UnderlineShortcut, nullptr) && app)
app->installEventFilter(this);
- d->activeCaptionColor = app->palette().highlight().color();
- d->activeGradientCaptionColor = app->palette().highlight() .color();
- d->inactiveCaptionColor = app->palette().dark().color();
- d->inactiveGradientCaptionColor = app->palette().dark().color();
- d->inactiveCaptionText = app->palette().window().color();
+ const auto &palette = QGuiApplication::palette();
+ d->activeGradientCaptionColor = palette.highlight().color();
+ d->activeCaptionColor = d->activeGradientCaptionColor;
+ d->inactiveGradientCaptionColor = palette.dark().color();
+ d->inactiveCaptionColor = d->inactiveGradientCaptionColor;
+ d->inactiveCaptionText = palette.window().color();
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) //fetch native title bar colors
if(app->desktopSettingsAware()){
@@ -341,7 +340,6 @@ int QWindowsStylePrivate::fixedPixelMetric(QStyle::PixelMetric pm)
case QStyle::PM_MenuVMargin:
case QStyle::PM_ToolBarItemMargin:
return 1;
- break;
case QStyle::PM_DockWidgetSeparatorExtent:
return 4;
#if QT_CONFIG(tabbar)
@@ -380,23 +378,12 @@ int QWindowsStylePrivate::fixedPixelMetric(QStyle::PixelMetric pm)
return QWindowsStylePrivate::InvalidMetric;
}
-static QWindow *windowOf(const QWidget *w)
+static QScreen *screenOf(const QWidget *w)
{
- QWindow *result = nullptr;
if (w) {
- result = w->windowHandle();
- if (!result) {
- if (const QWidget *np = w->nativeParentWidget())
- result = np->windowHandle();
- }
+ if (auto screen = qt_widget_private(const_cast<QWidget *>(w))->associatedScreen())
+ return screen;
}
- return result;
-}
-
-static QScreen *screenOf(const QWidget *w)
-{
- if (const QWindow *window = windowOf(w))
- return window->screen();
return QGuiApplication::primaryScreen();
}
@@ -405,8 +392,6 @@ static QScreen *screenOf(const QWidget *w)
// and account for secondary screens with differing logical DPI.
qreal QWindowsStylePrivate::nativeMetricScaleFactor(const QWidget *widget)
{
- if (!QHighDpiScaling::isActive())
- return 1;
qreal result = qreal(1) / QWindowsStylePrivate::devicePixelRatio(widget);
if (QGuiApplicationPrivate::screen_list.size() > 1) {
const QScreen *primaryScreen = QGuiApplication::primaryScreen();
@@ -432,7 +417,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
ret = QWindowsStylePrivate::fixedPixelMetric(pm);
if (ret != QWindowsStylePrivate::InvalidMetric)
- return int(QStyleHelper::dpiScaled(ret));
+ return int(QStyleHelper::dpiScaled(ret, opt));
ret = 0;
@@ -478,7 +463,7 @@ int QWindowsStyle::pixelMetric(PixelMetric pm, const QStyleOption *opt, const QW
break;
case PM_SplitterWidth:
- ret = qMax(int(QStyleHelper::dpiScaled(4)), QApplication::globalStrut().width());
+ ret = qMax(int(QStyleHelper::dpiScaled(4, opt)), QApplication::globalStrut().width());
break;
default:
@@ -707,17 +692,17 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
x -= 2;
if (opt->rect.height() > 4) {
qDrawShadePanel(p, x, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
+ opt->palette, false, 1, nullptr);
qDrawShadePanel(p, x + 3, 2, 3, opt->rect.height() - 4,
- opt->palette, false, 1, 0);
+ opt->palette, false, 1, nullptr);
}
} else {
if (opt->rect.width() > 4) {
int y = opt->rect.height() / 2 - 4;
qDrawShadePanel(p, 2, y, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
+ opt->palette, false, 1, nullptr);
qDrawShadePanel(p, 2, y + 3, opt->rect.width() - 4, 3,
- opt->palette, false, 1, 0);
+ opt->palette, false, 1, nullptr);
}
}
p->restore();
@@ -768,7 +753,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
}
} else {
qDrawWinButton(p, opt->rect, opt->palette,
- opt->state & (State_Sunken | State_On), panel ? &fill : 0);
+ opt->state & (State_Sunken | State_On), panel ? &fill : nullptr);
}
} else {
p->fillRect(opt->rect, fill);
@@ -802,8 +787,11 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
QPen oldPen = p->pen();
p->setPen(QPen(opt->palette.shadow().color(), 0));
QRectF rect = opt->rect;
- rect.adjust(QStyleHelper::dpiScaled(0.5), QStyleHelper::dpiScaled(0.5),
- QStyleHelper::dpiScaled(-1.5), QStyleHelper::dpiScaled(-1.5));
+ const qreal dpi = QStyleHelper::dpi(opt);
+ const qreal topLevelAdjustment = QStyleHelper::dpiScaled(0.5, dpi);
+ const qreal bottomRightAdjustment = QStyleHelper::dpiScaled(-1.5, dpi);
+ rect.adjust(topLevelAdjustment, topLevelAdjustment,
+ bottomRightAdjustment, bottomRightAdjustment);
p->drawRect(rect);
p->setPen(oldPen);
break;
@@ -986,7 +974,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
if (opt->state & (State_Raised | State_On | State_Sunken)) {
qDrawWinButton(p, opt->rect, opt->palette, opt->state & (State_Sunken | State_On),
- panel ? &fill : 0);
+ panel ? &fill : nullptr);
} else {
if (panel)
p->fillRect(opt->rect, fill);
@@ -1011,7 +999,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
#endif // QT_CONFIG(dockwidget)
case PE_FrameStatusBarItem:
- qDrawShadePanel(p, opt->rect, opt->palette, true, 1, 0);
+ qDrawShadePanel(p, opt->rect, opt->palette, true, 1, nullptr);
break;
case PE_IndicatorProgressChunk:
@@ -1049,7 +1037,7 @@ void QWindowsStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt,
break;
case PE_FrameTabWidget: {
- qDrawWinButton(p, opt->rect, opt->palette, false, 0);
+ qDrawWinButton(p, opt->rect, opt->palette, false, nullptr);
break;
}
default:
@@ -1591,6 +1579,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
case QStyleOptionToolBar::Beginning:
case QStyleOptionToolBar::OnlyOne:
paintBottomBorder = false;
+ break;
default:
break;
}
@@ -1606,6 +1595,7 @@ void QWindowsStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPai
case QStyleOptionToolBar::OnlyOne:
paintRightBorder = false;
paintLeftBorder = false;
+ break;
default:
break;
}
@@ -2310,8 +2300,9 @@ QSize QWindowsStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
int defwidth = 0;
if (btn->features & QStyleOptionButton::AutoDefaultButton)
defwidth = 2 * proxy()->pixelMetric(PM_ButtonDefaultIndicator, btn, widget);
- int minwidth = int(QStyleHelper::dpiScaled(75.));
- int minheight = int(QStyleHelper::dpiScaled(23.));
+ const qreal dpi = QStyleHelper::dpi(opt);
+ int minwidth = int(QStyleHelper::dpiScaled(75, dpi));
+ int minheight = int(QStyleHelper::dpiScaled(23, dpi));
#ifndef QT_QWS_SMALL_PUSHBUTTON
if (w < minwidth + defwidth && !btn->text.isEmpty())
diff --git a/src/widgets/styles/qwindowsstyle_p.h b/src/widgets/styles/qwindowsstyle_p.h
index 47816ff651..b5f0bd68a1 100644
--- a/src/widgets/styles/qwindowsstyle_p.h
+++ b/src/widgets/styles/qwindowsstyle_p.h
@@ -77,25 +77,25 @@ public:
void polish(QPalette &) override;
void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
- const QWidget *w = 0) const override;
- QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const override;
+ const QWidget *w = nullptr) const override;
+ QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = nullptr) const override;
void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
- const QWidget *w = 0) const override;
+ const QWidget *w = nullptr) const override;
QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
- const QSize &contentsSize, const QWidget *widget = 0) const override;
+ const QSize &contentsSize, const QWidget *widget = nullptr) const override;
- int pixelMetric(PixelMetric pm, const QStyleOption *option = 0, const QWidget *widget = 0) const override;
+ int pixelMetric(PixelMetric pm, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const override;
- int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
- QStyleHintReturn *returnData = 0) const override;
+ int styleHint(StyleHint hint, const QStyleOption *opt = nullptr, const QWidget *widget = nullptr,
+ QStyleHintReturn *returnData = nullptr) const override;
QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
- const QWidget *widget = 0) const override;
+ const QWidget *widget = nullptr) const override;
- QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = 0,
- const QWidget *widget = 0) const override;
+ QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = nullptr,
+ const QWidget *widget = nullptr) const override;
protected:
bool eventFilter(QObject *o, QEvent *e) override;
diff --git a/src/widgets/styles/qwindowsstyle_p_p.h b/src/widgets/styles/qwindowsstyle_p_p.h
index 67fa6a2f86..4f6ffcefc2 100644
--- a/src/widgets/styles/qwindowsstyle_p_p.h
+++ b/src/widgets/styles/qwindowsstyle_p_p.h
@@ -69,17 +69,17 @@ public:
enum { InvalidMetric = -23576 };
QWindowsStylePrivate();
- static int pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *option = 0, const QWidget *widget = 0);
+ static int pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *option = nullptr, const QWidget *widget = nullptr);
static int fixedPixelMetric(QStyle::PixelMetric pm);
- static qreal devicePixelRatio(const QWidget *widget = 0)
+ static qreal devicePixelRatio(const QWidget *widget = nullptr)
{ return widget ? widget->devicePixelRatioF() : QWindowsStylePrivate::appDevicePixelRatio(); }
static qreal nativeMetricScaleFactor(const QWidget *widget = nullptr);
bool hasSeenAlt(const QWidget *widget) const;
bool altDown() const { return alt_down; }
- bool alt_down;
+ bool alt_down = false;
QList<const QWidget *> seenAlt;
- int menuBarTimer;
+ int menuBarTimer = 0;
QColor inactiveCaptionText;
QColor activeCaptionColor;
diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp
index e41f7e7573..7b69eff30c 100644
--- a/src/widgets/util/qcompleter.cpp
+++ b/src/widgets/util/qcompleter.cpp
@@ -145,7 +145,9 @@
#include "QtWidgets/qscrollbar.h"
#include "QtCore/qdir.h"
+#if QT_CONFIG(stringlistmodel)
#include "QtCore/qstringlistmodel.h"
+#endif
#if QT_CONFIG(dirmodel)
#include "QtWidgets/qdirmodel.h"
#endif
@@ -159,6 +161,7 @@
#include "QtWidgets/qapplication.h"
#include "QtGui/qevent.h"
#include "QtWidgets/qdesktopwidget.h"
+#include <private/qapplication_p.h>
#include <private/qdesktopwidget_p.h>
#if QT_CONFIG(lineedit)
#include "QtWidgets/qlineedit.h"
@@ -1414,7 +1417,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
// widget lost focus, hide the popup
if (d->widget && (!d->widget->hasFocus()
#ifdef QT_KEYPAD_NAVIGATION
- || (QApplication::keypadNavigationEnabled() && !d->widget->hasEditFocus())
+ || (QApplicationPrivate::keypadNavigationEnabled() && !d->widget->hasEditFocus())
#endif
))
d->popup->hide();
@@ -1432,7 +1435,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
switch (key) {
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
- if (!QApplication::keypadNavigationEnabled())
+ if (!QApplicationPrivate::keypadNavigationEnabled())
break;
#endif
case Qt::Key_Return:
@@ -1462,7 +1465,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
case QEvent::KeyRelease: {
QKeyEvent *ke = static_cast<QKeyEvent *>(e);
- if (QApplication::keypadNavigationEnabled() && ke->key() == Qt::Key_Back) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && ke->key() == Qt::Key_Back) {
// Send the event to the 'widget'. This is what we did for KeyPress, so we need
// to do the same for KeyRelease, in case the widget's KeyPress event set
// up something (such as a timer) that is relying on also receiving the
@@ -1479,7 +1482,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
case QEvent::MouseButtonPress: {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// if we've clicked in the widget (or its descendant), let it handle the click
QWidget *source = qobject_cast<QWidget *>(o);
if (source) {
@@ -1504,7 +1507,7 @@ bool QCompleter::eventFilter(QObject *o, QEvent *e)
case QEvent::InputMethod:
case QEvent::ShortcutOverride:
- QApplication::sendEvent(d->widget, e);
+ QCoreApplication::sendEvent(d->widget, e);
break;
default:
diff --git a/src/widgets/util/qcompleter_p.h b/src/widgets/util/qcompleter_p.h
index 21dddf446e..a52e63a6e2 100644
--- a/src/widgets/util/qcompleter_p.h
+++ b/src/widgets/util/qcompleter_p.h
@@ -75,7 +75,7 @@ class QCompleterPrivate : public QObjectPrivate
public:
QCompleterPrivate();
~QCompleterPrivate() { delete popup; }
- void init(QAbstractItemModel *model = 0);
+ void init(QAbstractItemModel *model = nullptr);
QPointer<QWidget> widget;
QCompletionModel *proxy;
diff --git a/src/widgets/util/qflickgesture.cpp b/src/widgets/util/qflickgesture.cpp
index a8b2a00a80..14a30ce7cf 100644
--- a/src/widgets/util/qflickgesture.cpp
+++ b/src/widgets/util/qflickgesture.cpp
@@ -228,7 +228,7 @@ public:
// we did send a press, so we need to fake a release now
// release all pressed mouse buttons
- /* Qt::MouseButtons mouseButtons = QApplication::mouseButtons();
+ /* Qt::MouseButtons mouseButtons = QGuiApplication::mouseButtons();
for (int i = 0; i < 32; ++i) {
if (mouseButtons & (1 << i)) {
Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i);
@@ -237,7 +237,7 @@ public:
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway,
- b, mouseButtons, QApplication::keyboardModifiers());
+ b, mouseButtons, QGuiApplication::keyboardModifiers());
sendMouseEvent(&re);
}
}*/
@@ -246,8 +246,8 @@ public:
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, farFarAway,
- mouseButton, QApplication::mouseButtons() & ~mouseButton,
- QApplication::keyboardModifiers(), mouseEventSource);
+ mouseButton, QGuiApplication::mouseButtons() & ~mouseButton,
+ QGuiApplication::keyboardModifiers(), mouseEventSource);
sendMouseEvent(&re, RegrabMouseAfterwards);
// don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release!
}
@@ -462,21 +462,6 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
}
break;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // the only way to distinguish between real mouse wheels and wheel
- // events generated by the native 2 finger swipe gesture is to listen
- // for these events (according to Apple's Cocoa Event-Handling Guide)
-
- case QEvent::NativeGesture: {
- QNativeGestureEvent *nge = static_cast<QNativeGestureEvent *>(event);
- if (nge->gestureType == QNativeGestureEvent::GestureBegin)
- d->macIgnoreWheel = true;
- else if (nge->gestureType == QNativeGestureEvent::GestureEnd)
- d->macIgnoreWheel = false;
- break;
- }
-#endif
-
// consume all wheel events if the scroller is active
case QEvent::Wheel:
if (d->macIgnoreWheel || (scroller->state() != QScroller::Inactive))
diff --git a/src/widgets/util/qflickgesture_p.h b/src/widgets/util/qflickgesture_p.h
index d5ace887ae..0b47516047 100644
--- a/src/widgets/util/qflickgesture_p.h
+++ b/src/widgets/util/qflickgesture_p.h
@@ -71,7 +71,7 @@ class Q_WIDGETS_EXPORT QFlickGesture : public QGesture
Q_DECLARE_PRIVATE(QFlickGesture)
public:
- QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent = 0);
+ QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent = nullptr);
~QFlickGesture();
friend class QFlickGestureRecognizer;
diff --git a/src/widgets/util/qscroller.cpp b/src/widgets/util/qscroller.cpp
index 1e84237253..df05bbf71c 100644
--- a/src/widgets/util/qscroller.cpp
+++ b/src/widgets/util/qscroller.cpp
@@ -1031,7 +1031,8 @@ void QScrollerPrivate::setDpi(const QPointF &dpi)
*/
void QScrollerPrivate::setDpiFromWidget(QWidget *widget)
{
- const QScreen *screen = QGuiApplication::screens().at(QApplication::desktop()->screenNumber(widget));
+ const QScreen *screen = widget ? widget->screen() : QGuiApplication::primaryScreen();
+ Q_ASSERT(screen);
setDpi(QPointF(screen->physicalDotsPerInchX(), screen->physicalDotsPerInchY()));
}
diff --git a/src/widgets/util/qscroller_mac.mm b/src/widgets/util/qscroller_mac.mm
deleted file mode 100644
index 6dbb483089..0000000000
--- a/src/widgets/util/qscroller_mac.mm
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtWidgets module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtCore/qglobal.h>
-
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-
-#import <AppKit/AppKit.h>
-
-#include "qscroller_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QPointF QScrollerPrivate::realDpi(int screen) const
-{
- QMacAutoReleasePool pool;
- NSArray *nsscreens = [NSScreen screens];
-
- if (screen < 0 || screen >= int([nsscreens count]))
- screen = 0;
-
- NSScreen *nsscreen = [nsscreens objectAtIndex:screen];
- CGDirectDisplayID display = [[[nsscreen deviceDescription] objectForKey:@"NSScreenNumber"] intValue];
-
- CGSize mmsize = CGDisplayScreenSize(display);
- if (mmsize.width > 0 && mmsize.height > 0) {
- return QPointF(CGDisplayPixelsWide(display) / mmsize.width,
- CGDisplayPixelsHigh(display) / mmsize.height) * qreal(25.4);
- } else {
- return QPointF();
- }
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/util/qscrollerproperties.cpp b/src/widgets/util/qscrollerproperties.cpp
index c26fba2cd3..df6b899fe4 100644
--- a/src/widgets/util/qscrollerproperties.cpp
+++ b/src/widgets/util/qscrollerproperties.cpp
@@ -40,9 +40,6 @@
#include <QPointer>
#include <QObject>
#include <QtCore/qmath.h>
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
-# include <QLibrary>
-#endif
#include "qscrollerproperties.h"
#include "private/qscrollerproperties_p.h"
@@ -73,10 +70,6 @@ QScrollerPropertiesPrivate *QScrollerPropertiesPrivate::defaults()
spp.overshootDragDistanceFactor = qreal(1);
spp.overshootScrollDistanceFactor = qreal(0.5);
spp.overshootScrollTime = qreal(0.7);
-# if 0 // Used to be included in Qt4 for Q_WS_WIN
- if (QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback"))
- spp.overshootScrollTime = qreal(0.35);
-# endif
spp.hOvershootPolicy = QScrollerProperties::OvershootWhenScrollable;
spp.vOvershootPolicy = QScrollerProperties::OvershootWhenScrollable;
spp.frameRate = QScrollerProperties::Standard;
diff --git a/src/widgets/util/qsystemtrayicon.cpp b/src/widgets/util/qsystemtrayicon.cpp
index a38a50d3df..fd18888870 100644
--- a/src/widgets/util/qsystemtrayicon.cpp
+++ b/src/widgets/util/qsystemtrayicon.cpp
@@ -626,16 +626,6 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
}
QPainterPath path;
-#if defined(QT_NO_XSHAPE) && 0 /* Used to be included in Qt4 for Q_WS_X11 */
- // XShape is required for setting the mask, so we just
- // draw an ugly square when its not available
- path.moveTo(0, 0);
- path.lineTo(sz.width() - 1, 0);
- path.lineTo(sz.width() - 1, sz.height() - 1);
- path.lineTo(0, sz.height() - 1);
- path.lineTo(0, 0);
- move(qMax(pos.x() - sz.width(), scr.left()), pos.y());
-#else
path.moveTo(ml + rc, mt);
if (arrowAtTop && arrowAtLeft) {
if (showArrow) {
@@ -685,7 +675,6 @@ void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
painter1.setBrush(QBrush(Qt::color1));
painter1.drawPath(path);
setMask(bitmap);
-#endif
// Draw the border
pixmap = QPixmap(sz);
diff --git a/src/widgets/util/qsystemtrayicon_x11.cpp b/src/widgets/util/qsystemtrayicon_x11.cpp
index 70e5f3678e..0c7bb94a91 100644
--- a/src/widgets/util/qsystemtrayicon_x11.cpp
+++ b/src/widgets/util/qsystemtrayicon_x11.cpp
@@ -151,11 +151,11 @@ bool QSystemTrayIconSys::event(QEvent *e)
{
switch (e->type()) {
case QEvent::ToolTip:
- QApplication::sendEvent(q, e);
+ QCoreApplication::sendEvent(q, e);
break;
#if QT_CONFIG(wheelevent)
case QEvent::Wheel:
- return QApplication::sendEvent(q, e);
+ return QCoreApplication::sendEvent(q, e);
#endif
default:
break;
diff --git a/src/widgets/util/qundostack_p.h b/src/widgets/util/qundostack_p.h
index 04bc381114..05c9e0d27e 100644
--- a/src/widgets/util/qundostack_p.h
+++ b/src/widgets/util/qundostack_p.h
@@ -80,7 +80,7 @@ class QUndoStackPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QUndoStack)
public:
- QUndoStackPrivate() : index(0), clean_index(0), group(0), undo_limit(0) {}
+ QUndoStackPrivate() : index(0), clean_index(0), group(nullptr), undo_limit(0) {}
QList<QUndoCommand*> command_list;
QList<QUndoCommand*> macro_stack;
@@ -98,7 +98,7 @@ class QUndoAction : public QAction
{
Q_OBJECT
public:
- explicit QUndoAction(const QString &prefix, QObject *parent = 0);
+ explicit QUndoAction(const QString &prefix, QObject *parent = nullptr);
void setTextFormat(const QString &textFormat, const QString &defaultText);
public Q_SLOTS:
void setPrefixedText(const QString &text);
diff --git a/src/widgets/util/util.pri b/src/widgets/util/util.pri
index a3bd8897f1..363291528e 100644
--- a/src/widgets/util/util.pri
+++ b/src/widgets/util/util.pri
@@ -54,7 +54,3 @@ qtConfig(xcb) {
} else {
SOURCES += util/qsystemtrayicon_qpa.cpp
}
-
-mac {
- OBJECTIVE_SOURCES += util/qscroller_mac.mm
-}
diff --git a/src/widgets/widgets.pro b/src/widgets/widgets.pro
index e556cb8b10..6f807e1696 100644
--- a/src/widgets/widgets.pro
+++ b/src/widgets/widgets.pro
@@ -32,8 +32,6 @@ qtConfig(graphicseffect) {
QMAKE_LIBS += $$QMAKE_LIBS_GUI
-contains(DEFINES,QT_EVAL):include($$QT_SOURCE_TREE/src/corelib/eval.pri)
-
QMAKE_DYNAMIC_LIST_FILE = $$PWD/QtWidgets.dynlist
# Code coverage with TestCocoon
diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp
index f30a3bc7b8..d956d2ba23 100644
--- a/src/widgets/widgets/qabstractbutton.cpp
+++ b/src/widgets/widgets/qabstractbutton.cpp
@@ -44,6 +44,7 @@
#endif
#if QT_CONFIG(buttongroup)
#include "qbuttongroup.h"
+#include "private/qapplication_p.h"
#include "private/qbuttongroup_p.h"
#endif
#include "qabstractbutton_p.h"
@@ -319,7 +320,7 @@ void QAbstractButtonPrivate::moveFocus(int key)
if (exclusive
#ifdef QT_KEYPAD_NAVIGATION
- && !QApplication::keypadNavigationEnabled()
+ && !QApplicationPrivate::keypadNavigationEnabled()
#endif
&& candidate
&& fb->d_func()->checked
@@ -1063,7 +1064,7 @@ void QAbstractButton::keyPressEvent(QKeyEvent *e)
case Qt::Key_Right:
case Qt::Key_Down: {
#ifdef QT_KEYPAD_NAVIGATION
- if ((QApplication::keypadNavigationEnabled()
+ if ((QApplicationPrivate::keypadNavigationEnabled()
&& (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
|| (!QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
|| (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down))) {
@@ -1159,7 +1160,7 @@ void QAbstractButton::focusInEvent(QFocusEvent *e)
{
Q_D(QAbstractButton);
#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled())
+ if (!QApplicationPrivate::keypadNavigationEnabled())
#endif
d->fixFocusPolicy();
QWidget::focusInEvent(e);
diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp
index 5ea8330db2..d2372a7be9 100644
--- a/src/widgets/widgets/qabstractscrollarea.cpp
+++ b/src/widgets/widgets/qabstractscrollarea.cpp
@@ -62,10 +62,6 @@
#include <private/qapplication_p.h>
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
#ifdef Q_OS_WIN
# include <qt_windows.h>
#endif
@@ -169,9 +165,6 @@ QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate()
shownOnce(false), inResize(false), sizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored),
viewport(0), cornerWidget(0), left(0), top(0), right(0), bottom(0),
xoffset(0), yoffset(0), viewportFilter(0)
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- , singleFingerPanEnabled(false)
-#endif
{
}
@@ -322,16 +315,6 @@ void QAbstractScrollAreaPrivate::init()
#endif
}
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
-void QAbstractScrollAreaPrivate::setSingleFingerPanEnabled(bool on)
-{
- singleFingerPanEnabled = on;
- QWidgetPrivate *dd = static_cast<QWidgetPrivate *>(QObjectPrivate::get(viewport));
- if (dd)
- dd->winSetupGestures();
-}
-#endif
-
void QAbstractScrollAreaPrivate::layoutChildren()
{
bool needH = false;
@@ -362,38 +345,6 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, hbar);
const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, vbar);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- QWidget * const window = q->window();
-
- // Use small scroll bars for tool windows, to match the native size grip.
- bool hbarIsSmall = hbar->testAttribute(Qt::WA_MacSmallSize);
- bool vbarIsSmall = vbar->testAttribute(Qt::WA_MacSmallSize);
- const Qt::WindowType windowType = window->windowType();
- if (windowType == Qt::Tool) {
- if (!hbarIsSmall) {
- hbar->setAttribute(Qt::WA_MacMiniSize, false);
- hbar->setAttribute(Qt::WA_MacNormalSize, false);
- hbar->setAttribute(Qt::WA_MacSmallSize, true);
- }
- if (!vbarIsSmall) {
- vbar->setAttribute(Qt::WA_MacMiniSize, false);
- vbar->setAttribute(Qt::WA_MacNormalSize, false);
- vbar->setAttribute(Qt::WA_MacSmallSize, true);
- }
- } else {
- if (hbarIsSmall) {
- hbar->setAttribute(Qt::WA_MacMiniSize, false);
- hbar->setAttribute(Qt::WA_MacNormalSize, false);
- hbar->setAttribute(Qt::WA_MacSmallSize, false);
- }
- if (vbarIsSmall) {
- vbar->setAttribute(Qt::WA_MacMiniSize, false);
- vbar->setAttribute(Qt::WA_MacNormalSize, false);
- vbar->setAttribute(Qt::WA_MacSmallSize, false);
- }
- }
-#endif
-
const int hsbExt = hbar->sizeHint().height();
const int vsbExt = vbar->sizeHint().width();
const QPoint extPoint(vsbExt, hsbExt);
@@ -403,30 +354,6 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
const bool hasCornerWidget = (cornerWidget != 0);
-// If the scroll bars are at the very right and bottom of the window we
-// move their positions to be aligned with the size grip.
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // Check if a native sizegrip is present.
- bool hasMacReverseSizeGrip = false;
- bool hasMacSizeGrip = false;
- bool nativeGripPresent = false;
- if (q->testAttribute(Qt::WA_WState_Created))
- nativeGripPresent = qt_mac_checkForNativeSizeGrip(q);
-
- if (nativeGripPresent) {
- // Look for a native size grip at the visual window bottom right and at the
- // absolute window bottom right. In reverse mode, the native size grip does not
- // swich side, so we need to check if it is on the "wrong side".
- const QPoint scrollAreaBottomRight = q->mapTo(window, widgetRect.bottomRight() - QPoint(frameWidth, frameWidth));
- const QPoint windowBottomRight = window->rect().bottomRight();
- const QPoint visualWindowBottomRight = QStyle::visualPos(opt.direction, opt.rect, windowBottomRight);
- const QPoint offset = windowBottomRight - scrollAreaBottomRight;
- const QPoint visualOffset = visualWindowBottomRight - scrollAreaBottomRight;
- hasMacSizeGrip = (visualOffset.manhattanLength() < vsbExt);
- hasMacReverseSizeGrip = (hasMacSizeGrip == false && (offset.manhattanLength() < hsbExt));
- }
-#endif
-
QPoint cornerOffset((needv && vscrollOverlap == 0) ? vsbExt : 0, (needh && hscrollOverlap == 0) ? hsbExt : 0);
QRect controlsRect;
QRect viewportRect;
@@ -458,12 +385,6 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
if (hasCornerWidget && ((needv && vscrollOverlap == 0) || (needh && hscrollOverlap == 0)))
cornerOffset = extPoint;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- // Also move the scroll bars if they are covered by the native Mac size grip.
- if (hasMacSizeGrip)
- cornerOffset = extPoint;
-#endif
-
// The corner point is where the scroll bar rects, the corner widget rect and the
// viewport rect meets.
const QPoint cornerPoint(controlsRect.bottomRight() + QPoint(1, 1) - cornerOffset);
@@ -475,13 +396,6 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
else
cornerPaintingRect = QRect();
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (hasMacReverseSizeGrip)
- reverseCornerPaintingRect = QRect(controlsRect.bottomRight() + QPoint(1, 1) - extPoint, extSize);
- else
- reverseCornerPaintingRect = QRect();
-#endif
-
// move the scrollbars away from top/left headers
int vHeaderRight = 0;
int hHeaderBottom = 0;
@@ -501,10 +415,7 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol
#endif // QT_CONFIG(itemviews)
if (needh) {
QRect horizontalScrollBarRect(QPoint(controlsRect.left() + vHeaderRight, cornerPoint.y()), QPoint(cornerPoint.x() - 1, controlsRect.bottom()));
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (hasMacReverseSizeGrip)
- horizontalScrollBarRect.adjust(vsbExt, 0, 0, 0);
-#endif
+
if (!hasCornerWidget && htransient)
horizontalScrollBarRect.adjust(0, 0, cornerOffset.x(), 0);
scrollBarContainers[Qt::Horizontal]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, horizontalScrollBarRect));
@@ -617,11 +528,9 @@ void QAbstractScrollArea::setViewport(QWidget *widget)
d->viewport->setParent(this);
d->viewport->setFocusProxy(this);
d->viewport->installEventFilter(d->viewportFilter.data());
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
#ifndef QT_NO_GESTURES
d->viewport->grabGesture(Qt::PanGesture);
#endif
-#endif
d->layoutChildren();
#ifndef QT_NO_OPENGL
QWidgetPrivate::get(d->viewport)->initializeViewportFramebuffer();
@@ -1043,13 +952,6 @@ bool QAbstractScrollArea::event(QEvent *e)
QPainter p(this);
style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (d->reverseCornerPaintingRect.isValid()) {
- option.rect = d->reverseCornerPaintingRect;
- QPainter p(this);
- style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
- }
-#endif
}
QFrame::paintEvent((QPaintEvent*)e);
break;
@@ -1086,7 +988,7 @@ bool QAbstractScrollArea::event(QEvent *e)
QScrollBar *vBar = verticalScrollBar();
QPointF delta = g->delta();
if (!delta.isNull()) {
- if (QApplication::isRightToLeft())
+ if (QGuiApplication::isRightToLeft())
delta.rx() *= -1;
int newX = hBar->value() - delta.x();
int newY = vBar->value() - delta.y();
@@ -1122,38 +1024,10 @@ bool QAbstractScrollArea::event(QEvent *e)
hBar->setValue(se->contentPos().x());
vBar->setValue(se->contentPos().y());
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- typedef BOOL (*PtrBeginPanningFeedback)(HWND);
- typedef BOOL (*PtrUpdatePanningFeedback)(HWND, LONG, LONG, BOOL);
- typedef BOOL (*PtrEndPanningFeedback)(HWND, BOOL);
-
- static PtrBeginPanningFeedback ptrBeginPanningFeedback = 0;
- static PtrUpdatePanningFeedback ptrUpdatePanningFeedback = 0;
- static PtrEndPanningFeedback ptrEndPanningFeedback = 0;
-
- if (!ptrBeginPanningFeedback)
- ptrBeginPanningFeedback = (PtrBeginPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "BeginPanningFeedback");
- if (!ptrUpdatePanningFeedback)
- ptrUpdatePanningFeedback = (PtrUpdatePanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "UpdatePanningFeedback");
- if (!ptrEndPanningFeedback)
- ptrEndPanningFeedback = (PtrEndPanningFeedback) QLibrary::resolve(QLatin1String("UxTheme"), "EndPanningFeedback");
-
- if (ptrBeginPanningFeedback && ptrUpdatePanningFeedback && ptrEndPanningFeedback) {
- WId wid = window()->winId();
-
- if (!se->overshootDistance().isNull() && d->overshoot.isNull())
- ptrBeginPanningFeedback(wid);
- if (!se->overshootDistance().isNull())
- ptrUpdatePanningFeedback(wid, -se->overshootDistance().x(), -se->overshootDistance().y(), false);
- if (se->overshootDistance().isNull() && !d->overshoot.isNull())
- ptrEndPanningFeedback(wid, true);
- } else
-#endif
- {
- QPoint delta = d->overshoot - se->overshootDistance().toPoint();
- if (!delta.isNull())
- viewport()->move(viewport()->pos() + delta);
- }
+ QPoint delta = d->overshoot - se->overshootDistance().toPoint();
+ if (!delta.isNull())
+ viewport()->move(viewport()->pos() + delta);
+
d->overshoot = se->overshootDistance().toPoint();
return true;
@@ -1270,11 +1144,14 @@ void QAbstractScrollArea::paintEvent(QPaintEvent*)
mouse press events for the viewport() widget. The event is passed
in \a e.
+ The default implementation calls QWidget::mousePressEvent() for
+ default popup handling.
+
\sa QWidget::mousePressEvent()
*/
void QAbstractScrollArea::mousePressEvent(QMouseEvent *e)
{
- e->ignore();
+ QWidget::mousePressEvent(e);
}
/*!
@@ -1324,10 +1201,10 @@ void QAbstractScrollArea::mouseMoveEvent(QMouseEvent *e)
void QAbstractScrollArea::wheelEvent(QWheelEvent *e)
{
Q_D(QAbstractScrollArea);
- if (e->orientation() == Qt::Horizontal)
- QApplication::sendEvent(d->hbar, e);
+ if (qAbs(e->angleDelta().x()) > qAbs(e->angleDelta().y()))
+ QCoreApplication::sendEvent(d->hbar, e);
else
- QApplication::sendEvent(d->vbar, e);
+ QCoreApplication::sendEvent(d->vbar, e);
}
#endif
@@ -1362,7 +1239,7 @@ void QAbstractScrollArea::keyPressEvent(QKeyEvent * e)
#endif
} else {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
e->ignore();
return;
}
@@ -1376,7 +1253,7 @@ void QAbstractScrollArea::keyPressEvent(QKeyEvent * e)
break;
case Qt::Key_Left:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()
+ if (QApplicationPrivate::keypadNavigationEnabled() && hasEditFocus()
&& (!d->hbar->isVisible() || d->hbar->value() == d->hbar->minimum())) {
//if we aren't using the hbar or we are already at the leftmost point ignore
e->ignore();
@@ -1389,7 +1266,7 @@ void QAbstractScrollArea::keyPressEvent(QKeyEvent * e)
break;
case Qt::Key_Right:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()
+ if (QApplicationPrivate::keypadNavigationEnabled() && hasEditFocus()
&& (!d->hbar->isVisible() || d->hbar->value() == d->hbar->maximum())) {
//if we aren't using the hbar or we are already at the rightmost point ignore
e->ignore();
@@ -1546,13 +1423,6 @@ void QAbstractScrollAreaPrivate::_q_vslide(int y)
void QAbstractScrollAreaPrivate::_q_showOrHideScrollBars()
{
layoutChildren();
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- // Need to re-subscribe to gestures as the content changes to make sure we
- // enable/disable panning when needed.
- QWidgetPrivate *dd = static_cast<QWidgetPrivate *>(QObjectPrivate::get(viewport));
- if (dd)
- dd->winSetupGestures();
-#endif
}
QPoint QAbstractScrollAreaPrivate::contentsOffset() const
diff --git a/src/widgets/widgets/qabstractscrollarea_p.h b/src/widgets/widgets/qabstractscrollarea_p.h
index 732a2ab40d..6d78b9db6d 100644
--- a/src/widgets/widgets/qabstractscrollarea_p.h
+++ b/src/widgets/widgets/qabstractscrollarea_p.h
@@ -85,9 +85,7 @@ public:
QWidget *viewport;
QWidget *cornerWidget;
QRect cornerPaintingRect;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- QRect reverseCornerPaintingRect;
-#endif
+
int left, top, right, bottom; // viewport margin
int xoffset, yoffset;
@@ -112,11 +110,6 @@ public:
inline bool viewportEvent(QEvent *event)
{ return q_func()->viewportEvent(event); }
QScopedPointer<QObject> viewportFilter;
-
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- bool singleFingerPanEnabled;
- void setSingleFingerPanEnabled(bool on = true);
-#endif
};
class QAbstractScrollAreaFilter : public QObject
diff --git a/src/widgets/widgets/qabstractslider.cpp b/src/widgets/widgets/qabstractslider.cpp
index 2172ebc99c..dc325ab871 100644
--- a/src/widgets/widgets/qabstractslider.cpp
+++ b/src/widgets/widgets/qabstractslider.cpp
@@ -47,6 +47,8 @@
#endif
#include <limits.h>
+#include <private/qapplication_p.h>
+
QT_BEGIN_NAMESPACE
/*!
@@ -719,15 +721,10 @@ bool QAbstractSliderPrivate::scrollByDelta(Qt::Orientation orientation, Qt::Keyb
offset_accumulated = 0;
offset_accumulated += stepsToScrollF;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
+
// Don't scroll more than one page in any case:
stepsToScroll = qBound(-pageStep, int(offset_accumulated), pageStep);
-#else
- // Native UI-elements on Mac can scroll hundreds of lines at a time as
- // a result of acceleration. So keep the same behaviour in Qt, and
- // don't restrict stepsToScroll to certain maximum (pageStep):
- stepsToScroll = int(offset_accumulated);
-#endif
+
offset_accumulated -= int(offset_accumulated);
if (stepsToScroll == 0) {
// We moved less than a line, but might still have accumulated partial scroll,
@@ -764,10 +761,11 @@ void QAbstractSlider::wheelEvent(QWheelEvent * e)
{
Q_D(QAbstractSlider);
e->ignore();
- int delta = e->delta();
+ bool vertical = bool(e->angleDelta().y());
+ int delta = vertical ? e->angleDelta().y() : e->angleDelta().x();
if (e->inverted())
delta = -delta;
- if (d->scrollByDelta(e->orientation(), e->modifiers(), delta))
+ if (d->scrollByDelta(vertical ? Qt::Vertical : Qt::Horizontal, e->modifiers(), delta))
e->accept();
}
@@ -815,13 +813,13 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
switch (ev->key()) {
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
setEditFocus(!hasEditFocus());
else
ev->ignore();
break;
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && hasEditFocus()) {
setValue(d->origValue);
setEditFocus(false);
} else
@@ -834,7 +832,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
// In QApplication::KeypadNavigationDirectional, we want to change the slider
// value if there is no left/right navigation possible and if this slider is not
// inside a tab widget.
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
|| d->orientation == Qt::Vertical
|| !hasEditFocus()
@@ -842,7 +840,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
ev->ignore();
return;
}
- if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
+ if (QApplicationPrivate::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
action = d->invertedControls ? SliderSingleStepSub : SliderSingleStepAdd;
else
#endif
@@ -854,7 +852,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
case Qt::Key_Right:
#ifdef QT_KEYPAD_NAVIGATION
// Same logic as in Qt::Key_Left
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& (!hasEditFocus() && QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
|| d->orientation == Qt::Vertical
|| !hasEditFocus()
@@ -862,7 +860,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
ev->ignore();
return;
}
- if (QApplication::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
+ if (QApplicationPrivate::keypadNavigationEnabled() && d->orientation == Qt::Vertical)
action = d->invertedControls ? SliderSingleStepAdd : SliderSingleStepSub;
else
#endif
@@ -875,7 +873,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
#ifdef QT_KEYPAD_NAVIGATION
// In QApplication::KeypadNavigationDirectional, we want to change the slider
// value if there is no up/down navigation possible.
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
|| d->orientation == Qt::Horizontal
|| !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
@@ -888,7 +886,7 @@ void QAbstractSlider::keyPressEvent(QKeyEvent *ev)
case Qt::Key_Down:
#ifdef QT_KEYPAD_NAVIGATION
// Same logic as in Qt::Key_Up
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder
|| d->orientation == Qt::Horizontal
|| !hasEditFocus() && QWidgetPrivate::canKeypadNavigate(Qt::Vertical))) {
diff --git a/src/widgets/widgets/qabstractslider_p.h b/src/widgets/widgets/qabstractslider_p.h
index 419ce2ba07..1b8c76c7ec 100644
--- a/src/widgets/widgets/qabstractslider_p.h
+++ b/src/widgets/widgets/qabstractslider_p.h
@@ -134,7 +134,7 @@ public:
inline void setAdjustedSliderPosition(int position)
{
Q_Q(QAbstractSlider);
- if (q->style()->styleHint(QStyle::SH_Slider_StopMouseOverSlider, 0, q)) {
+ if (q->style()->styleHint(QStyle::SH_Slider_StopMouseOverSlider, nullptr, q)) {
if ((position > pressValue - 2 * pageStep) && (position < pressValue + 2 * pageStep)) {
repeatAction = QAbstractSlider::SliderNoAction;
q->setSliderPosition(pressValue);
diff --git a/src/widgets/widgets/qabstractspinbox.cpp b/src/widgets/widgets/qabstractspinbox.cpp
index f30ea35303..fc19e0793e 100644
--- a/src/widgets/widgets/qabstractspinbox.cpp
+++ b/src/widgets/widgets/qabstractspinbox.cpp
@@ -39,6 +39,7 @@
#include <qplatformdefs.h>
#include <private/qabstractspinbox_p.h>
+#include <private/qapplication_p.h>
#if QT_CONFIG(datetimeparser)
#include <private/qdatetimeparser_p.h>
#endif
@@ -253,7 +254,7 @@ QString QAbstractSpinBox::text() const
All values are displayed with the prefix and suffix (if set), \e
except for the special value, which only shows the special value
- text. This special text is passed in the QSpinBox::valueChanged()
+ text. This special text is passed in the QSpinBox::textChanged()
signal that passes a QString.
To turn off the special-value text display, call this function
@@ -333,7 +334,7 @@ void QAbstractSpinBox::setReadOnly(bool enable)
d->readOnly = enable;
d->edit->setReadOnly(enable);
QEvent event(QEvent::ReadOnlyChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
update();
}
@@ -343,18 +344,18 @@ void QAbstractSpinBox::setReadOnly(bool enable)
\since 4.3
If keyboard tracking is enabled (the default), the spinbox
- emits the valueChanged() signal while the new value is being
- entered from the keyboard.
+ emits the valueChanged() and textChanged() signals while the
+ new value is being entered from the keyboard.
E.g. when the user enters the value 600 by typing 6, 0, and 0,
the spinbox emits 3 signals with the values 6, 60, and 600
respectively.
If keyboard tracking is disabled, the spinbox doesn't emit the
- valueChanged() signal while typing. It emits the signal later,
- when the return key is pressed, when keyboard focus is lost, or
- when other spinbox functionality is used, e.g. pressing an arrow
- key.
+ valueChanged() and textChanged() signals while typing. It emits
+ the signals later, when the return key is pressed, when keyboard
+ focus is lost, or when other spinbox functionality is used, e.g.
+ pressing an arrow key.
*/
bool QAbstractSpinBox::keyboardTracking() const
@@ -574,10 +575,10 @@ QAbstractSpinBox::StepEnabled QAbstractSpinBox::stepEnabled() const
if (d->wrapping)
return StepEnabled(StepUpEnabled | StepDownEnabled);
StepEnabled ret = StepNone;
- if (d->variantCompare(d->value, d->maximum) < 0) {
+ if (QAbstractSpinBoxPrivate::variantCompare(d->value, d->maximum) < 0) {
ret |= StepUpEnabled;
}
- if (d->variantCompare(d->value, d->minimum) > 0) {
+ if (QAbstractSpinBoxPrivate::variantCompare(d->value, d->minimum) > 0) {
ret |= StepDownEnabled;
}
return ret;
@@ -803,7 +804,7 @@ bool QAbstractSpinBox::event(QEvent *event)
#ifdef QT_KEYPAD_NAVIGATION
case QEvent::EnterEditFocus:
case QEvent::LeaveEditFocus:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
const bool b = d->edit->event(event);
d->edit->setSelection(d->edit->displayText().size() - d->suffix.size(),0);
if (event->type() == QEvent::LeaveEditFocus)
@@ -1025,7 +1026,7 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
case Qt::Key_Up:
case Qt::Key_Down: {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// Reserve up/down for nav - use left/right for edit.
if (!hasEditFocus() && (event->key() == Qt::Key_Up
|| event->key() == Qt::Key_Down)) {
@@ -1061,13 +1062,13 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Left:
case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
event->ignore();
return;
}
break;
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
event->ignore();
return;
}
@@ -1085,7 +1086,7 @@ void QAbstractSpinBox::keyPressEvent(QKeyEvent *event)
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// Toggles between left/right moving cursor and inc/dec.
setEditFocus(!hasEditFocus());
}
@@ -1221,7 +1222,7 @@ void QAbstractSpinBox::focusOutEvent(QFocusEvent *event)
#ifdef QT_KEYPAD_NAVIGATION
// editingFinished() is already emitted on LeaveEditFocus
- if (!QApplication::keypadNavigationEnabled())
+ if (!QApplicationPrivate::keypadNavigationEnabled())
#endif
emit editingFinished();
}
@@ -1320,6 +1321,9 @@ void QAbstractSpinBox::contextMenuEvent(QContextMenuEvent *event)
d->reset();
QAction *selAll = new QAction(tr("&Select All"), menu);
+#if QT_CONFIG(shortcut)
+ selAll->setShortcut(QKeySequence::SelectAll);
+#endif
menu->insertAction(d->edit->d_func()->selectAllAction,
selAll);
menu->removeAction(d->edit->d_func()->selectAllAction);
@@ -1722,7 +1726,7 @@ void QAbstractSpinBox::initStyleOption(QStyleOptionSpinBox *option) const
option->activeSubControls = d->hoverControl;
}
- option->stepEnabled = style()->styleHint(QStyle::SH_SpinControls_DisableOnBounds)
+ option->stepEnabled = style()->styleHint(QStyle::SH_SpinControls_DisableOnBounds, nullptr, this)
? stepEnabled()
: (QAbstractSpinBox::StepDownEnabled|QAbstractSpinBox::StepUpEnabled);
@@ -2031,8 +2035,8 @@ QVariant operator+(const QVariant &arg1, const QVariant &arg2)
#if QT_CONFIG(datetimeparser)
case QVariant::DateTime: {
QDateTime a2 = arg2.toDateTime();
- QDateTime a1 = arg1.toDateTime().addDays(QDATETIMEEDIT_DATETIME_MIN.daysTo(a2));
- a1.setTime(a1.time().addMSecs(QTime().msecsTo(a2.time())));
+ QDateTime a1 = arg1.toDateTime().addDays(QDATETIMEEDIT_DATE_MIN.daysTo(a2.date()));
+ a1.setTime(a1.time().addMSecs(a2.time().msecsSinceStartOfDay()));
ret = QVariant(a1);
break;
}
@@ -2094,11 +2098,11 @@ QVariant operator*(const QVariant &arg1, double multiplier)
#if QT_CONFIG(datetimeparser)
case QVariant::DateTime: {
double days = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDateTime().date()) * multiplier;
- int daysInt = (int)days;
+ const qint64 daysInt = qint64(days);
days -= daysInt;
- long msecs = (long)((QDATETIMEEDIT_TIME_MIN.msecsTo(arg1.toDateTime().time()) * multiplier)
- + (days * (24 * 3600 * 1000)));
- ret = QDateTime(QDate().addDays(int(days)), QTime().addMSecs(msecs));
+ qint64 msecs = qint64(arg1.toDateTime().time().msecsSinceStartOfDay() * multiplier
+ + days * (24 * 3600 * 1000));
+ ret = QDATETIMEEDIT_DATE_MIN.addDays(daysInt).startOfDay().addMSecs(msecs);
break;
}
#endif // datetimeparser
@@ -2128,8 +2132,8 @@ double operator/(const QVariant &arg1, const QVariant &arg2)
case QVariant::DateTime:
a1 = QDATETIMEEDIT_DATE_MIN.daysTo(arg1.toDate());
a2 = QDATETIMEEDIT_DATE_MIN.daysTo(arg2.toDate());
- a1 += (double)QDATETIMEEDIT_TIME_MIN.msecsTo(arg1.toDateTime().time()) / (long)(3600 * 24 * 1000);
- a2 += (double)QDATETIMEEDIT_TIME_MIN.msecsTo(arg2.toDateTime().time()) / (long)(3600 * 24 * 1000);
+ a1 += arg1.toDateTime().time().msecsSinceStartOfDay() / (36e5 * 24);
+ a2 += arg2.toDateTime().time().msecsSinceStartOfDay() / (36e5 * 24);
break;
#endif // datetimeparser
default: break;
diff --git a/src/widgets/widgets/qabstractspinbox_p.h b/src/widgets/widgets/qabstractspinbox_p.h
index fce88e43f4..ad169fde19 100644
--- a/src/widgets/widgets/qabstractspinbox_p.h
+++ b/src/widgets/widgets/qabstractspinbox_p.h
@@ -97,7 +97,7 @@ public:
void init();
void reset();
void updateState(bool up, bool fromKeyboard = false);
- QString stripped(const QString &text, int *pos = 0) const;
+ QString stripped(const QString &text, int *pos = nullptr) const;
bool specialValue() const;
virtual QVariant getZeroVariant() const;
virtual void setRange(const QVariant &min, const QVariant &max);
diff --git a/src/widgets/widgets/qcalendarwidget.cpp b/src/widgets/widgets/qcalendarwidget.cpp
index 47c5267c73..8593001f8b 100644
--- a/src/widgets/widgets/qcalendarwidget.cpp
+++ b/src/widgets/widgets/qcalendarwidget.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -54,8 +54,10 @@
#include <qspinbox.h>
#include <qmenu.h>
#include <qapplication.h>
+#include <private/qapplication_p.h>
#include <qbasictimer.h>
#include <qstylepainter.h>
+#include <qcalendar.h>
#include <vector>
@@ -89,16 +91,15 @@ public:
QCalendarDateSectionValidator() {}
virtual ~QCalendarDateSectionValidator() {}
virtual Section handleKey(int key) = 0;
- virtual QDate applyToDate(const QDate &date) const = 0;
- virtual void setDate(const QDate &date) = 0;
+ virtual QDate applyToDate(QDate date, QCalendar cal = QCalendar()) const = 0;
+ virtual void setDate(QDate date, QCalendar cal = QCalendar()) = 0;
virtual QString text() const = 0;
- virtual QString text(const QDate &date, int repeat) const = 0;
+ virtual QString text(QDate date, QCalendar cal, int repeat) const = 0;
QLocale m_locale;
protected:
static QString highlightString(const QString &str, int pos);
-private:
};
QString QCalendarDateSectionValidator::highlightString(const QString &str, int pos)
@@ -116,10 +117,10 @@ class QCalendarDayValidator : public QCalendarDateSectionValidator
public:
QCalendarDayValidator();
virtual Section handleKey(int key) override;
- virtual QDate applyToDate(const QDate &date) const override;
- virtual void setDate(const QDate &date) override;
+ virtual QDate applyToDate(QDate date, QCalendar cal) const override;
+ virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
- virtual QString text(const QDate &date, int repeat) const override;
+ virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int m_pos;
int m_day;
@@ -180,21 +181,18 @@ QCalendarDateSectionValidator::Section QCalendarDayValidator::handleKey(int key)
return QCalendarDateSectionValidator::ThisSection;
}
-QDate QCalendarDayValidator::applyToDate(const QDate &date) const
+QDate QCalendarDayValidator::applyToDate(QDate date, QCalendar cal) const
{
- int day = m_day;
- if (day < 1)
- day = 1;
- else if (day > 31)
- day = 31;
- if (day > date.daysInMonth())
- day = date.daysInMonth();
- return QDate(date.year(), date.month(), day);
+ auto parts = cal.partsFromDate(date);
+ if (!parts.isValid())
+ return QDate();
+ parts.day = qMin(qMax(1, m_day), cal.daysInMonth(parts.year, parts.month));
+ return cal.dateFromParts(parts);
}
-void QCalendarDayValidator::setDate(const QDate &date)
+void QCalendarDayValidator::setDate(QDate date, QCalendar cal)
{
- m_day = m_oldDay = date.day();
+ m_day = m_oldDay = date.day(cal);
m_pos = 0;
}
@@ -203,16 +201,16 @@ QString QCalendarDayValidator::text() const
return highlightString(formatNumber(m_day, 2), m_pos);
}
-QString QCalendarDayValidator::text(const QDate &date, int repeat) const
+QString QCalendarDayValidator::text(QDate date, QCalendar cal, int repeat) const
{
if (repeat <= 1) {
- return QString::number(date.day());
+ return QString::number(date.day(cal));
} else if (repeat == 2) {
- return formatNumber(date.day(), 2);
+ return formatNumber(date.day(cal), 2);
} else if (repeat == 3) {
- return m_locale.dayName(date.dayOfWeek(), QLocale::ShortFormat);
+ return m_locale.dayName(date.dayOfWeek(cal), QLocale::ShortFormat);
} else /* repeat >= 4 */ {
- return m_locale.dayName(date.dayOfWeek(), QLocale::LongFormat);
+ return m_locale.dayName(date.dayOfWeek(cal), QLocale::LongFormat);
}
}
@@ -224,10 +222,10 @@ class QCalendarMonthValidator : public QCalendarDateSectionValidator
public:
QCalendarMonthValidator();
virtual Section handleKey(int key) override;
- virtual QDate applyToDate(const QDate &date) const override;
- virtual void setDate(const QDate &date) override;
+ virtual QDate applyToDate(QDate date, QCalendar cal) const override;
+ virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
- virtual QString text(const QDate &date, int repeat) const override;
+ virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int m_pos;
int m_month;
@@ -288,23 +286,19 @@ QCalendarDateSectionValidator::Section QCalendarMonthValidator::handleKey(int ke
return QCalendarDateSectionValidator::ThisSection;
}
-QDate QCalendarMonthValidator::applyToDate(const QDate &date) const
+QDate QCalendarMonthValidator::applyToDate(QDate date, QCalendar cal) const
{
- int month = m_month;
- if (month < 1)
- month = 1;
- else if (month > 12)
- month = 12;
- QDate newDate(date.year(), m_month, 1);
- int day = date.day();
- if (day > newDate.daysInMonth())
- day = newDate.daysInMonth();
- return QDate(date.year(), month, day);
+ auto parts = cal.partsFromDate(date);
+ if (!parts.isValid())
+ return QDate();
+ parts.month = qMin(qMax(1, m_month), cal.monthsInYear(parts.year));
+ parts.day = qMin(parts.day, cal.daysInMonth(parts.year, m_month)); // m_month or parts.month ?
+ return cal.dateFromParts(parts);
}
-void QCalendarMonthValidator::setDate(const QDate &date)
+void QCalendarMonthValidator::setDate(QDate date, QCalendar cal)
{
- m_month = m_oldMonth = date.month();
+ m_month = m_oldMonth = date.month(cal);
m_pos = 0;
}
@@ -313,17 +307,19 @@ QString QCalendarMonthValidator::text() const
return highlightString(formatNumber(m_month, 2), m_pos);
}
-QString QCalendarMonthValidator::text(const QDate &date, int repeat) const
+QString QCalendarMonthValidator::text(QDate date, QCalendar cal, int repeat) const
{
- if (repeat <= 1) {
- return QString::number(date.month());
- } else if (repeat == 2) {
- return formatNumber(date.month(), 2);
- } else if (repeat == 3) {
- return m_locale.standaloneMonthName(date.month(), QLocale::ShortFormat);
- } else /*if (repeat >= 4)*/ {
- return m_locale.standaloneMonthName(date.month(), QLocale::LongFormat);
- }
+ const auto parts = cal.partsFromDate(date);
+ // Numeric forms:
+ if (repeat <= 1)
+ return QString::number(parts.month);
+ if (repeat == 2)
+ return formatNumber(parts.month, 2);
+ // Text forms:
+ if (repeat == 3)
+ return cal.standaloneMonthName(m_locale, parts.month, parts.year, QLocale::ShortFormat);
+ /* repeat >= 4 */
+ return cal.standaloneMonthName(m_locale, parts.month, parts.year, QLocale::LongFormat);
}
//////////////////////////////////
@@ -334,10 +330,10 @@ class QCalendarYearValidator : public QCalendarDateSectionValidator
public:
QCalendarYearValidator();
virtual Section handleKey(int key) override;
- virtual QDate applyToDate(const QDate &date) const override;
- virtual void setDate(const QDate &date) override;
+ virtual QDate applyToDate(QDate date, QCalendar cal) const override;
+ virtual void setDate(QDate date, QCalendar cal) override;
virtual QString text() const override;
- virtual QString text(const QDate &date, int repeat) const override;
+ virtual QString text(QDate date, QCalendar cal, int repeat) const override;
private:
int pow10(int n);
int m_pos;
@@ -348,6 +344,8 @@ private:
QCalendarYearValidator::QCalendarYearValidator()
: QCalendarDateSectionValidator(), m_pos(0), m_year(2000), m_oldYear(2000)
{
+ // TODO: What to use (for non-Gregorian calendars) as default year?
+ // Maybe 1360 for Jalali, 1420 for Islamic, etc.
}
int QCalendarYearValidator::pow10(int n)
@@ -396,21 +394,20 @@ QCalendarDateSectionValidator::Section QCalendarYearValidator::handleKey(int key
return QCalendarDateSectionValidator::ThisSection;
}
-QDate QCalendarYearValidator::applyToDate(const QDate &date) const
+QDate QCalendarYearValidator::applyToDate(QDate date, QCalendar cal) const
{
- int year = m_year;
- if (year < 1)
- year = 1;
- QDate newDate(year, date.month(), 1);
- int day = date.day();
- if (day > newDate.daysInMonth())
- day = newDate.daysInMonth();
- return QDate(year, date.month(), day);
+ auto parts = cal.partsFromDate(date);
+ if (!parts.isValid())
+ return QDate();
+ // This widget does not support negative years (some calendars may support)
+ parts.year = qMax(1, m_year);
+ parts.day = qMin(parts.day, cal.daysInMonth(parts.year, parts.month));
+ return cal.dateFromParts(parts);
}
-void QCalendarYearValidator::setDate(const QDate &date)
+void QCalendarYearValidator::setDate(QDate date, QCalendar cal)
{
- m_year = m_oldYear = date.year();
+ m_year = m_oldYear = date.year(cal);
m_pos = 0;
}
@@ -419,11 +416,11 @@ QString QCalendarYearValidator::text() const
return highlightString(formatNumber(m_year, 4), m_pos);
}
-QString QCalendarYearValidator::text(const QDate &date, int repeat) const
+QString QCalendarYearValidator::text(QDate date, QCalendar cal, int repeat) const
{
if (repeat < 4)
- return formatNumber(date.year() % 100, 2);
- return QString::number(date.year());
+ return formatNumber(date.year(cal) % 100, 2);
+ return QString::number(date.year(cal));
}
///////////////////////////////////
@@ -445,18 +442,18 @@ public:
QCalendarDateValidator();
~QCalendarDateValidator();
- void handleKeyEvent(QKeyEvent *keyEvent);
- QString currentText() const;
+ void handleKeyEvent(QKeyEvent *keyEvent, QCalendar cal);
+ QString currentText(QCalendar cal) const;
QDate currentDate() const { return m_currentDate; }
void setFormat(const QString &format);
- void setInitialDate(const QDate &date);
+ void setInitialDate(QDate date, QCalendar cal);
void setLocale(const QLocale &locale);
private:
void toNextToken();
void toPreviousToken();
- void applyToDate();
+ void applyToDate(QCalendar cal);
int countRepeat(const QString &str, int index) const;
void clear();
@@ -506,17 +503,17 @@ int QCalendarDateValidator::countRepeat(const QString &str, int index) const
return count;
}
-void QCalendarDateValidator::setInitialDate(const QDate &date)
+void QCalendarDateValidator::setInitialDate(QDate date, QCalendar cal)
{
- m_yearValidator.setDate(date);
- m_monthValidator.setDate(date);
- m_dayValidator.setDate(date);
+ m_yearValidator.setDate(date, cal);
+ m_monthValidator.setDate(date, cal);
+ m_dayValidator.setDate(date, cal);
m_initialDate = date;
m_currentDate = date;
m_lastSectionMove = QCalendarDateSectionValidator::ThisSection;
}
-QString QCalendarDateValidator::currentText() const
+QString QCalendarDateValidator::currentText(QCalendar cal) const
{
QString str;
const int numSeps = m_separators.size();
@@ -528,7 +525,7 @@ QString QCalendarDateValidator::currentText() const
if (i == m_currentToken)
str += token.validator->text();
else
- str += token.validator->text(m_currentDate, token.repeat);
+ str += token.validator->text(m_currentDate, cal, token.repeat);
}
}
return str;
@@ -590,11 +587,11 @@ void QCalendarDateValidator::setFormat(const QString &format)
m_separators += separator;
}
-void QCalendarDateValidator::applyToDate()
+void QCalendarDateValidator::applyToDate(QCalendar cal)
{
- m_currentDate = m_yearValidator.applyToDate(m_currentDate);
- m_currentDate = m_monthValidator.applyToDate(m_currentDate);
- m_currentDate = m_dayValidator.applyToDate(m_currentDate);
+ m_currentDate = m_yearValidator.applyToDate(m_currentDate, cal);
+ m_currentDate = m_monthValidator.applyToDate(m_currentDate, cal);
+ m_currentDate = m_dayValidator.applyToDate(m_currentDate, cal);
}
void QCalendarDateValidator::toNextToken()
@@ -613,7 +610,7 @@ void QCalendarDateValidator::toPreviousToken()
m_currentToken %= m_tokens.size();
}
-void QCalendarDateValidator::handleKeyEvent(QKeyEvent *keyEvent)
+void QCalendarDateValidator::handleKeyEvent(QKeyEvent *keyEvent,QCalendar cal)
{
if (m_currentToken < 0)
return;
@@ -630,7 +627,7 @@ void QCalendarDateValidator::handleKeyEvent(QKeyEvent *keyEvent)
m_lastSectionMove = m_tokens[m_currentToken].validator->handleKey(key);
- applyToDate();
+ applyToDate(cal);
if (m_lastSectionMove == QCalendarDateSectionValidator::NextSection)
toNextToken();
else if (m_lastSectionMove == QCalendarDateSectionValidator::PrevSection)
@@ -644,7 +641,8 @@ class QCalendarTextNavigator: public QObject
Q_OBJECT
public:
QCalendarTextNavigator(QObject *parent = 0)
- : QObject(parent), m_dateText(0), m_dateFrame(0), m_dateValidator(0), m_widget(0), m_editDelay(1500), m_date(QDate::currentDate()) { }
+ : QObject(parent), m_dateText(0), m_dateFrame(0), m_dateValidator(0),
+ m_widget(0), m_editDelay(1500), m_date(QDate::currentDate()) {}
QWidget *widget() const;
void setWidget(QWidget *widget);
@@ -652,13 +650,13 @@ public:
int dateEditAcceptDelay() const;
void setDateEditAcceptDelay(int delay);
- void setDate(const QDate &date);
+ void setDate(QDate date);
bool eventFilter(QObject *o, QEvent *e) override;
void timerEvent(QTimerEvent *e) override;
signals:
- void dateChanged(const QDate &date);
+ void dateChanged(QDate date);
void editingFinished();
private:
@@ -675,6 +673,7 @@ private:
int m_editDelay;
QDate m_date;
+ const QCalendar m_calendar;
};
QWidget *QCalendarTextNavigator::widget() const
@@ -687,7 +686,7 @@ void QCalendarTextNavigator::setWidget(QWidget *widget)
m_widget = widget;
}
-void QCalendarTextNavigator::setDate(const QDate &date)
+void QCalendarTextNavigator::setDate(QDate date)
{
m_date = date;
}
@@ -699,7 +698,7 @@ void QCalendarTextNavigator::updateDateLabel()
m_acceptTimer.start(m_editDelay, this);
- m_dateText->setText(m_dateValidator->currentText());
+ m_dateText->setText(m_dateValidator->currentText(m_calendar));
QSize s = m_dateFrame->sizeHint();
QRect r = m_widget->geometry(); // later, just the table section
@@ -739,7 +738,7 @@ void QCalendarTextNavigator::createDateLabel()
m_dateValidator = new QCalendarDateValidator();
m_dateValidator->setLocale(m_widget->locale());
m_dateValidator->setFormat(m_widget->locale().dateFormat(QLocale::ShortFormat));
- m_dateValidator->setInitialDate(m_date);
+ m_dateValidator->setInitialDate(m_date, m_calendar);
m_dateFrame->setAutoFillBackground(true);
m_dateFrame->setBackgroundRole(QPalette::Window);
@@ -774,7 +773,7 @@ bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e)
#endif
} else if (e->type() == QEvent::KeyPress) {
createDateLabel();
- m_dateValidator->handleKeyEvent(ke);
+ m_dateValidator->handleKeyEvent(ke, m_calendar);
updateDateLabel();
}
ke->accept();
@@ -827,9 +826,9 @@ class StaticDayOfWeekAssociativeArray {
bool contained[7];
T data[7];
- static Q_DECL_CONSTEXPR int day2idx(Qt::DayOfWeek day) Q_DECL_NOTHROW { return int(day) - 1; } // alt: day % 7
+ static Q_DECL_CONSTEXPR int day2idx(Qt::DayOfWeek day) noexcept { return int(day) - 1; } // alt: day % 7
public:
- Q_DECL_CONSTEXPR StaticDayOfWeekAssociativeArray() Q_DECL_NOEXCEPT_EXPR(noexcept(T()))
+ Q_DECL_CONSTEXPR StaticDayOfWeekAssociativeArray() noexcept(noexcept(T()))
#ifdef Q_COMPILER_CONSTEXPR
: contained{}, data{} // arrays require uniform initialization
#else
@@ -837,17 +836,17 @@ public:
#endif
{}
- Q_DECL_CONSTEXPR bool contains(Qt::DayOfWeek day) const Q_DECL_NOTHROW { return contained[day2idx(day)]; }
- Q_DECL_CONSTEXPR const T &value(Qt::DayOfWeek day) const Q_DECL_NOTHROW { return data[day2idx(day)]; }
+ Q_DECL_CONSTEXPR bool contains(Qt::DayOfWeek day) const noexcept { return contained[day2idx(day)]; }
+ Q_DECL_CONSTEXPR const T &value(Qt::DayOfWeek day) const noexcept { return data[day2idx(day)]; }
- Q_DECL_RELAXED_CONSTEXPR T &operator[](Qt::DayOfWeek day) Q_DECL_NOTHROW
+ Q_DECL_RELAXED_CONSTEXPR T &operator[](Qt::DayOfWeek day) noexcept
{
const int idx = day2idx(day);
contained[idx] = true;
return data[idx];
}
- Q_DECL_RELAXED_CONSTEXPR void insert(Qt::DayOfWeek day, T v) Q_DECL_NOTHROW
+ Q_DECL_RELAXED_CONSTEXPR void insert(Qt::DayOfWeek day, T v) noexcept
{
operator[](day).swap(v);
}
@@ -894,12 +893,15 @@ public:
}
void showMonth(int year, int month);
- void setDate(const QDate &d);
+ void setDate(QDate d);
- void setMinimumDate(const QDate &date);
- void setMaximumDate(const QDate &date);
+ void setCalendar(QCalendar c);
+ QCalendar calendar() const;
- void setRange(const QDate &min, const QDate &max);
+ void setMinimumDate(QDate date);
+ void setMaximumDate(QDate date);
+
+ void setRange(QDate min, QDate max);
void setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat format);
@@ -913,7 +915,7 @@ public:
Qt::DayOfWeek dayOfWeekForColumn(int section) const;
int columnForDayOfWeek(Qt::DayOfWeek day) const;
QDate dateForCell(int row, int column) const;
- void cellForDate(const QDate &date, int *row, int *column) const;
+ void cellForDate(QDate date, int *row, int *column) const;
QString dayName(Qt::DayOfWeek day) const;
void setView(QCalendarView *view)
@@ -921,10 +923,16 @@ public:
void internalUpdate();
QDate referenceDate() const;
- int columnForFirstOfMonth(const QDate &date) const;
+ int columnForFirstOfMonth(QDate date) const;
+
+ QString monthName(const QLocale &locale, int month)
+ {
+ return m_calendar.standaloneMonthName(locale, month, m_shownYear, QLocale::LongFormat);
+ }
int m_firstColumn;
int m_firstRow;
+ QCalendar m_calendar;
QDate m_date;
QDate m_minimumDate;
QDate m_maximumDate;
@@ -950,9 +958,9 @@ public:
virtual void keyboardSearch(const QString & search) override { Q_UNUSED(search) }
signals:
- void showDate(const QDate &date);
- void changeDate(const QDate &date, bool changeMonth);
- void clicked(const QDate &date);
+ void showDate(QDate date);
+ void changeDate(QDate date, bool changeMonth);
+ void clicked(QDate date);
void editingFinished();
protected:
QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override;
@@ -983,8 +991,8 @@ QCalendarModel::QCalendarModel(QObject *parent)
m_date(QDate::currentDate()),
m_minimumDate(QDate::fromJulianDay(1)),
m_maximumDate(9999, 12, 31),
- m_shownYear(m_date.year()),
- m_shownMonth(m_date.month()),
+ m_shownYear(m_date.year(m_calendar)),
+ m_shownMonth(m_date.month(m_calendar)),
m_firstDay(QLocale().firstDayOfWeek()),
m_horizontalHeaderFormat(QCalendarWidget::ShortDayNames),
m_weekNumbersShown(true),
@@ -1027,9 +1035,10 @@ will be rendered in 2nd or 3rd row, showing more dates from previous month.
*/
QDate QCalendarModel::referenceDate() const
{
+ // TODO: Check this
int refDay = 1;
while (refDay <= 31) {
- QDate refDate(m_shownYear, m_shownMonth, refDay);
+ QDate refDate(m_shownYear, m_shownMonth, refDay, m_calendar);
if (refDate.isValid())
return refDate;
refDay += 1;
@@ -1037,9 +1046,10 @@ QDate QCalendarModel::referenceDate() const
return QDate();
}
-int QCalendarModel::columnForFirstOfMonth(const QDate &date) const
+int QCalendarModel::columnForFirstOfMonth(QDate date) const
{
- return (columnForDayOfWeek(static_cast<Qt::DayOfWeek>(date.dayOfWeek())) - (date.day() % 7) + 8) % 7;
+ return (columnForDayOfWeek(static_cast<Qt::DayOfWeek>(m_calendar.dayOfWeek(date)))
+ - (date.day(m_calendar) % 7) + 8) % 7;
}
QDate QCalendarModel::dateForCell(int row, int column) const
@@ -1055,11 +1065,12 @@ QDate QCalendarModel::dateForCell(int row, int column) const
if (columnForFirstOfShownMonth - m_firstColumn < MinimumDayOffset)
row -= 1;
- const int requestedDay = 7 * (row - m_firstRow) + column - columnForFirstOfShownMonth - refDate.day() + 1;
+ const int requestedDay =
+ 7 * (row - m_firstRow) + column - columnForFirstOfShownMonth - refDate.day(m_calendar) + 1;
return refDate.addDays(requestedDay);
}
-void QCalendarModel::cellForDate(const QDate &date, int *row, int *column) const
+void QCalendarModel::cellForDate(QDate date, int *row, int *column) const
{
if (!row && !column)
return;
@@ -1074,7 +1085,8 @@ void QCalendarModel::cellForDate(const QDate &date, int *row, int *column) const
return;
const int columnForFirstOfShownMonth = columnForFirstOfMonth(refDate);
- const int requestedPosition = refDate.daysTo(date) - m_firstColumn + columnForFirstOfShownMonth + refDate.day() - 1;
+ const int requestedPosition = (refDate.daysTo(date) - m_firstColumn +
+ columnForFirstOfShownMonth + refDate.day(m_calendar) - 1);
int c = requestedPosition % 7;
int r = requestedPosition / 7;
@@ -1147,7 +1159,7 @@ QTextCharFormat QCalendarModel::formatForCell(int row, int col) const
format.merge(m_dateFormats.value(date));
if(date < m_minimumDate || date > m_maximumDate)
format.setBackground(pal.brush(cg, QPalette::Window));
- if (m_shownMonth != date.month())
+ if (m_shownMonth != date.month(m_calendar))
format.setForeground(pal.brush(QPalette::Disabled, QPalette::Text));
}
return format;
@@ -1173,7 +1185,7 @@ QVariant QCalendarModel::data(const QModelIndex &index, int role) const
return dayName(dayOfWeekForColumn(column));
QDate date = dateForCell(row, column);
if (date.isValid())
- return date.day();
+ return date.day(m_calendar);
return QString();
}
@@ -1201,7 +1213,7 @@ Qt::ItemFlags QCalendarModel::flags(const QModelIndex &index) const
return QAbstractTableModel::flags(index);
}
-void QCalendarModel::setDate(const QDate &d)
+void QCalendarModel::setDate(QDate d)
{
m_date = d;
if (m_date < m_minimumDate)
@@ -1210,6 +1222,20 @@ void QCalendarModel::setDate(const QDate &d)
m_date = m_maximumDate;
}
+void QCalendarModel::setCalendar(QCalendar c)
+{
+ m_calendar = c;
+ m_shownYear = m_date.year(c);
+ m_shownMonth = m_date.month(c);
+ internalUpdate();
+ m_view->internalUpdate();
+}
+
+QCalendar QCalendarModel::calendar() const
+{
+ return m_calendar;
+}
+
void QCalendarModel::showMonth(int year, int month)
{
if (m_shownYear == year && m_shownMonth == month)
@@ -1221,7 +1247,7 @@ void QCalendarModel::showMonth(int year, int month)
internalUpdate();
}
-void QCalendarModel::setMinimumDate(const QDate &d)
+void QCalendarModel::setMinimumDate(QDate d)
{
if (!d.isValid() || d == m_minimumDate)
return;
@@ -1234,7 +1260,7 @@ void QCalendarModel::setMinimumDate(const QDate &d)
internalUpdate();
}
-void QCalendarModel::setMaximumDate(const QDate &d)
+void QCalendarModel::setMaximumDate(QDate d)
{
if (!d.isValid() || d == m_maximumDate)
return;
@@ -1247,7 +1273,7 @@ void QCalendarModel::setMaximumDate(const QDate &d)
internalUpdate();
}
-void QCalendarModel::setRange(const QDate &min, const QDate &max)
+void QCalendarModel::setRange(QDate min, QDate max)
{
m_minimumDate = min;
m_maximumDate = max;
@@ -1340,6 +1366,8 @@ QModelIndex QCalendarView::moveCursor(CursorAction cursorAction, Qt::KeyboardMod
if (!calendarModel)
return QTableView::moveCursor(cursorAction, modifiers);
+ QCalendar cal = calendarModel->calendar();
+
if (readOnly)
return currentIndex();
@@ -1358,17 +1386,27 @@ QModelIndex QCalendarView::moveCursor(CursorAction cursorAction, Qt::KeyboardMod
case QAbstractItemView::MoveRight:
currentDate = currentDate.addDays(isRightToLeft() ? -1 : 1);
break;
- case QAbstractItemView::MoveHome:
- currentDate = QDate(currentDate.year(), currentDate.month(), 1);
+ case QAbstractItemView::MoveHome: {
+ auto parts = cal.partsFromDate(currentDate);
+ if (parts.isValid()) {
+ parts.day = 1;
+ currentDate = cal.dateFromParts(parts);
+ }
+ }
break;
- case QAbstractItemView::MoveEnd:
- currentDate = QDate(currentDate.year(), currentDate.month(), currentDate.daysInMonth());
+ case QAbstractItemView::MoveEnd: {
+ auto parts = cal.partsFromDate(currentDate);
+ if (parts.isValid()) {
+ parts.day = cal.daysInMonth(parts.year, parts.month);
+ currentDate = cal.dateFromParts(parts);
+ }
+ }
break;
case QAbstractItemView::MovePageUp:
- currentDate = currentDate.addMonths(-1);
+ currentDate = currentDate.addMonths(-1, cal);
break;
case QAbstractItemView::MovePageDown:
- currentDate = currentDate.addMonths(1);
+ currentDate = currentDate.addMonths(1, cal);
break;
case QAbstractItemView::MoveNext:
case QAbstractItemView::MovePrevious:
@@ -1384,14 +1422,14 @@ void QCalendarView::keyPressEvent(QKeyEvent *event)
{
#ifdef QT_KEYPAD_NAVIGATION
if (event->key() == Qt::Key_Select) {
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus()) {
setEditFocus(true);
return;
}
}
} else if (event->key() == Qt::Key_Back) {
- if (QApplication::keypadNavigationEnabled() && hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && hasEditFocus()) {
if (qobject_cast<QCalendarModel *>(model())) {
emit changeDate(origDate, true); //changes selection back to origDate, but doesn't activate
setEditFocus(false);
@@ -1418,11 +1456,12 @@ void QCalendarView::keyPressEvent(QKeyEvent *event)
#if QT_CONFIG(wheelevent)
void QCalendarView::wheelEvent(QWheelEvent *event)
{
- const int numDegrees = event->delta() / 8;
+ const int numDegrees = event->angleDelta().y() / 8;
const int numSteps = numDegrees / 15;
const QModelIndex index = currentIndex();
- QDate currentDate = static_cast<QCalendarModel*>(model())->dateForCell(index.row(), index.column());
- currentDate = currentDate.addMonths(-numSteps);
+ QCalendarModel *calendarModel = static_cast<QCalendarModel*>(model());
+ QDate currentDate = calendarModel->dateForCell(index.row(), index.column());
+ currentDate = currentDate.addMonths(-numSteps, calendarModel->calendar());
emit showDate(currentDate);
}
#endif
@@ -1565,7 +1604,7 @@ public:
{ }
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
- void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
+ void paintCell(QPainter *painter, const QRect &rect, QDate date) const;
private:
QCalendarWidgetPrivate *calendarWidgetPrivate;
@@ -1584,7 +1623,6 @@ protected:
{
Q_UNUSED(e)
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
QStyleOptionToolButton opt;
initStyleOption(&opt);
@@ -1597,7 +1635,7 @@ protected:
toolPalette.setColor(QPalette::ButtonText, toolPalette.color(QPalette::HighlightedText));
setPalette(toolPalette);
}
-#endif
+
QToolButton::paintEvent(e);
}
};
@@ -1627,11 +1665,11 @@ public:
void showMonth(int year, int month);
void update();
- void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
+ void paintCell(QPainter *painter, const QRect &rect, QDate date) const;
- void _q_slotShowDate(const QDate &date);
- void _q_slotChangeDate(const QDate &date);
- void _q_slotChangeDate(const QDate &date, bool changeMonth);
+ void _q_slotShowDate(QDate date);
+ void _q_slotChangeDate(QDate date);
+ void _q_slotChangeDate(QDate date, bool changeMonth);
void _q_editingFinished();
void _q_monthChanged(QAction*);
void _q_prevMonthClicked();
@@ -1644,7 +1682,7 @@ public:
void updateMonthMenu();
void updateMonthMenuNames();
void updateNavigationBar();
- void updateCurrentPage(const QDate &newDate);
+ void updateCurrentPage(QDate newDate);
inline QDate getCurrentDate();
void setNavigatorEnabled(bool enable);
@@ -1683,7 +1721,7 @@ void QCalendarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt
}
}
-void QCalendarDelegate::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
+void QCalendarDelegate::paintCell(QPainter *painter, const QRect &rect, QDate date) const
{
storedOption.rect = rect;
int row = -1;
@@ -1755,8 +1793,8 @@ void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
monthButton->setAutoRaise(true);
monthButton->setPopupMode(QToolButton::InstantPopup);
monthMenu = new QMenu(monthButton);
- for (int i = 1; i <= 12; i++) {
- QString monthName(q->locale().standaloneMonthName(i, QLocale::LongFormat));
+ for (int i = 1, e = m_model->m_calendar.maximumMonthsInYear(); i <= e; i++) {
+ QString monthName(m_model->monthName(q->locale(), i));
QAction *act = monthMenu->addAction(monthName);
act->setData(i);
monthToAction[i] = act;
@@ -1772,8 +1810,8 @@ void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
monthButton->setFont(font);
yearButton->setFont(font);
yearEdit->setFrame(false);
- yearEdit->setMinimum(m_model->m_minimumDate.year());
- yearEdit->setMaximum(m_model->m_maximumDate.year());
+ yearEdit->setMinimum(m_model->m_minimumDate.year(m_model->m_calendar));
+ yearEdit->setMaximum(m_model->m_maximumDate.year(m_model->m_calendar));
yearEdit->hide();
spaceHolder = new QSpacerItem(0,0);
@@ -1803,7 +1841,7 @@ void QCalendarWidgetPrivate::createNavigationBar(QWidget *widget)
yearEdit->setObjectName(QLatin1String("qt_calendar_yearedit"));
updateMonthMenu();
- showMonth(m_model->m_date.year(), m_model->m_date.month());
+ showMonth(m_model->m_date.year(m_model->m_calendar), m_model->m_date.month(m_model->m_calendar));
}
void QCalendarWidgetPrivate::updateButtonIcons()
@@ -1815,22 +1853,24 @@ void QCalendarWidgetPrivate::updateButtonIcons()
void QCalendarWidgetPrivate::updateMonthMenu()
{
- int beg = 1, end = 12;
+ int maxMonths = m_model->m_calendar.monthsInYear(m_model->m_shownYear);
+ int beg = 1, end = maxMonths;
bool prevEnabled = true;
bool nextEnabled = true;
- if (m_model->m_shownYear == m_model->m_minimumDate.year()) {
- beg = m_model->m_minimumDate.month();
- if (m_model->m_shownMonth == m_model->m_minimumDate.month())
+ QCalendar cal = m_model->calendar();
+ if (m_model->m_shownYear == m_model->m_minimumDate.year(cal)) {
+ beg = m_model->m_minimumDate.month(cal);
+ if (m_model->m_shownMonth == m_model->m_minimumDate.month(cal))
prevEnabled = false;
}
- if (m_model->m_shownYear == m_model->m_maximumDate.year()) {
- end = m_model->m_maximumDate.month();
- if (m_model->m_shownMonth == m_model->m_maximumDate.month())
+ if (m_model->m_shownYear == m_model->m_maximumDate.year(cal)) {
+ end = m_model->m_maximumDate.month(cal);
+ if (m_model->m_shownMonth == m_model->m_maximumDate.month(cal))
nextEnabled = false;
}
prevMonth->setEnabled(prevEnabled);
nextMonth->setEnabled(nextEnabled);
- for (int i = 1; i <= 12; i++) {
+ for (int i = 1; i <= maxMonths; i++) {
bool monthEnabled = true;
if (i < beg || i > end)
monthEnabled = false;
@@ -1843,14 +1883,15 @@ void QCalendarWidgetPrivate::updateMonthMenuNames()
Q_Q(QCalendarWidget);
for (int i = 1; i <= 12; i++) {
- QString monthName(q->locale().standaloneMonthName(i, QLocale::LongFormat));
+ QString monthName(m_model->monthName(q->locale(), i));
monthToAction[i]->setText(monthName);
}
}
-void QCalendarWidgetPrivate::updateCurrentPage(const QDate &date)
+void QCalendarWidgetPrivate::updateCurrentPage(QDate date)
{
Q_Q(QCalendarWidget);
+ QCalendar cal = m_model->calendar();
QDate newDate = date;
QDate minDate = q->minimumDate();
@@ -1859,7 +1900,7 @@ void QCalendarWidgetPrivate::updateCurrentPage(const QDate &date)
newDate = minDate;
if (maxDate.isValid()&& maxDate.daysTo(newDate) > 0)
newDate = maxDate;
- showMonth(newDate.year(), newDate.month());
+ showMonth(newDate.year(cal), newDate.month(cal));
int row = -1, col = -1;
m_model->cellForDate(newDate, &row, &col);
if (row != -1 && col != -1)
@@ -1873,7 +1914,7 @@ void QCalendarWidgetPrivate::_q_monthChanged(QAction *act)
{
monthButton->setText(act->text());
QDate currentDate = getCurrentDate();
- QDate newDate = currentDate.addMonths(act->data().toInt()-currentDate.month());
+ QDate newDate = currentDate.addMonths(act->data().toInt() - currentDate.month(m_model->m_calendar), m_model->m_calendar);
updateCurrentPage(newDate);
}
@@ -1885,27 +1926,28 @@ QDate QCalendarWidgetPrivate::getCurrentDate()
void QCalendarWidgetPrivate::_q_prevMonthClicked()
{
- QDate currentDate = getCurrentDate().addMonths(-1);
+ QDate currentDate = getCurrentDate().addMonths(-1, m_model->m_calendar);
updateCurrentPage(currentDate);
}
void QCalendarWidgetPrivate::_q_nextMonthClicked()
{
- QDate currentDate = getCurrentDate().addMonths(1);
+ QDate currentDate = getCurrentDate().addMonths(1, m_model->m_calendar);
updateCurrentPage(currentDate);
}
void QCalendarWidgetPrivate::_q_yearEditingFinished()
{
Q_Q(QCalendarWidget);
- yearButton->setText(yearEdit->text());
+ yearButton->setText(q->locale().toString(yearEdit->value()));
yearEdit->hide();
q->setFocusPolicy(oldFocusPolicy);
qApp->removeEventFilter(q);
spaceHolder->changeSize(0, 0);
yearButton->show();
QDate currentDate = getCurrentDate();
- currentDate = currentDate.addYears(yearEdit->text().toInt() - currentDate.year());
+ int newYear = q->locale().toInt(yearEdit->text());
+ currentDate = currentDate.addYears(newYear - currentDate.year(m_model->m_calendar), m_model->m_calendar);
updateCurrentPage(currentDate);
}
@@ -1944,7 +1986,7 @@ void QCalendarWidgetPrivate::updateNavigationBar()
{
Q_Q(QCalendarWidget);
- QString monthName = q->locale().standaloneMonthName(m_model->m_shownMonth, QLocale::LongFormat);
+ QString monthName = m_model->monthName(q->locale(), m_model->m_shownMonth);
monthButton->setText(monthName);
yearEdit->setValue(m_model->m_shownYear);
@@ -1964,29 +2006,29 @@ void QCalendarWidgetPrivate::update()
}
}
-void QCalendarWidgetPrivate::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const
+void QCalendarWidgetPrivate::paintCell(QPainter *painter, const QRect &rect, QDate date) const
{
Q_Q(const QCalendarWidget);
q->paintCell(painter, rect, date);
}
-void QCalendarWidgetPrivate::_q_slotShowDate(const QDate &date)
+void QCalendarWidgetPrivate::_q_slotShowDate(QDate date)
{
updateCurrentPage(date);
}
-void QCalendarWidgetPrivate::_q_slotChangeDate(const QDate &date)
+void QCalendarWidgetPrivate::_q_slotChangeDate(QDate date)
{
_q_slotChangeDate(date, true);
}
-void QCalendarWidgetPrivate::_q_slotChangeDate(const QDate &date, bool changeMonth)
+void QCalendarWidgetPrivate::_q_slotChangeDate(QDate date, bool changeMonth)
{
QDate oldDate = m_model->m_date;
m_model->setDate(date);
QDate newDate = m_model->m_date;
if (changeMonth)
- showMonth(newDate.year(), newDate.month());
+ showMonth(newDate.year(m_model->m_calendar), newDate.month(m_model->m_calendar));
if (oldDate != newDate) {
update();
Q_Q(QCalendarWidget);
@@ -2242,7 +2284,7 @@ QSize QCalendarWidget::minimumSizeHint() const
QFontMetrics fm = d->monthButton->fontMetrics();
int monthW = 0;
for (int i = 1; i < 12; i++) {
- QString monthName = locale().standaloneMonthName(i, QLocale::LongFormat);
+ QString monthName = d->m_model->monthName(locale(), i);
monthW = qMax(monthW, fm.boundingRect(monthName).width());
}
const int buttonDecoMargin = d->monthButton->sizeHint().width() - fm.boundingRect(d->monthButton->text()).width();
@@ -2302,7 +2344,8 @@ void QCalendarWidget::setSelectedDate(const QDate &date)
d->m_model->setDate(date);
d->update();
QDate newDate = d->m_model->m_date;
- d->showMonth(newDate.year(), newDate.month());
+ QCalendar cal = d->m_model->m_calendar;
+ d->showMonth(newDate.year(cal), newDate.month(cal));
emit selectionChanged();
}
@@ -2348,14 +2391,15 @@ void QCalendarWidget::setCurrentPage(int year, int month)
{
Q_D(QCalendarWidget);
QDate currentDate = d->getCurrentDate();
- int day = currentDate.day();
- int daysInMonths = QDate(year, month, 1).daysInMonth();
+ QCalendar cal = d->m_model->m_calendar;
+ int day = currentDate.day(cal);
+ int daysInMonths = cal.daysInMonth(year, month);
if (day > daysInMonths)
day = daysInMonths;
d->showMonth(year, month);
- QDate newDate(year, month, day);
+ QDate newDate(year, month, day, d->m_model->m_calendar);
int row = -1, col = -1;
d->m_model->cellForDate(newDate, &row, &col);
if (row != -1 && col != -1) {
@@ -2373,9 +2417,10 @@ void QCalendarWidget::setCurrentPage(int year, int month)
void QCalendarWidget::showNextMonth()
{
+ Q_D(const QCalendarWidget);
int year = yearShown();
int month = monthShown();
- if (month == 12) {
+ if (month == d->m_model->m_calendar.maximumMonthsInYear()) {
++year;
month = 1;
} else {
@@ -2393,11 +2438,13 @@ void QCalendarWidget::showNextMonth()
void QCalendarWidget::showPreviousMonth()
{
+ Q_D(const QCalendarWidget);
+
int year = yearShown();
int month = monthShown();
if (month == 1) {
--year;
- month = 12;
+ month = d->m_model->m_calendar.maximumMonthsInYear();
} else {
--month;
}
@@ -2443,8 +2490,10 @@ void QCalendarWidget::showPreviousYear()
*/
void QCalendarWidget::showSelectedDate()
{
+ Q_D(const QCalendarWidget);
+
QDate currentDate = selectedDate();
- setCurrentPage(currentDate.year(), currentDate.month());
+ setCurrentPage(currentDate.year(d->m_model->m_calendar), currentDate.month(d->m_model->m_calendar));
}
/*!
@@ -2454,8 +2503,10 @@ void QCalendarWidget::showSelectedDate()
*/
void QCalendarWidget::showToday()
{
+ Q_D(const QCalendarWidget);
+
QDate currentDate = QDate::currentDate();
- setCurrentPage(currentDate.year(), currentDate.month());
+ setCurrentPage(currentDate.year(d->m_model->m_calendar), currentDate.month(d->m_model->m_calendar));
}
/*!
@@ -2498,12 +2549,12 @@ void QCalendarWidget::setMinimumDate(const QDate &date)
QDate oldDate = d->m_model->m_date;
d->m_model->setMinimumDate(date);
- d->yearEdit->setMinimum(d->m_model->m_minimumDate.year());
+ d->yearEdit->setMinimum(d->m_model->m_minimumDate.year(d->m_model->m_calendar));
d->updateMonthMenu();
QDate newDate = d->m_model->m_date;
if (oldDate != newDate) {
d->update();
- d->showMonth(newDate.year(), newDate.month());
+ d->showMonth(newDate.year(d->m_model->m_calendar), newDate.month(d->m_model->m_calendar));
d->m_navigator->setDate(newDate);
emit selectionChanged();
}
@@ -2549,12 +2600,12 @@ void QCalendarWidget::setMaximumDate(const QDate &date)
QDate oldDate = d->m_model->m_date;
d->m_model->setMaximumDate(date);
- d->yearEdit->setMaximum(d->m_model->m_maximumDate.year());
+ d->yearEdit->setMaximum(d->m_model->m_maximumDate.year(d->m_model->m_calendar));
d->updateMonthMenu();
QDate newDate = d->m_model->m_date;
if (oldDate != newDate) {
d->update();
- d->showMonth(newDate.year(), newDate.month());
+ d->showMonth(newDate.year(d->m_model->m_calendar), newDate.month(d->m_model->m_calendar));
d->m_navigator->setDate(newDate);
emit selectionChanged();
}
@@ -2589,13 +2640,13 @@ void QCalendarWidget::setDateRange(const QDate &min, const QDate &max)
QDate oldDate = d->m_model->m_date;
d->m_model->setRange(min, max);
- d->yearEdit->setMinimum(d->m_model->m_minimumDate.year());
- d->yearEdit->setMaximum(d->m_model->m_maximumDate.year());
+ d->yearEdit->setMinimum(d->m_model->m_minimumDate.year(d->m_model->m_calendar));
+ d->yearEdit->setMaximum(d->m_model->m_maximumDate.year(d->m_model->m_calendar));
d->updateMonthMenu();
QDate newDate = d->m_model->m_date;
if (oldDate != newDate) {
d->update();
- d->showMonth(newDate.year(), newDate.month());
+ d->showMonth(newDate.year(d->m_model->m_calendar), newDate.month(d->m_model->m_calendar));
d->m_navigator->setDate(newDate);
emit selectionChanged();
}
@@ -2702,6 +2753,22 @@ bool QCalendarWidget::isGridVisible() const
return d->m_view->showGrid();
}
+QCalendar QCalendarWidget::calendar() const
+{
+ Q_D(const QCalendarWidget);
+ return d->m_model->m_calendar;
+}
+
+void QCalendarWidget::setCalendar(QCalendar c)
+{
+ Q_D(QCalendarWidget);
+ d->m_model->setCalendar(c);
+ d->updateMonthMenuNames();
+ d->yearEdit->setMinimum(d->m_model->m_minimumDate.year(d->m_model->m_calendar));
+ d->yearEdit->setMaximum(d->m_model->m_maximumDate.year(d->m_model->m_calendar));
+ d->updateNavigationBar();
+}
+
void QCalendarWidget::setGridVisible(bool show)
{
Q_D(QCalendarWidget);
@@ -3042,6 +3109,9 @@ bool QCalendarWidget::event(QEvent *event)
d->updateMonthMenuNames();
d->updateNavigationBar();
d->m_view->updateGeometry();
+ // TODO: fix this known bug of calendaring API:
+ // Changing locale before calendar works, but reverse order causes
+ // invalid month names (in C Locale apparently).
break;
case QEvent::FontChange:
case QEvent::ApplicationFontChange:
diff --git a/src/widgets/widgets/qcalendarwidget.h b/src/widgets/widgets/qcalendarwidget.h
index 44ba340289..08825a0ff3 100644
--- a/src/widgets/widgets/qcalendarwidget.h
+++ b/src/widgets/widgets/qcalendarwidget.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -112,6 +112,9 @@ public:
bool isNavigationBarVisible() const;
bool isGridVisible() const;
+ QCalendar calendar() const;
+ void setCalendar(QCalendar calendar);
+
SelectionMode selectionMode() const;
void setSelectionMode(SelectionMode mode);
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index 483cfd8c55..9a0e969e1c 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -64,7 +64,9 @@
#include <qheaderview.h>
#include <qmath.h>
#include <qmetaobject.h>
+#if QT_CONFIG(proxymodel)
#include <qabstractproxymodel.h>
+#endif
#include <qstylehints.h>
#include <private/qguiapplication_p.h>
#include <private/qhighdpiscaling_p.h>
@@ -200,6 +202,7 @@ QStyleOptionMenuItem QComboMenuDelegate::getStyleOption(const QStyleOptionViewIt
void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
{
Q_Q(QComboBox);
+#if QT_CONFIG(proxymodel)
if (index.isValid() && q->completer()) {
QAbstractProxyModel *proxy = qobject_cast<QAbstractProxyModel *>(q->completer()->completionModel());
if (proxy) {
@@ -221,9 +224,10 @@ void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
emitActivated(currentIndex);
}
}
+#endif
# ifdef QT_KEYPAD_NAVIGATION
- if ( QApplication::keypadNavigationEnabled()
+ if ( QApplicationPrivate::keypadNavigationEnabled()
&& q->isEditable()
&& q->completer()
&& q->completer()->completionMode() == QCompleter::UnfilteredPopupCompletion ) {
@@ -443,13 +447,6 @@ void QComboBoxPrivateContainer::paintEvent(QPaintEvent *e)
void QComboBoxPrivateContainer::leaveEvent(QEvent *)
{
-// On Mac using the Mac style we want to clear the selection
-// when the mouse moves outside the popup.
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- QStyleOptionComboBox opt = comboStyleOption();
- if (combo->style()->styleHint(QStyle::SH_ComboBox_Popup, &opt, combo))
- view->clearSelection();
-#endif
}
QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent)
@@ -691,7 +688,7 @@ void QComboBoxPrivateContainer::changeEvent(QEvent *e)
setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));
}
- QWidget::changeEvent(e);
+ QFrame::changeEvent(e);
}
@@ -865,6 +862,16 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
when the choice is not changed. If you need to know when the
choice actually changes, use signal currentIndexChanged().
+ \obsolete Use QComboBox::textActivated() instead
+*/
+/*!
+ \fn void QComboBox::textActivated(const QString &text)
+ \since 5.14
+
+ This signal is sent when the user chooses an item in the combobox.
+ The item's \a text is passed. Note that this signal is sent even
+ when the choice is not changed. If you need to know when the
+ choice actually changes, use signal currentIndexChanged().
*/
/*!
@@ -879,6 +886,15 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
This signal is sent when an item in the combobox popup list is
highlighted by the user. The item's \a text is passed.
+
+ \obsolete Use textHighlighted() instead
+*/
+/*!
+ \fn void QComboBox::textHighlighted(const QString &text)
+ \since 5.14
+
+ This signal is sent when an item in the combobox popup list is
+ highlighted by the user. The item's \a text is passed.
*/
/*!
@@ -891,7 +907,6 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
currentIndex was reset.
*/
-#if QT_DEPRECATED_SINCE(5, 13)
/*!
\fn void QComboBox::currentIndexChanged(const QString &text)
\since 4.1
@@ -900,7 +915,6 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
changes either through user interaction or programmatically. The
item's \a text is passed.
*/
-#endif
/*!
\fn void QComboBox::currentTextChanged(const QString &text)
@@ -1355,7 +1369,13 @@ void QComboBoxPrivate::emitActivated(const QModelIndex &index)
return;
QString text(itemText(index));
emit q->activated(index.row());
+ emit q->textActivated(text);
+#if QT_DEPRECATED_SINCE(5, 15)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
emit q->activated(text);
+QT_WARNING_POP
+#endif
}
void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
@@ -1365,7 +1385,13 @@ void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
return;
QString text(itemText(index));
emit q->highlighted(index.row());
+ emit q->textHighlighted(text);
+#if QT_DEPRECATED_SINCE(5, 15)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
emit q->highlighted(text);
+QT_WARNING_POP
+#endif
}
void QComboBoxPrivate::_q_emitCurrentIndexChanged(const QModelIndex &index)
@@ -1522,7 +1548,7 @@ void QComboBox::setAutoCompletion(bool enable)
Q_D(QComboBox);
#ifdef QT_KEYPAD_NAVIGATION
- if (Q_UNLIKELY(QApplication::keypadNavigationEnabled() && !enable && isEditable()))
+ if (Q_UNLIKELY(QApplicationPrivate::keypadNavigationEnabled() && !enable && isEditable()))
qWarning("QComboBox::setAutoCompletion: auto completion is mandatory when combo box editable");
#endif
@@ -1864,13 +1890,12 @@ void QComboBox::setLineEdit(QLineEdit *edit)
d->updateFocusPolicy();
d->lineEdit->setFocusProxy(this);
d->lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
+#if QT_DEPRECATED_SINCE(5, 13)
#if QT_CONFIG(completer)
setAutoCompletion(d->autoCompletion);
-#endif
#ifdef QT_KEYPAD_NAVIGATION
-#if QT_CONFIG(completer)
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// Editable combo boxes will have a completer that is set to UnfilteredPopupCompletion.
// This means that when the user enters edit mode they are immediately presented with a
// list of possible completions.
@@ -1882,6 +1907,7 @@ void QComboBox::setLineEdit(QLineEdit *edit)
}
#endif
#endif
+#endif
setAttribute(Qt::WA_InputMethodEnabled);
d->updateLayoutDirection();
@@ -2513,21 +2539,6 @@ QSize QComboBox::sizeHint() const
}
#ifdef Q_OS_MAC
-
-namespace {
-struct IndexSetter {
- int index;
- QComboBox *cb;
-
- void operator()(void)
- {
- cb->setCurrentIndex(index);
- emit cb->activated(index);
- emit cb->activated(cb->itemText(index));
- }
-};
-}
-
void QComboBoxPrivate::cleanupNativePopup()
{
if (!m_platformMenu)
@@ -2601,7 +2612,7 @@ bool QComboBoxPrivate::showNativePopup()
// We need to fake one here to un-press the button.
QMouseEvent mouseReleased(QEvent::MouseButtonRelease, q->pos(), Qt::LeftButton,
Qt::MouseButtons(Qt::LeftButton), Qt::KeyboardModifiers());
- qApp->sendEvent(q, &mouseReleased);
+ QCoreApplication::sendEvent(q, &mouseReleased);
#endif
return true;
@@ -2641,7 +2652,7 @@ void QComboBox::showPopup()
#ifdef QT_KEYPAD_NAVIGATION
#if QT_CONFIG(completer)
- if (QApplication::keypadNavigationEnabled() && d->completer) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && d->completer) {
// editable combo box is line edit plus completer
setEditFocus(true);
d->completer->complete(); // show popup
@@ -2702,15 +2713,14 @@ void QComboBox::showPopup()
int heightMargin = container->topMargin() + container->bottomMargin();
// add the frame of the container
- int marginTop, marginBottom;
- container->getContentsMargins(0, &marginTop, 0, &marginBottom);
- heightMargin += marginTop + marginBottom;
+ const QMargins cm = container->contentsMargins();
+ heightMargin += cm.top() + cm.bottom();
//add the frame of the view
- view()->getContentsMargins(0, &marginTop, 0, &marginBottom);
- marginTop += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top;
- marginBottom += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom;
- heightMargin += marginTop + marginBottom;
+ const QMargins vm = view()->contentsMargins();
+ heightMargin += vm.top() + vm.bottom();
+ heightMargin += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top;
+ heightMargin += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom;
listRect.setHeight(listRect.height() + heightMargin);
}
@@ -2821,19 +2831,15 @@ void QComboBox::showPopup()
bool startTimer = !container->isVisible();
container->raise();
container->create();
- QWindow *containerWindow = container->window()->windowHandle();
- if (containerWindow) {
- QWindow *win = window()->windowHandle();
- if (win) {
- QScreen *currentScreen = win->screen();
- if (currentScreen && !currentScreen->virtualSiblings().contains(containerWindow->screen())) {
- containerWindow->setScreen(currentScreen);
-
- // This seems to workaround an issue in xcb+multi GPU+multiscreen
- // environment where the window might not always show up when screen
- // is changed.
- container->hide();
- }
+ if (QWindow *containerWindow = qt_widget_private(container)->windowHandle(QWidgetPrivate::WindowHandleMode::TopLevel)) {
+ QScreen *currentScreen = d->associatedScreen();
+ if (currentScreen && !currentScreen->virtualSiblings().contains(containerWindow->screen())) {
+ containerWindow->setScreen(currentScreen);
+
+ // This seems to workaround an issue in xcb+multi GPU+multiscreen
+ // environment where the window might not always show up when screen
+ // is changed.
+ container->hide();
}
}
container->show();
@@ -2851,7 +2857,7 @@ void QComboBox::showPopup()
container->update();
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
view()->setEditFocus(true);
#endif
if (startTimer) {
@@ -2902,7 +2908,7 @@ void QComboBox::hidePopup()
bool didFade = false;
if (needFade) {
#if defined(Q_OS_MAC)
- QPlatformNativeInterface *platformNativeInterface = qApp->platformNativeInterface();
+ QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface();
int at = platformNativeInterface->metaObject()->indexOfMethod("fadeWindow()");
if (at != -1) {
QMetaMethod windowFade = platformNativeInterface->metaObject()->method(at);
@@ -2923,7 +2929,7 @@ void QComboBox::hidePopup()
d->container->hide();
}
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && isEditable() && hasFocus())
+ if (QApplicationPrivate::keypadNavigationEnabled() && isEditable() && hasFocus())
setEditFocus(true);
#endif
d->_q_resetButton();
@@ -3182,7 +3188,7 @@ void QComboBoxPrivate::showPopupFromMouseEvent(QMouseEvent *e)
}
} else {
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && sc == QStyle::SC_ComboBoxEditField && lineEdit) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && sc == QStyle::SC_ComboBoxEditField && lineEdit) {
lineEdit->event(e); //so lineedit can move cursor, etc
return;
}
@@ -3231,7 +3237,7 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
Q_FALLTHROUGH();
case Qt::Key_PageUp:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
e->ignore();
else
#endif
@@ -3246,7 +3252,7 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
Q_FALLTHROUGH();
case Qt::Key_PageDown:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
e->ignore();
else
#endif
@@ -3280,7 +3286,7 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
break;
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& (!hasEditFocus() || !d->lineEdit)) {
showPopup();
return;
@@ -3288,11 +3294,11 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Left:
case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())
e->ignore();
break;
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus() || !d->lineEdit)
e->ignore();
} else {
@@ -3370,12 +3376,13 @@ void QComboBox::wheelEvent(QWheelEvent *e)
!d->viewContainer()->isVisible()) {
const int rowCount = count();
int newIndex = currentIndex();
+ int delta = e->angleDelta().y();
- if (e->delta() > 0) {
+ if (delta > 0) {
newIndex--;
while ((newIndex >= 0) && !(d->model->flags(d->model->index(newIndex,d->modelColumn,d->root)) & Qt::ItemIsEnabled))
newIndex--;
- } else if (e->delta() < 0) {
+ } else if (delta < 0) {
newIndex++;
while (newIndex < rowCount && !(d->model->index(newIndex, d->modelColumn, d->root).flags() & Qt::ItemIsEnabled))
newIndex++;
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index b2fe921bd8..286772c091 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -223,12 +223,18 @@ public Q_SLOTS:
Q_SIGNALS:
void editTextChanged(const QString &);
void activated(int index);
- void activated(const QString &);
+ void textActivated(const QString &);
void highlighted(int index);
- void highlighted(const QString &);
+ void textHighlighted(const QString &);
void currentIndexChanged(int index);
void currentIndexChanged(const QString &);
void currentTextChanged(const QString &);
+#if QT_DEPRECATED_SINCE(5, 15)
+ QT_DEPRECATED_VERSION_X(5, 15, "Use textActivated() instead")
+ void activated(const QString &);
+ QT_DEPRECATED_VERSION_X(5, 15, "Use textHighlighted() instead")
+ void highlighted(const QString &);
+#endif
protected:
void focusInEvent(QFocusEvent *e) override;
diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h
index 71404964da..5967776a61 100644
--- a/src/widgets/widgets/qcombobox_p.h
+++ b/src/widgets/widgets/qcombobox_p.h
@@ -86,7 +86,7 @@ class QComboBoxListView : public QListView
{
Q_OBJECT
public:
- QComboBoxListView(QComboBox *cmb = 0) : combo(cmb) {}
+ QComboBoxListView(QComboBox *cmb = nullptr) : combo(cmb) {}
protected:
void resizeEvent(QResizeEvent *event) override
@@ -331,7 +331,7 @@ protected:
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
if (isSeparator(index)) {
- int pm = mCombo->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, mCombo);
+ int pm = mCombo->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, nullptr, mCombo);
return QSize(pm, pm);
}
return QItemDelegate::sizeHint(option, index);
@@ -390,6 +390,16 @@ public:
#ifdef Q_OS_MAC
void cleanupNativePopup();
bool showNativePopup();
+ struct IndexSetter {
+ int index;
+ QComboBox *cb;
+
+ void operator()(void)
+ {
+ cb->setCurrentIndex(index);
+ cb->d_func()->emitActivated(cb->d_func()->currentIndex);
+ }
+ };
#endif
QAbstractItemModel *model;
diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp
index 3e6afdb586..e26993fb23 100644
--- a/src/widgets/widgets/qdatetimeedit.cpp
+++ b/src/widgets/widgets/qdatetimeedit.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -37,6 +37,7 @@
**
****************************************************************************/
+#include <private/qapplication_p.h>
#include <private/qdatetimeedit_p.h>
#include <qabstractspinbox.h>
#include <qapplication.h>
@@ -153,7 +154,7 @@ QDateTimeEdit::QDateTimeEdit(QWidget *parent)
: QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
{
Q_D(QDateTimeEdit);
- d->init(QDateTime(QDATETIMEEDIT_DATE_INITIAL, QDATETIMEEDIT_TIME_MIN));
+ d->init(QDATETIMEEDIT_DATE_INITIAL.startOfDay());
}
/*!
@@ -165,8 +166,7 @@ QDateTimeEdit::QDateTimeEdit(const QDateTime &datetime, QWidget *parent)
: QAbstractSpinBox(*new QDateTimeEditPrivate, parent)
{
Q_D(QDateTimeEdit);
- d->init(datetime.isValid() ? datetime : QDateTime(QDATETIMEEDIT_DATE_INITIAL,
- QDATETIMEEDIT_TIME_MIN));
+ d->init(datetime.isValid() ? datetime : QDATETIMEEDIT_DATE_INITIAL.startOfDay());
}
/*!
@@ -312,6 +312,22 @@ void QDateTimeEdit::setTime(const QTime &time)
}
+QCalendar QDateTimeEdit::calendar() const
+{
+ Q_D(const QDateTimeEdit);
+ return d->calendar;
+}
+
+void QDateTimeEdit::setCalendar(QCalendar calendar)
+{
+ Q_D(QDateTimeEdit);
+ // Set invalid date time to prevent runtime crashes on calendar change
+ QDateTime previousValue = d->value.toDateTime();
+ setDateTime(QDateTime());
+ d->setCalendar(calendar);
+ setDateTime(previousValue);
+}
+
/*!
\property QDateTimeEdit::minimumDateTime
\since 4.4
@@ -342,7 +358,7 @@ QDateTime QDateTimeEdit::minimumDateTime() const
void QDateTimeEdit::clearMinimumDateTime()
{
- setMinimumDateTime(QDateTime(QDATETIMEEDIT_COMPAT_DATE_MIN, QDATETIMEEDIT_TIME_MIN));
+ setMinimumDateTime(QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay());
}
void QDateTimeEdit::setMinimumDateTime(const QDateTime &dt)
@@ -385,7 +401,7 @@ QDateTime QDateTimeEdit::maximumDateTime() const
void QDateTimeEdit::clearMaximumDateTime()
{
- setMaximumDateTime(QDATETIMEEDIT_DATETIME_MAX);
+ setMaximumDateTime(QDATETIMEEDIT_DATE_MAX.endOfDay());
}
void QDateTimeEdit::setMaximumDateTime(const QDateTime &dt)
@@ -643,10 +659,10 @@ QDateTimeEdit::Section QDateTimeEdit::currentSection() const
{
Q_D(const QDateTimeEdit);
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && d->focusOnButton)
+ if (QApplicationPrivate::keypadNavigationEnabled() && d->focusOnButton)
return NoSection;
#endif
- return d->convertToPublic(d->sectionType(d->currentSectionIndex));
+ return QDateTimeEditPrivate::convertToPublic(d->sectionType(d->currentSectionIndex));
}
void QDateTimeEdit::setCurrentSection(Section section)
@@ -660,7 +676,7 @@ void QDateTimeEdit::setCurrentSection(Section section)
int index = d->currentSectionIndex + 1;
for (int i=0; i<2; ++i) {
while (index < size) {
- if (d->convertToPublic(d->sectionType(index)) == section) {
+ if (QDateTimeEditPrivate::convertToPublic(d->sectionType(index)) == section) {
d->edit->setCursorPosition(d->sectionPos(index));
QDTEDEBUG << d->sectionPos(index);
return;
@@ -686,7 +702,7 @@ QDateTimeEdit::Section QDateTimeEdit::sectionAt(int index) const
Q_D(const QDateTimeEdit);
if (index < 0 || index >= d->sectionNodes.size())
return NoSection;
- return d->convertToPublic(d->sectionType(index));
+ return QDateTimeEditPrivate::convertToPublic(d->sectionType(index));
}
/*!
@@ -880,7 +896,7 @@ void QDateTimeEdit::setDisplayFormat(const QString &format)
}
d->formatExplicitlySet = true;
- d->sections = d->convertSections(d->display);
+ d->sections = QDateTimeEditPrivate::convertSections(d->display);
d->clearCache();
d->currentSectionIndex = qMin(d->currentSectionIndex, d->sectionNodes.size() - 1);
@@ -1056,7 +1072,7 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
switch (event->key()) {
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_NumberSign: //shortcut to popup calendar
- if (QApplication::keypadNavigationEnabled() && d->calendarPopupEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && d->calendarPopupEnabled()) {
d->initCalendarPopup();
d->positionCalendarPopup();
d->monthCalendar->show();
@@ -1064,7 +1080,7 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
}
break;
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (hasEditFocus()) {
if (d->focusOnButton) {
d->initCalendarPopup();
@@ -1096,7 +1112,7 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
return;
default:
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()
&& !event->text().isEmpty() && event->text().at(0).isLetterOrNumber()) {
setEditFocus(true);
@@ -1118,23 +1134,13 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
if (
#ifdef QT_KEYPAD_NAVIGATION
- QApplication::keypadNavigationEnabled() && !hasEditFocus()
- || !QApplication::keypadNavigationEnabled() &&
+ QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()
+ || !QApplicationPrivate::keypadNavigationEnabled() &&
#endif
!(event->modifiers() & Qt::ControlModifier)) {
select = false;
break;
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- else
-#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled())
-#endif
- {
- select = (event->modifiers() & Qt::ShiftModifier);
- break;
- }
-#endif
}
Q_FALLTHROUGH();
case Qt::Key_Backtab:
@@ -1148,7 +1154,7 @@ void QDateTimeEdit::keyPressEvent(QKeyEvent *event)
&& (event->key() != Qt::Key_Tab || !(event->modifiers() & Qt::ShiftModifier));
#ifdef QT_KEYPAD_NAVIGATION
int newSection = d->nextPrevSection(d->currentSectionIndex, forward);
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (d->focusOnButton) {
newSection = forward ? 0 : d->sectionNodes.size() - 1;
d->focusOnButton = false;
@@ -1291,7 +1297,7 @@ void QDateTimeEdit::stepBy(int steps)
Q_D(QDateTimeEdit);
#ifdef QT_KEYPAD_NAVIGATION
// with keypad navigation and not editFocus, left right change the date/time by a fixed amount.
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
// if date based, shift by day. else shift by 15min
if (d->sections & DateSections_Mask) {
setDateTime(dateTime().addDays(steps));
@@ -1354,7 +1360,7 @@ void QDateTimeEdit::stepBy(int steps)
QString QDateTimeEdit::textFromDateTime(const QDateTime &dateTime) const
{
Q_D(const QDateTimeEdit);
- return locale().toString(dateTime, d->displayFormat);
+ return locale().toString(dateTime, d->displayFormat, d->calendar);
}
@@ -1418,7 +1424,7 @@ QDateTimeEdit::StepEnabled QDateTimeEdit::stepEnabled() const
QAbstractSpinBox::StepEnabled ret = 0;
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
if (d->wrapping)
return StepEnabled(StepUpEnabled | StepDownEnabled);
// 3 cases. date, time, datetime. each case look
@@ -1646,7 +1652,7 @@ QDateEdit::~QDateEdit()
QDateTimeEditPrivate::QDateTimeEditPrivate()
- : QDateTimeParser(QVariant::DateTime, QDateTimeParser::DateTimeEdit)
+ : QDateTimeParser(QVariant::DateTime, QDateTimeParser::DateTimeEdit, QCalendar())
{
hasHadFocus = false;
formatExplicitlySet = false;
@@ -1660,8 +1666,8 @@ QDateTimeEditPrivate::QDateTimeEditPrivate()
first.pos = 0;
sections = 0;
calendarPopup = false;
- minimum = QDATETIMEEDIT_COMPAT_DATETIME_MIN;
- maximum = QDATETIMEEDIT_DATETIME_MAX;
+ minimum = QDATETIMEEDIT_COMPAT_DATE_MIN.startOfDay();
+ maximum = QDATETIMEEDIT_DATE_MAX.endOfDay();
arrowState = QStyle::State_None;
monthCalendar = 0;
readLocaleSettings();
@@ -1671,10 +1677,6 @@ QDateTimeEditPrivate::QDateTimeEditPrivate()
#endif
}
-QDateTimeEditPrivate::~QDateTimeEditPrivate()
-{
-}
-
void QDateTimeEditPrivate::updateTimeSpec()
{
minimum = minimum.toDateTime().toTimeSpec(spec);
@@ -1685,8 +1687,8 @@ void QDateTimeEditPrivate::updateTimeSpec()
const bool dateShown = (sections & QDateTimeEdit::DateSections_Mask);
if (!dateShown) {
if (minimum.toTime() >= maximum.toTime()){
- minimum = QDateTime(value.toDate(), QDATETIMEEDIT_TIME_MIN, spec);
- maximum = QDateTime(value.toDate(), QDATETIMEEDIT_TIME_MAX, spec);
+ minimum = value.toDate().startOfDay(spec);
+ maximum = value.toDate().endOfDay(spec);
}
}
}
@@ -1703,7 +1705,7 @@ void QDateTimeEditPrivate::updateEdit()
if (!specialValue()
#ifdef QT_KEYPAD_NAVIGATION
- && !(QApplication::keypadNavigationEnabled() && !edit->hasEditFocus())
+ && !(QApplicationPrivate::keypadNavigationEnabled() && !edit->hasEditFocus())
#endif
) {
int cursor = sectionPos(currentSectionIndex);
@@ -1732,7 +1734,7 @@ void QDateTimeEditPrivate::setSelected(int sectionIndex, bool forward)
{
if (specialValue()
#ifdef QT_KEYPAD_NAVIGATION
- || (QApplication::keypadNavigationEnabled() && !edit->hasEditFocus())
+ || (QApplicationPrivate::keypadNavigationEnabled() && !edit->hasEditFocus())
#endif
) {
edit->selectAll();
@@ -2018,8 +2020,7 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
val = (wrapping ? min + val - max - 1 : max);
}
-
- const int oldDay = v.date().day();
+ const int oldDay = v.date().day(calendar);
setDigit(v, sectionIndex, val);
// if this sets year or month it will make
@@ -2038,10 +2039,10 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
if (steps > 0) {
setDigit(v, sectionIndex, min);
if (!(sn.type & DaySectionMask) && sections & DateSectionMask) {
- const int daysInMonth = v.date().daysInMonth();
- if (v.date().day() < oldDay && v.date().day() < daysInMonth) {
+ const int daysInMonth = v.date().daysInMonth(calendar);
+ if (v.date().day(calendar) < oldDay && v.date().day(calendar) < daysInMonth) {
const int adds = qMin(oldDay, daysInMonth);
- v = v.addDays(adds - v.date().day());
+ v = v.addDays(adds - v.date().day(calendar));
}
}
@@ -2053,10 +2054,10 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
} else {
setDigit(v, sectionIndex, max);
if (!(sn.type & DaySectionMask) && sections & DateSectionMask) {
- const int daysInMonth = v.date().daysInMonth();
- if (v.date().day() < oldDay && v.date().day() < daysInMonth) {
+ const int daysInMonth = v.date().daysInMonth(calendar);
+ if (v.date().day(calendar) < oldDay && v.date().day(calendar) < daysInMonth) {
const int adds = qMin(oldDay, daysInMonth);
- v = v.addDays(adds - v.date().day());
+ v = v.addDays(adds - v.date().day(calendar));
}
}
@@ -2070,7 +2071,7 @@ QDateTime QDateTimeEditPrivate::stepBy(int sectionIndex, int steps, bool test) c
setDigit(v, sectionIndex, (steps > 0 ? localmax : localmin));
}
}
- if (!test && oldDay != v.date().day() && !(sn.type & DaySectionMask)) {
+ if (!test && oldDay != v.date().day(calendar) && !(sn.type & DaySectionMask)) {
// this should not happen when called from stepEnabled
cachedDay = qMax<int>(oldDay, cachedDay);
}
@@ -2402,7 +2403,7 @@ void QDateTimeEditPrivate::init(const QVariant &var)
Q_Q(QDateTimeEdit);
switch (var.type()) {
case QVariant::Date:
- value = QDateTime(var.toDate(), QDATETIMEEDIT_TIME_MIN);
+ value = var.toDate().startOfDay();
updateTimeSpec();
q->setDisplayFormat(defaultDateFormat);
if (sectionNodes.isEmpty()) // ### safeguard for broken locale
@@ -2427,7 +2428,7 @@ void QDateTimeEditPrivate::init(const QVariant &var)
break;
}
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
q->setCalendarPopup(true);
#endif
q->setInputMethodHints(Qt::ImhPreferNumbers);
@@ -2523,7 +2524,7 @@ void QDateTimeEditPrivate::initCalendarPopup(QCalendarWidget *cw)
{
Q_Q(QDateTimeEdit);
if (!monthCalendar) {
- monthCalendar = new QCalendarPopup(q, cw);
+ monthCalendar = new QCalendarPopup(q, cw, calendar);
monthCalendar->setObjectName(QLatin1String("qt_datetimedit_calendar"));
QObject::connect(monthCalendar, SIGNAL(newDateSelected(QDate)), q, SLOT(setDate(QDate)));
QObject::connect(monthCalendar, SIGNAL(hidingCalendar(QDate)), q, SLOT(setDate(QDate)));
@@ -2584,8 +2585,8 @@ void QDateTimeEditPrivate::syncCalendarWidget()
}
}
-QCalendarPopup::QCalendarPopup(QWidget * parent, QCalendarWidget *cw)
- : QWidget(parent, Qt::Popup)
+QCalendarPopup::QCalendarPopup(QWidget *parent, QCalendarWidget *cw, QCalendar ca)
+ : QWidget(parent, Qt::Popup), calendarSystem(ca)
{
setAttribute(Qt::WA_WindowPropagation);
@@ -2601,9 +2602,10 @@ QCalendarWidget *QCalendarPopup::verifyCalendarInstance()
{
if (calendar.isNull()) {
QCalendarWidget *cw = new QCalendarWidget(this);
+ cw->setCalendar(calendarSystem);
cw->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader);
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
cw->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames);
#endif
setCalendarWidget(cw);
@@ -2634,13 +2636,13 @@ void QCalendarPopup::setCalendarWidget(QCalendarWidget *cw)
}
-void QCalendarPopup::setDate(const QDate &date)
+void QCalendarPopup::setDate(QDate date)
{
oldDate = date;
verifyCalendarInstance()->setSelectedDate(date);
}
-void QCalendarPopup::setDateRange(const QDate &min, const QDate &max)
+void QCalendarPopup::setDateRange(QDate min, QDate max)
{
QCalendarWidget *cw = verifyCalendarInstance();
cw->setMinimumDate(min);
@@ -2684,7 +2686,7 @@ void QCalendarPopup::dateSelectionChanged()
dateChanged = true;
emit newDateSelected(verifyCalendarInstance()->selectedDate());
}
-void QCalendarPopup::dateSelected(const QDate &date)
+void QCalendarPopup::dateSelected(QDate date)
{
dateChanged = true;
emit activated(date);
diff --git a/src/widgets/widgets/qdatetimeedit.h b/src/widgets/widgets/qdatetimeedit.h
index b6fb35fc71..03994675ae 100644
--- a/src/widgets/widgets/qdatetimeedit.h
+++ b/src/widgets/widgets/qdatetimeedit.h
@@ -42,6 +42,7 @@
#include <QtWidgets/qtwidgetsglobal.h>
#include <QtCore/qdatetime.h>
+#include <QtCore/qcalendar.h>
#include <QtCore/qvariant.h>
#include <QtWidgets/qabstractspinbox.h>
@@ -102,6 +103,9 @@ public:
QDate date() const;
QTime time() const;
+ QCalendar calendar() const;
+ void setCalendar(QCalendar calendar);
+
QDateTime minimumDateTime() const;
void clearMinimumDateTime();
void setMinimumDateTime(const QDateTime &dt);
diff --git a/src/widgets/widgets/qdatetimeedit_p.h b/src/widgets/widgets/qdatetimeedit_p.h
index 1ebc98dedf..dcf8863c8b 100644
--- a/src/widgets/widgets/qdatetimeedit_p.h
+++ b/src/widgets/widgets/qdatetimeedit_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -52,6 +52,7 @@
//
#include <QtWidgets/private/qtwidgetsglobal_p.h>
+#include <QtCore/qcalendar.h>
#include "QtWidgets/qcalendarwidget.h"
#include "QtWidgets/qspinbox.h"
#include "QtWidgets/qtoolbutton.h"
@@ -70,7 +71,6 @@ class Q_AUTOTEST_EXPORT QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, p
Q_DECLARE_PUBLIC(QDateTimeEdit)
public:
QDateTimeEditPrivate();
- ~QDateTimeEditPrivate();
void init(const QVariant &var);
void readLocaleSettings();
@@ -123,7 +123,7 @@ public:
static QDateTimeEdit::Sections convertSections(QDateTimeParser::Sections s);
static QDateTimeEdit::Section convertToPublic(QDateTimeParser::Section s);
- void initCalendarPopup(QCalendarWidget *cw = 0);
+ void initCalendarPopup(QCalendarWidget *cw = nullptr);
void positionCalendarPopup();
QDateTimeEdit::Sections sections;
@@ -145,21 +145,22 @@ class QCalendarPopup : public QWidget
{
Q_OBJECT
public:
- explicit QCalendarPopup(QWidget *parent = 0, QCalendarWidget *cw = 0);
+ explicit QCalendarPopup(QWidget *parent = nullptr, QCalendarWidget *cw = nullptr,
+ QCalendar ca = QCalendar());
QDate selectedDate() { return verifyCalendarInstance()->selectedDate(); }
- void setDate(const QDate &date);
- void setDateRange(const QDate &min, const QDate &max);
+ void setDate(QDate date);
+ void setDateRange(QDate min, QDate max);
void setFirstDayOfWeek(Qt::DayOfWeek dow) { verifyCalendarInstance()->setFirstDayOfWeek(dow); }
QCalendarWidget *calendarWidget() const { return const_cast<QCalendarPopup*>(this)->verifyCalendarInstance(); }
void setCalendarWidget(QCalendarWidget *cw);
Q_SIGNALS:
- void activated(const QDate &date);
- void newDateSelected(const QDate &newDate);
- void hidingCalendar(const QDate &oldDate);
+ void activated(QDate date);
+ void newDateSelected(QDate newDate);
+ void hidingCalendar(QDate oldDate);
void resetButton();
private Q_SLOTS:
- void dateSelected(const QDate &date);
+ void dateSelected(QDate date);
void dateSelectionChanged();
protected:
@@ -174,6 +175,7 @@ private:
QPointer<QCalendarWidget> calendar;
QDate oldDate;
bool dateChanged;
+ QCalendar calendarSystem;
};
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp
index 26b86f80be..28f6cdc7bd 100644
--- a/src/widgets/widgets/qdialogbuttonbox.cpp
+++ b/src/widgets/widgets/qdialogbuttonbox.cpp
@@ -387,12 +387,25 @@ QPushButton *QDialogButtonBoxPrivate::createButton(QDialogButtonBox::StandardBut
icon = QStyle::SP_DialogNoButton;
break;
case QDialogButtonBox::YesToAll:
+ icon = QStyle::SP_DialogYesToAllButton;
+ break;
case QDialogButtonBox::NoToAll:
+ icon = QStyle::SP_DialogNoToAllButton;
+ break;
case QDialogButtonBox::SaveAll:
+ icon = QStyle::SP_DialogSaveAllButton;
+ break;
case QDialogButtonBox::Abort:
+ icon = QStyle::SP_DialogAbortButton;
+ break;
case QDialogButtonBox::Retry:
+ icon = QStyle::SP_DialogRetryButton;
+ break;
case QDialogButtonBox::Ignore:
+ icon = QStyle::SP_DialogIgnoreButton;
+ break;
case QDialogButtonBox::RestoreDefaults:
+ icon = QStyle::SP_RestoreDefaultsButton;
break;
case QDialogButtonBox::NoButton:
return 0;
diff --git a/src/widgets/widgets/qdockarealayout.cpp b/src/widgets/widgets/qdockarealayout.cpp
index 54504d124b..5900326087 100644
--- a/src/widgets/widgets/qdockarealayout.cpp
+++ b/src/widgets/widgets/qdockarealayout.cpp
@@ -138,11 +138,8 @@ bool QDockAreaLayoutItem::skip() const
QSize QDockAreaLayoutItem::minimumSize() const
{
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->minimumSize() + QSize(left+right, top+bottom);
- }
+ if (widgetItem)
+ return widgetItem->minimumSize().grownBy(widgetItem->widget()->contentsMargins());
if (subinfo != 0)
return subinfo->minimumSize();
return QSize(0, 0);
@@ -150,11 +147,8 @@ QSize QDockAreaLayoutItem::minimumSize() const
QSize QDockAreaLayoutItem::maximumSize() const
{
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->maximumSize()+ QSize(left+right, top+bottom);
- }
+ if (widgetItem)
+ return widgetItem->maximumSize().grownBy(widgetItem->widget()->contentsMargins());
if (subinfo != 0)
return subinfo->maximumSize();
return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
@@ -180,11 +174,8 @@ QSize QDockAreaLayoutItem::sizeHint() const
{
if (placeHolderItem != 0)
return QSize(0, 0);
- if (widgetItem != 0) {
- int left, top, right, bottom;
- widgetItem->widget()->getContentsMargins(&left, &top, &right, &bottom);
- return widgetItem->sizeHint() + QSize(left+right, top+bottom);
- }
+ if (widgetItem)
+ return widgetItem->sizeHint().grownBy(widgetItem->widget()->contentsMargins());
if (subinfo != 0)
return subinfo->sizeHint();
return QSize(-1, -1);
@@ -1678,12 +1669,9 @@ int QDockAreaLayoutInfo::prev(int index) const
return -1;
}
+#if QT_CONFIG(tabbar)
void QDockAreaLayoutInfo::tab(int index, QLayoutItem *dockWidgetItem)
{
-#if !QT_CONFIG(tabbar)
- Q_UNUSED(index);
- Q_UNUSED(dockWidgetItem);
-#else
if (tabbed) {
item_list.append(QDockAreaLayoutItem(dockWidgetItem));
updateTabBar();
@@ -1699,8 +1687,8 @@ void QDockAreaLayoutInfo::tab(int index, QLayoutItem *dockWidgetItem)
new_info->updateTabBar();
new_info->setCurrentTab(dockWidgetItem->widget());
}
-#endif // QT_CONFIG(tabbar)
}
+#endif // QT_CONFIG(tabbar)
void QDockAreaLayoutInfo::split(int index, Qt::Orientation orientation,
QLayoutItem *dockWidgetItem)
@@ -1937,11 +1925,6 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
QDockAreaLayoutItem item(new QDockWidgetItem(widget));
if (flags & StateFlagFloating) {
bool drawer = false;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC // drawer support
- extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
- extern bool qt_mac_set_drawer_preferred_edge(QWidget *, Qt::DockWidgetArea); //qwidget_mac.cpp
- drawer = qt_mac_is_macdrawer(widget);
-#endif
if (!testing) {
widget->hide();
@@ -1952,13 +1935,6 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*>
int x, y, w, h;
stream >> x >> y >> w >> h;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC // drawer support
- if (drawer) {
- mainWindow->window()->createWinId();
- widget->window()->createWinId();
- qt_mac_set_drawer_preferred_edge(widget, toDockWidgetArea(dockPos));
- } else
-#endif
if (!testing)
widget->setGeometry(QDockAreaLayout::constrainedRect(QRect(x, y, w, h), widget));
@@ -2052,9 +2028,8 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const
}
j++;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
sepWidget->raise();
-#endif
+
QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
sepWidget->setGeometry(sepRect);
sepWidget->setMask( QRegion(separatorRect(i).translated( - sepRect.topLeft())));
@@ -3093,10 +3068,6 @@ bool QDockAreaLayout::restoreDockWidget(QDockWidget *dockWidget)
dockWidget->d_func()->setWindowState(true, true, r);
}
dockWidget->setVisible(!placeHolder->hidden);
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- if (placeHolder->window) // gets rid of the X11BypassWindowManager window flag
- dockWidget->d_func()->setWindowState(true);
-#endif
item->placeHolderItem = 0;
delete placeHolder;
@@ -3137,6 +3108,7 @@ void QDockAreaLayout::addDockWidget(QInternal::DockPosition pos, QDockWidget *do
removePlaceHolder(dockWidget->objectName());
}
+#if QT_CONFIG(tabbar)
void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
{
const QList<int> path = indexOf(first);
@@ -3149,6 +3121,7 @@ void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
removePlaceHolder(second->objectName());
}
+#endif // QT_CONFIG(tabbar)
void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks,
const QList<int> &sizes, Qt::Orientation o)
@@ -3341,9 +3314,8 @@ void QDockAreaLayout::updateSeparatorWidgets() const
}
j++;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
sepWidget->raise();
-#endif
+
QRect sepRect = separatorRect(i).adjusted(-2, -2, 2, 2);
sepWidget->setGeometry(sepRect);
sepWidget->setMask( QRegion(separatorRect(i).translated( - sepRect.topLeft())));
diff --git a/src/widgets/widgets/qdockarealayout_p.h b/src/widgets/widgets/qdockarealayout_p.h
index 49bd157179..81384bd1b7 100644
--- a/src/widgets/widgets/qdockarealayout_p.h
+++ b/src/widgets/widgets/qdockarealayout_p.h
@@ -89,7 +89,7 @@ struct QDockAreaLayoutItem
{
enum ItemFlags { NoFlags = 0, GapItem = 1, KeepSize = 2 };
- explicit QDockAreaLayoutItem(QLayoutItem *_widgetItem = 0);
+ explicit QDockAreaLayoutItem(QLayoutItem *_widgetItem = nullptr);
explicit QDockAreaLayoutItem(QDockAreaLayoutInfo *_subinfo);
explicit QDockAreaLayoutItem(QPlaceHolderItem *_placeHolderItem);
QDockAreaLayoutItem(const QDockAreaLayoutItem &other);
@@ -144,7 +144,9 @@ public:
void remove(const QList<int> &path);
void unnest(int index);
void split(int index, Qt::Orientation orientation, QLayoutItem *dockWidgetItem);
+#if QT_CONFIG(tabbar)
void tab(int index, QLayoutItem *dockWidgetItem);
+#endif
QDockAreaLayoutItem &item(const QList<int> &path);
QDockAreaLayoutInfo *info(const QList<int> &path);
QDockAreaLayoutInfo *info(QWidget *widget);
@@ -275,7 +277,9 @@ public:
bool restoreDockWidget(QDockWidget *dockWidget);
void splitDockWidget(QDockWidget *after, QDockWidget *dockWidget,
Qt::Orientation orientation);
+#if QT_CONFIG(tabbar)
void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
+#endif
void resizeDocks(const QList<QDockWidget *> &docks, const QList<int> &sizes, Qt::Orientation o);
void apply(bool animate);
diff --git a/src/widgets/widgets/qdockwidget.cpp b/src/widgets/widgets/qdockwidget.cpp
index 4041c730b8..05ec3aface 100644
--- a/src/widgets/widgets/qdockwidget.cpp
+++ b/src/widgets/widgets/qdockwidget.cpp
@@ -267,9 +267,11 @@ QDockWidgetLayout::~QDockWidgetLayout()
bool QDockWidgetLayout::nativeWindowDeco() const
{
bool floating = parentWidget()->isWindow();
+#if QT_CONFIG(tabbar)
if (auto groupWindow =
qobject_cast<const QDockWidgetGroupWindow *>(parentWidget()->parentWidget()))
floating = floating || groupWindow->tabLayoutInfo();
+#endif
return nativeWindowDeco(floating);
}
@@ -379,11 +381,10 @@ QSize QDockWidgetLayout::sizeFromContent(const QSize &content, bool floating) co
if (content.height() < 0)
result.setHeight(-1);
- int left, top, right, bottom;
- w->getContentsMargins(&left, &top, &right, &bottom);
+ const QMargins margins = w->contentsMargins();
//we need to subtract the contents margin (it will be added by the caller)
- QSize min = w->minimumSize() - QSize(left + right, top + bottom);
- QSize max = w->maximumSize() - QSize(left + right, top + bottom);
+ QSize min = w->minimumSize().shrunkBy(margins);
+ QSize max = w->maximumSize().shrunkBy(margins);
/* A floating dockwidget will automatically get its minimumSize set to the layout's
minimum size + deco. We're *not* interested in this, we only take minimumSize()
@@ -975,11 +976,7 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event)
&& (event->pos() - state->pressPos).manhattanLength()
> QApplication::startDragDistance()) {
startDrag();
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- grabMouseWhileInWindow();
-#else
q->grabMouse();
-#endif
ret = true;
}
}
@@ -1027,13 +1024,6 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
QWidget *tl = q->topLevelWidget();
QRect geo = tl->geometry();
QRect titleRect = tl->frameGeometry();
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if ((features & QDockWidget::DockWidgetVerticalTitleBar)) {
- titleRect.setTop(geo.top());
- titleRect.setBottom(geo.bottom());
- titleRect.setRight(geo.left() - 1);
- } else
-#endif
{
titleRect.setLeft(geo.left());
titleRect.setRight(geo.right());
@@ -1182,6 +1172,8 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect
QMainWindowLayout *mwlayout = qt_mainwindow_layout_from_dock(q);
if (mwlayout)
emit q->dockLocationChanged(mwlayout->dockWidgetArea(q));
+ } else {
+ emit q->dockLocationChanged(Qt::NoDockWidgetArea);
}
}
@@ -1533,10 +1525,10 @@ bool QDockWidget::event(QEvent *event)
d->toggleViewAction->setChecked(true);
QPoint parentTopLeft(0, 0);
if (isWindow()) {
- if (const QWindow *window = windowHandle())
- parentTopLeft = window->screen()->availableVirtualGeometry().topLeft();
- else
- parentTopLeft = QGuiApplication::primaryScreen()->availableVirtualGeometry().topLeft();
+ const QScreen *screen = d->associatedScreen();
+ parentTopLeft = screen
+ ? screen->availableVirtualGeometry().topLeft()
+ : QGuiApplication::primaryScreen()->availableVirtualGeometry().topLeft();
}
emit visibilityChanged(geometry().right() >= parentTopLeft.x() && geometry().bottom() >= parentTopLeft.y());
}
@@ -1554,8 +1546,10 @@ bool QDockWidget::event(QEvent *event)
const QObjectList &siblings = win->children();
onTop = siblings.count() > 0 && siblings.last() == (QObject*)this;
}
+#if QT_CONFIG(tabbar)
if (!isFloating() && layout != 0 && onTop)
layout->raise(this);
+#endif
break;
}
case QEvent::WindowActivate:
@@ -1582,17 +1576,6 @@ bool QDockWidget::event(QEvent *event)
if (d->mouseMoveEvent(static_cast<QMouseEvent *>(event)))
return true;
break;
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- case QEvent::Leave:
- if (d->state != 0 && d->state->dragging && !d->state->nca) {
- // This is a workaround for loosing the mouse on Vista.
- QPoint pos = QCursor::pos();
- QMouseEvent fake(QEvent::MouseMove, mapFromGlobal(pos), pos, Qt::NoButton,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
- d->mouseMoveEvent(&fake);
- }
- break;
-#endif
case QEvent::MouseButtonRelease:
if (d->mouseReleaseEvent(static_cast<QMouseEvent *>(event)))
return true;
diff --git a/src/widgets/widgets/qdockwidget_p.h b/src/widgets/widgets/qdockwidget_p.h
index e224ba7143..bc6ac86c45 100644
--- a/src/widgets/widgets/qdockwidget_p.h
+++ b/src/widgets/widgets/qdockwidget_p.h
@@ -138,7 +138,7 @@ class Q_WIDGETS_EXPORT QDockWidgetLayout : public QLayout
{
Q_OBJECT
public:
- QDockWidgetLayout(QWidget *parent = 0);
+ QDockWidgetLayout(QWidget *parent = nullptr);
~QDockWidgetLayout();
void addItem(QLayoutItem *item) override;
QLayoutItem *itemAt(int index) const override;
@@ -196,15 +196,15 @@ inline QLayoutItem *QDockWidgetItem::dockWidgetChildItem() const
{
if (QDockWidgetLayout *layout = dockWidgetLayout())
return layout->itemForRole(QDockWidgetLayout::Content);
- return 0;
+ return nullptr;
}
inline QDockWidgetLayout *QDockWidgetItem::dockWidgetLayout() const
{
QWidget *w = const_cast<QDockWidgetItem*>(this)->widget();
- if (w != 0)
+ if (w != nullptr)
return qobject_cast<QDockWidgetLayout*>(w->layout());
- return 0;
+ return nullptr;
}
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qeffects.cpp b/src/widgets/widgets/qeffects.cpp
index bcc8d7815d..7069ef0368 100644
--- a/src/widgets/widgets/qeffects.cpp
+++ b/src/widgets/widgets/qeffects.cpp
@@ -99,7 +99,7 @@ static QAlphaWidget* q_blend = 0;
Constructs a QAlphaWidget.
*/
QT_WARNING_PUSH
-QT_WARNING_DISABLE_DEPRECATED // QDesktopWidget::screen()
+QT_WARNING_DISABLE_DEPRECATED // ### Qt 6: Find a replacement for QDesktopWidget::screen()
QAlphaWidget::QAlphaWidget(QWidget* w, Qt::WindowFlags f)
: QWidget(QApplication::desktop()->screen(QDesktopWidgetPrivate::screenNumber(w)), f)
{
@@ -569,8 +569,8 @@ void qScrollEffect(QWidget* w, QEffects::DirFlags orient, int time)
if (!w)
return;
- QApplication::sendPostedEvents(w, QEvent::Move);
- QApplication::sendPostedEvents(w, QEvent::Resize);
+ QCoreApplication::sendPostedEvents(w, QEvent::Move);
+ QCoreApplication::sendPostedEvents(w, QEvent::Resize);
Qt::WindowFlags flags = Qt::ToolTip;
// those can be popups - they would steal the focus, but are disabled
@@ -591,8 +591,8 @@ void qFadeEffect(QWidget* w, int time)
if (!w)
return;
- QApplication::sendPostedEvents(w, QEvent::Move);
- QApplication::sendPostedEvents(w, QEvent::Resize);
+ QCoreApplication::sendPostedEvents(w, QEvent::Move);
+ QCoreApplication::sendPostedEvents(w, QEvent::Resize);
Qt::WindowFlags flags = Qt::ToolTip;
diff --git a/src/widgets/widgets/qgroupbox.cpp b/src/widgets/widgets/qgroupbox.cpp
index 69eac1ebf7..eec794562a 100644
--- a/src/widgets/widgets/qgroupbox.cpp
+++ b/src/widgets/widgets/qgroupbox.cpp
@@ -389,9 +389,13 @@ bool QGroupBox::event(QEvent *e)
void QGroupBox::childEvent(QChildEvent *c)
{
Q_D(QGroupBox);
- if (c->type() != QEvent::ChildAdded || !c->child()->isWidgetType())
+ /*
+ Children might have been enabled after being added to the group box, in which case
+ the childEvent handler ran too early, and we need to disabled children again.
+ */
+ if (!(c->added() || c->polished()) || !c->child()->isWidgetType())
return;
- QWidget *w = (QWidget*)c->child();
+ QWidget *w = static_cast<QWidget*>(c->child());
if (w->isWindow())
return;
if (d->checkable) {
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index a5c0c41ee0..fb67936768 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -84,7 +84,7 @@
#include "qkeysequence.h"
#define ACCEL_KEY(k) ((!QCoreApplication::testAttribute(Qt::AA_DontShowIconsInMenus) \
&& QGuiApplication::styleHints()->showShortcutsInContextMenus()) \
- && !qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? \
+ && !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ? \
QLatin1Char('\t') + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
#else
#define ACCEL_KEY(k) QString()
@@ -315,7 +315,7 @@ QString QLineEdit::text() const
void QLineEdit::setText(const QString& text)
{
Q_D(QLineEdit);
- d->control->setText(text);
+ d->setText(text);
}
/*!
@@ -684,11 +684,12 @@ QSize QLineEdit::sizeHint() const
ensurePolished();
QFontMetrics fm(font());
const int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this);
- int h = qMax(fm.height(), qMax(14, iconSize - 2)) + 2*d->verticalMargin
- + d->topTextMargin + d->bottomTextMargin
+ const QMargins tm = d->effectiveTextMargins();
+ int h = qMax(fm.height(), qMax(14, iconSize - 2)) + 2 * QLineEditPrivate::verticalMargin
+ + tm.top() + tm.bottom()
+ d->topmargin + d->bottommargin;
- int w = fm.horizontalAdvance(QLatin1Char('x')) * 17 + 2*d->horizontalMargin
- + d->effectiveLeftTextMargin() + d->effectiveRightTextMargin()
+ int w = fm.horizontalAdvance(QLatin1Char('x')) * 17 + 2 * QLineEditPrivate::horizontalMargin
+ + tm.left() + tm.right()
+ d->leftmargin + d->rightmargin; // "some"
QStyleOptionFrame opt;
initStyleOption(&opt);
@@ -708,11 +709,12 @@ QSize QLineEdit::minimumSizeHint() const
Q_D(const QLineEdit);
ensurePolished();
QFontMetrics fm = fontMetrics();
- int h = fm.height() + qMax(2*d->verticalMargin, fm.leading())
- + d->topTextMargin + d->bottomTextMargin
+ const QMargins tm = d->effectiveTextMargins();
+ int h = fm.height() + qMax(2 * QLineEditPrivate::verticalMargin, fm.leading())
+ + tm.top() + tm.bottom()
+ d->topmargin + d->bottommargin;
int w = fm.maxWidth()
- + d->effectiveLeftTextMargin() + d->effectiveRightTextMargin()
+ + tm.left() + tm.right()
+ d->leftmargin + d->rightmargin;
QStyleOptionFrame opt;
initStyleOption(&opt);
@@ -1127,17 +1129,11 @@ bool QLineEdit::hasAcceptableInput() const
sizes \a left, \a top, \a right, and \a bottom.
\since 4.5
- See also getTextMargins().
+ See also textMargins().
*/
void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
{
- Q_D(QLineEdit);
- d->leftTextMargin = left;
- d->topTextMargin = top;
- d->rightTextMargin = right;
- d->bottomTextMargin = bottom;
- updateGeometry();
- update();
+ setTextMargins({left, top, right, bottom});
}
/*!
@@ -1148,10 +1144,17 @@ void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
*/
void QLineEdit::setTextMargins(const QMargins &margins)
{
- setTextMargins(margins.left(), margins.top(), margins.right(), margins.bottom());
+ Q_D(QLineEdit);
+ d->textMargins = margins;
+ updateGeometry();
+ update();
}
+#if QT_DEPRECATED_SINCE(5, 14)
/*!
+ \obsolete
+ Use textMargins()
+
Returns the widget's text margins for \a left, \a top, \a right, and \a bottom.
\since 4.5
@@ -1159,16 +1162,17 @@ void QLineEdit::setTextMargins(const QMargins &margins)
*/
void QLineEdit::getTextMargins(int *left, int *top, int *right, int *bottom) const
{
- Q_D(const QLineEdit);
+ QMargins m = textMargins();
if (left)
- *left = d->leftTextMargin;
+ *left = m.left();
if (top)
- *top = d->topTextMargin;
+ *top = m.top();
if (right)
- *right = d->rightTextMargin;
+ *right = m.right();
if (bottom)
- *bottom = d->bottomTextMargin;
+ *bottom = m.bottom();
}
+#endif
/*!
\since 4.6
@@ -1179,7 +1183,7 @@ void QLineEdit::getTextMargins(int *left, int *top, int *right, int *bottom) con
QMargins QLineEdit::textMargins() const
{
Q_D(const QLineEdit);
- return QMargins(d->leftTextMargin, d->topTextMargin, d->rightTextMargin, d->bottomTextMargin);
+ return d->textMargins;
}
/*!
@@ -1481,7 +1485,7 @@ bool QLineEdit::event(QEvent * e)
d->initMouseYThreshold();
}
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (e->type() == QEvent::EnterEditFocus) {
end(false);
d->setCursorVisible(true);
@@ -1489,8 +1493,11 @@ bool QLineEdit::event(QEvent * e)
} else if (e->type() == QEvent::LeaveEditFocus) {
d->setCursorVisible(false);
d->control->setCursorBlinkEnabled(false);
- if (d->control->hasAcceptableInput() || d->control->fixup())
+ if (d->edited && (d->control->hasAcceptableInput()
+ || d->control->fixup())) {
emit editingFinished();
+ d->edited = false;
+ }
}
}
#endif
@@ -1510,7 +1517,7 @@ void QLineEdit::mousePressEvent(QMouseEvent* e)
if (e->button() == Qt::RightButton)
return;
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplication::QApplicationPrivate() && !hasEditFocus()) {
setEditFocus(true);
// Get the completion list to pop up.
if (d->control->completer())
@@ -1603,7 +1610,7 @@ void QLineEdit::mouseReleaseEvent(QMouseEvent* e)
}
#endif
#ifndef QT_NO_CLIPBOARD
- if (QApplication::clipboard()->supportsSelection()) {
+ if (QGuiApplication::clipboard()->supportsSelection()) {
if (e->button() == Qt::LeftButton) {
d->control->copy(QClipboard::Selection);
} else if (!d->control->isReadOnly() && e->button() == Qt::MidButton) {
@@ -1719,7 +1726,7 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
bool select = false;
switch (event->key()) {
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (hasEditFocus()) {
setEditFocus(false);
if (d->control->completer() && d->control->completer()->popup()->isVisible())
@@ -1730,13 +1737,13 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
break;
case Qt::Key_Back:
case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled() || !hasEditFocus()) {
+ if (!QApplicationPrivate::keypadNavigationEnabled() || !hasEditFocus()) {
event->ignore();
return;
}
break;
default:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus() && !(event->modifiers() & Qt::ControlModifier)) {
if (!event->text().isEmpty() && event->text().at(0).isPrint()
&& !isReadOnly())
@@ -1751,7 +1758,7 @@ void QLineEdit::keyPressEvent(QKeyEvent *event)
- if (QApplication::keypadNavigationEnabled() && !select && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !select && !hasEditFocus()) {
setEditFocus(true);
if (event->key() == Qt::Key_Select)
return; // Just start. No action.
@@ -1798,7 +1805,7 @@ void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
// Focus in if currently in navigation focus on the widget
// Only focus in on preedits, to allow input methods to
// commit text as they focus out without interfering with focus
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& hasFocus() && !hasEditFocus()
&& !e->preeditString().isEmpty())
setEditFocus(true);
@@ -1871,7 +1878,7 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
d->clickCausedFocus = 1;
}
#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || (hasEditFocus() && ( e->reason() == Qt::PopupFocusReason))) {
+ if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus() && ( e->reason() == Qt::PopupFocusReason))) {
#endif
d->control->setBlinkingCursorEnabled(true);
QStyleOptionFrame opt;
@@ -1897,7 +1904,6 @@ void QLineEdit::focusInEvent(QFocusEvent *e)
/*!\reimp
*/
-
void QLineEdit::focusOutEvent(QFocusEvent *e)
{
Q_D(QLineEdit);
@@ -1916,12 +1922,14 @@ void QLineEdit::focusOutEvent(QFocusEvent *e)
d->control->setBlinkingCursorEnabled(false);
#ifdef QT_KEYPAD_NAVIGATION
// editingFinished() is already emitted on LeaveEditFocus
- if (!QApplication::keypadNavigationEnabled())
+ if (!QApplicationPrivate::keypadNavigationEnabled())
#endif
if (reason != Qt::PopupFocusReason
|| !(QApplication::activePopupWidget() && QApplication::activePopupWidget()->parentWidget() == this)) {
- if (hasAcceptableInput() || d->control->fixup())
+ if (d->edited && (hasAcceptableInput() || d->control->fixup())) {
emit editingFinished();
+ d->edited = false;
+ }
}
#ifdef QT_KEYPAD_NAVIGATION
d->control->setCancelText(QString());
@@ -1946,27 +1954,25 @@ void QLineEdit::paintEvent(QPaintEvent *)
initStyleOption(&panel);
style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &p, this);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
- r.setX(r.x() + d->effectiveLeftTextMargin());
- r.setY(r.y() + d->topTextMargin);
- r.setRight(r.right() - d->effectiveRightTextMargin());
- r.setBottom(r.bottom() - d->bottomTextMargin);
+ r = r.marginsRemoved(d->effectiveTextMargins());
p.setClipRect(r);
QFontMetrics fm = fontMetrics();
Qt::Alignment va = QStyle::visualAlignment(d->control->layoutDirection(), QFlag(d->alignment));
switch (va & Qt::AlignVertical_Mask) {
case Qt::AlignBottom:
- d->vscroll = r.y() + r.height() - fm.height() - d->verticalMargin;
+ d->vscroll = r.y() + r.height() - fm.height() - QLineEditPrivate::verticalMargin;
break;
case Qt::AlignTop:
- d->vscroll = r.y() + d->verticalMargin;
+ d->vscroll = r.y() + QLineEditPrivate::verticalMargin;
break;
default:
//center
d->vscroll = r.y() + (r.height() - fm.height() + 1) / 2;
break;
}
- QRect lineRect(r.x() + d->horizontalMargin, d->vscroll, r.width() - 2*d->horizontalMargin, fm.height());
+ QRect lineRect(r.x() + QLineEditPrivate::horizontalMargin, d->vscroll,
+ r.width() - 2 * QLineEditPrivate::horizontalMargin, fm.height());
if (d->shouldShowPlaceholderText()) {
if (!d->placeholderText.isEmpty()) {
@@ -2036,7 +2042,7 @@ void QLineEdit::paintEvent(QPaintEvent *)
int flags = QWidgetLineControl::DrawText;
#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || hasEditFocus())
+ if (!QApplicationPrivate::keypadNavigationEnabled() || hasEditFocus())
#endif
if (d->control->hasSelectedText() || (d->cursorVisible && !d->control->inputMask().isEmpty() && !d->control->isReadOnly())){
flags |= QWidgetLineControl::DrawSelections;
@@ -2202,7 +2208,7 @@ QMenu *QLineEdit::createStandardContextMenu()
if (!isReadOnly()) {
action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste));
- action->setEnabled(!d->control->isReadOnly() && !QApplication::clipboard()->text().isEmpty());
+ action->setEnabled(!d->control->isReadOnly() && !QGuiApplication::clipboard()->text().isEmpty());
setActionIcon(action, QStringLiteral("edit-paste"));
connect(action, SIGNAL(triggered()), SLOT(paste()));
}
@@ -2220,6 +2226,7 @@ QMenu *QLineEdit::createStandardContextMenu()
action = popup->addAction(QLineEdit::tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll));
action->setEnabled(!d->control->text().isEmpty() && !d->control->allSelected());
+ setActionIcon(action, QStringLiteral("edit-select-all"));
d->selectAllAction = action;
connect(action, SIGNAL(triggered()), SLOT(selectAll()));
diff --git a/src/widgets/widgets/qlineedit.h b/src/widgets/widgets/qlineedit.h
index de82927f74..1cf1f24449 100644
--- a/src/widgets/widgets/qlineedit.h
+++ b/src/widgets/widgets/qlineedit.h
@@ -172,7 +172,10 @@ public:
void setTextMargins(int left, int top, int right, int bottom);
void setTextMargins(const QMargins &margins);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("use textMargins()")
void getTextMargins(int *left, int *top, int *right, int *bottom) const;
+#endif
QMargins textMargins() const;
#if QT_CONFIG(action)
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index 2a5a0c34dc..d2b5f87906 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -127,6 +127,7 @@ void QLineEditPrivate::_q_handleWindowActivate()
void QLineEditPrivate::_q_textEdited(const QString &text)
{
Q_Q(QLineEdit);
+ edited = true;
emit q->textEdited(text);
#if QT_CONFIG(completer)
if (control->completer()
@@ -253,10 +254,7 @@ QRect QLineEditPrivate::adjustedContentsRect() const
QStyleOptionFrame opt;
q->initStyleOption(&opt);
QRect r = q->style()->subElementRect(QStyle::SE_LineEditContents, &opt, q);
- r.setX(r.x() + effectiveLeftTextMargin());
- r.setY(r.y() + topTextMargin);
- r.setRight(r.right() - effectiveRightTextMargin());
- r.setBottom(r.bottom() - bottomTextMargin);
+ r = r.marginsRemoved(effectiveTextMargins());
return r;
}
@@ -272,6 +270,12 @@ void QLineEditPrivate::setCursorVisible(bool visible)
q->update();
}
+void QLineEditPrivate::setText(const QString& text)
+{
+ edited = true;
+ control->setText(text);
+}
+
void QLineEditPrivate::updatePasswordEchoEditing(bool editing)
{
Q_Q(QLineEdit);
@@ -348,9 +352,7 @@ QLineEditPrivate *QLineEditIconButton::lineEditPrivate() const
void QLineEditIconButton::paintEvent(QPaintEvent *)
{
QPainter painter(this);
- QWindow *window = nullptr;
- if (const QWidget *nativeParent = nativeParentWidget())
- window = nativeParent->windowHandle();
+ QWindow *window = qt_widget_private(this)->windowHandle(QWidgetPrivate::WindowHandleMode::Closest);
QIcon::Mode state = QIcon::Disabled;
if (isEnabled())
state = isDown() ? QIcon::Active : QIcon::Normal;
@@ -667,14 +669,12 @@ static int effectiveTextMargin(int defaultMargin, const QLineEditPrivate::SideWi
return e.widget->isVisibleTo(e.widget->parentWidget()); }));
}
-int QLineEditPrivate::effectiveLeftTextMargin() const
-{
- return effectiveTextMargin(leftTextMargin, leftSideWidgetList(), sideWidgetParameters());
-}
-
-int QLineEditPrivate::effectiveRightTextMargin() const
+QMargins QLineEditPrivate::effectiveTextMargins() const
{
- return effectiveTextMargin(rightTextMargin, rightSideWidgetList(), sideWidgetParameters());
+ return {effectiveTextMargin(textMargins.left(), leftSideWidgetList(), sideWidgetParameters()),
+ textMargins.top(),
+ effectiveTextMargin(textMargins.right(), rightSideWidgetList(), sideWidgetParameters()),
+ textMargins.bottom()};
}
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 12a2f1ddfd..a11fea6bbe 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -67,6 +67,7 @@
#endif
#include "QtCore/qpointer.h"
#include "QtCore/qmimedata.h"
+#include <QtCore/qmargins.h>
#include "private/qwidgetlinecontrol_p.h"
@@ -85,7 +86,7 @@ class Q_AUTOTEST_EXPORT QLineEditIconButton : public QToolButton
Q_OBJECT
Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity)
public:
- explicit QLineEditIconButton(QWidget *parent = 0);
+ explicit QLineEditIconButton(QWidget *parent = nullptr);
qreal opacity() const { return m_opacity; }
void setOpacity(qreal value);
@@ -134,7 +135,7 @@ public:
};
struct SideWidgetEntry {
- explicit SideWidgetEntry(QWidget *w = 0, QAction *a = 0, int _flags = 0) : widget(w), action(a), flags(_flags) {}
+ explicit SideWidgetEntry(QWidget *w = nullptr, QAction *a = nullptr, int _flags = 0) : widget(w), action(a), flags(_flags) {}
QWidget *widget;
QAction *action;
@@ -151,9 +152,9 @@ public:
QLineEditPrivate()
: control(0), frame(1), contextMenuEnabled(1), cursorVisible(0),
- dragEnabled(0), clickCausedFocus(0), hscroll(0), vscroll(0),
+ dragEnabled(0), clickCausedFocus(0), edited(0), hscroll(0), vscroll(0),
alignment(Qt::AlignLeading | Qt::AlignVCenter),
- leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0),
+ textMargins{0, 0, 0, 0},
lastTextSize(0), mouseYThreshold(0)
{
}
@@ -176,6 +177,7 @@ public:
bool inSelection(int x) const;
QRect cursorRect() const;
void setCursorVisible(bool visible);
+ void setText(const QString& text);
void updatePasswordEchoEditing(bool);
@@ -202,6 +204,7 @@ public:
uint cursorVisible : 1;
uint dragEnabled : 1;
uint clickCausedFocus : 1;
+ uint edited : 1;
int hscroll;
int vscroll;
uint alignment;
@@ -231,10 +234,7 @@ public:
void _q_textChanged(const QString &);
void _q_clearButtonClicked();
- int leftTextMargin; // use effectiveLeftTextMargin() in case of icon.
- int topTextMargin;
- int rightTextMargin; // use effectiveRightTextMargin() in case of icon.
- int bottomTextMargin;
+ QMargins textMargins; // use effectiveTextMargins() in case of icon.
QString placeholderText;
@@ -250,8 +250,7 @@ public:
inline const SideWidgetEntryList &rightSideWidgetList() const
{ return q_func()->layoutDirection() == Qt::LeftToRight ? trailingSideWidgets : leadingSideWidgets; }
- int effectiveLeftTextMargin() const;
- int effectiveRightTextMargin() const;
+ QMargins effectiveTextMargins() const;
private:
struct SideWidgetLocation {
diff --git a/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm b/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm
index 0b64b2a2bb..88baf0410b 100644
--- a/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm
+++ b/src/widgets/widgets/qmaccocoaviewcontainer_mac.mm
@@ -82,8 +82,32 @@
The following is a snippet showing how to subclass QMacCocoaViewContainer
to wrap an NSSearchField.
- \snippet macmainwindow.mm 0
+ \code
+ SearchWidget::SearchWidget(QWidget *parent)
+ : QMacCocoaViewContainer(0, parent)
+ {
+ // Many Cocoa objects create temporary autorelease objects,
+ // so create a pool to catch them.
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ // Create the NSSearchField, set it on the QCocoaViewContainer.
+ NSSearchField *search = [[NSSearchField alloc] init];
+ setCocoaView(search);
+
+ // Use a Qt menu for the search field menu.
+ QMenu *qtMenu = createMenu(this);
+ NSMenu *nsMenu = qtMenu->macMenu(0);
+ [[search cell] setSearchMenuTemplate:nsMenu];
+
+ // Release our reference, since our super class takes ownership and we
+ // don't need it anymore.
+ [search release];
+
+ // Clean up our pool as we no longer need it.
+ [pool release];
+ }
+ \endcode
*/
QT_BEGIN_NAMESPACE
diff --git a/src/widgets/widgets/qmainwindow.cpp b/src/widgets/widgets/qmainwindow.cpp
index 9c4c46f2d6..16ed699137 100644
--- a/src/widgets/widgets/qmainwindow.cpp
+++ b/src/widgets/widgets/qmainwindow.cpp
@@ -1138,6 +1138,7 @@ void QMainWindow::splitDockWidget(QDockWidget *after, QDockWidget *dockwidget,
d_func()->layout->splitDockWidget(after, dockwidget, orientation);
}
+#if QT_CONFIG(tabbar)
/*!
\fn void QMainWindow::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
@@ -1164,9 +1165,6 @@ void QMainWindow::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) const
{
QList<QDockWidget*> ret;
-#if !QT_CONFIG(tabbar)
- Q_UNUSED(dockwidget);
-#else
const QDockAreaLayoutInfo *info = d_func()->layout->layoutState.dockAreaLayout.info(dockwidget);
if (info && info->tabbed && info->tabBar) {
for(int i = 0; i < info->item_list.count(); ++i) {
@@ -1180,9 +1178,9 @@ QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) co
}
}
}
-#endif
return ret;
}
+#endif // QT_CONFIG(tabbar)
/*!
diff --git a/src/widgets/widgets/qmainwindow.h b/src/widgets/widgets/qmainwindow.h
index 85e3f87d77..c69451fa3e 100644
--- a/src/widgets/widgets/qmainwindow.h
+++ b/src/widgets/widgets/qmainwindow.h
@@ -171,8 +171,10 @@ public:
Qt::Orientation orientation);
void splitDockWidget(QDockWidget *after, QDockWidget *dockwidget,
Qt::Orientation orientation);
+#if QT_CONFIG(tabbar)
void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
QList<QDockWidget*> tabifiedDockWidgets(QDockWidget *dockwidget) const;
+#endif
void removeDockWidget(QDockWidget *dockwidget);
bool restoreDockWidget(QDockWidget *dockwidget);
diff --git a/src/widgets/widgets/qmainwindowlayout.cpp b/src/widgets/widgets/qmainwindowlayout.cpp
index f54835f23b..0fb3a86cf8 100644
--- a/src/widgets/widgets/qmainwindowlayout.cpp
+++ b/src/widgets/widgets/qmainwindowlayout.cpp
@@ -292,25 +292,31 @@ bool QDockWidgetGroupWindow::event(QEvent *e)
switch (e->type()) {
case QEvent::Close:
+#if QT_CONFIG(tabbar)
// Forward the close to the QDockWidget just as if its close button was pressed
if (QDockWidget *dw = activeTabbedDockWidget()) {
e->ignore();
dw->close();
adjustFlags();
}
+#endif
return true;
case QEvent::Move:
+#if QT_CONFIG(tabbar)
// Let QDockWidgetPrivate::moseEvent handle the dragging
if (QDockWidget *dw = activeTabbedDockWidget())
static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->moveEvent(static_cast<QMoveEvent*>(e));
+#endif
return true;
case QEvent::NonClientAreaMouseMove:
case QEvent::NonClientAreaMouseButtonPress:
case QEvent::NonClientAreaMouseButtonRelease:
case QEvent::NonClientAreaMouseButtonDblClick:
+#if QT_CONFIG(tabbar)
// Let the QDockWidgetPrivate of the currently visible dock widget handle the drag and drop
if (QDockWidget *dw = activeTabbedDockWidget())
static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->nonClientAreaMouseEvent(static_cast<QMouseEvent*>(e));
+#endif
return true;
case QEvent::ChildAdded:
if (qobject_cast<QDockWidget *>(static_cast<QChildEvent*>(e)->child()))
@@ -347,6 +353,7 @@ QDockAreaLayoutInfo *QDockWidgetGroupWindow::layoutInfo() const
return static_cast<QDockWidgetGroupLayout *>(layout())->dockAreaLayoutInfo();
}
+#if QT_CONFIG(tabbar)
/*! \internal
If this is a floating tab bar returns the currently the QDockWidgetGroupWindow that contains
tab, otherwise, return nullptr;
@@ -383,7 +390,6 @@ const QDockAreaLayoutInfo *QDockWidgetGroupWindow::tabLayoutInfo() const
QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const
{
QDockWidget *dw = nullptr;
-#if QT_CONFIG(tabbar)
const QDockAreaLayoutInfo *info = tabLayoutInfo();
if (!info)
return nullptr;
@@ -405,9 +411,9 @@ QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const
dw = qobject_cast<QDockWidget *>(item.widgetItem->widget());
}
}
-#endif
return dw;
}
+#endif // QT_CONFIG(tabbar)
/*! \internal
Destroy or hide this window if there is no more QDockWidget in it.
@@ -461,7 +467,11 @@ void QDockWidgetGroupWindow::adjustFlags()
Qt::WindowFlags oldFlags = windowFlags();
Qt::WindowFlags flags = oldFlags;
+#if QT_CONFIG(tabbar)
QDockWidget *top = activeTabbedDockWidget();
+#else
+ QDockWidget *top = nullptr;
+#endif
if (!top) { // nested tabs, show window decoration
flags =
((oldFlags & ~Qt::FramelessWindowHint) | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
@@ -507,6 +517,7 @@ void QDockWidgetGroupWindow::adjustFlags()
bool QDockWidgetGroupWindow::hasNativeDecos() const
{
+#if QT_CONFIG(tabbar)
QDockWidget *dw = activeTabbedDockWidget();
if (!dw) // We have a group of nested QDockWidgets (not just floating tabs)
return true;
@@ -515,6 +526,9 @@ bool QDockWidgetGroupWindow::hasNativeDecos() const
return false;
return dw->titleBarWidget() == nullptr;
+#else
+ return true;
+#endif
}
/*
@@ -531,16 +545,18 @@ bool QDockWidgetGroupWindow::hover(QLayoutItem *widgetItem, const QPoint &mouseP
savedState = *layoutInfo();
QMainWindow::DockOptions opts = static_cast<QMainWindow *>(parentWidget())->dockOptions();
+ QDockAreaLayoutInfo newState = savedState;
bool nestingEnabled =
(opts & QMainWindow::AllowNestedDocks) && !(opts & QMainWindow::ForceTabbedDocks);
QDockAreaLayoutInfo::TabMode tabMode =
+#if !QT_CONFIG(tabbar)
+ QDockAreaLayoutInfo::NoTabs;
+#else
nestingEnabled ? QDockAreaLayoutInfo::AllowTabs : QDockAreaLayoutInfo::ForceTabs;
if (auto group = qobject_cast<QDockWidgetGroupWindow *>(widgetItem->widget())) {
if (!group->tabLayoutInfo())
tabMode = QDockAreaLayoutInfo::NoTabs;
}
-
- QDockAreaLayoutInfo newState = savedState;
if (newState.tabbed) {
// insertion into a top-level tab
newState.item_list = { QDockAreaLayoutItem(new QDockAreaLayoutInfo(newState)) };
@@ -548,6 +564,7 @@ bool QDockWidgetGroupWindow::hover(QLayoutItem *widgetItem, const QPoint &mouseP
newState.tabbed = false;
newState.tabBar = nullptr;
}
+#endif
auto newGapPos = newState.gapIndex(mousePos, nestingEnabled, tabMode);
Q_ASSERT(!newGapPos.isEmpty());
@@ -1498,14 +1515,6 @@ void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
invalidate();
}
-void QMainWindowLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
-{
- addChildWidget(second);
- layoutState.dockAreaLayout.tabifyDockWidget(first, second);
- emit second->dockLocationChanged(dockWidgetArea(first));
- invalidate();
-}
-
bool QMainWindowLayout::restoreDockWidget(QDockWidget *dockwidget)
{
addChildWidget(dockwidget);
@@ -1517,6 +1526,14 @@ bool QMainWindowLayout::restoreDockWidget(QDockWidget *dockwidget)
}
#if QT_CONFIG(tabbar)
+void QMainWindowLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
+{
+ addChildWidget(second);
+ layoutState.dockAreaLayout.tabifyDockWidget(first, second);
+ emit second->dockLocationChanged(dockWidgetArea(first));
+ invalidate();
+}
+
bool QMainWindowLayout::documentMode() const
{
return _documentMode;
@@ -1535,20 +1552,15 @@ void QMainWindowLayout::setDocumentMode(bool enabled)
for (QTabBar *bar : qAsConst(unusedTabBars))
bar->setDocumentMode(_documentMode);
}
-#endif // QT_CONFIG(tabbar)
void QMainWindowLayout::setVerticalTabsEnabled(bool enabled)
{
-#if !QT_CONFIG(tabbar)
- Q_UNUSED(enabled);
-#else
if (verticalTabsEnabled == enabled)
return;
verticalTabsEnabled = enabled;
updateTabBarShapes();
-#endif // QT_CONFIG(tabbar)
}
#if QT_CONFIG(tabwidget)
@@ -1609,7 +1621,6 @@ static inline QTabBar::Shape tabBarShapeFrom(QTabWidget::TabShape shape, QTabWid
}
#endif // QT_CONFIG(tabwidget)
-#if QT_CONFIG(tabbar)
void QMainWindowLayout::updateTabBarShapes()
{
#if QT_CONFIG(tabwidget)
@@ -1851,19 +1862,17 @@ void QMainWindowLayout::tabMoved(int from, int to)
info->moveTab(from, to);
}
-#endif // QT_CONFIG(tabbar)
void QMainWindowLayout::raise(QDockWidget *widget)
{
-#if QT_CONFIG(tabbar)
QDockAreaLayoutInfo *info = dockInfo(widget);
if (info == 0)
return;
if (!info->tabbed)
return;
info->setCurrentTab(widget);
-#endif
}
+#endif // QT_CONFIG(tabbar)
#endif // QT_CONFIG(dockwidget)
@@ -2329,7 +2338,7 @@ void QMainWindowLayout::setDockOptions(QMainWindow::DockOptions opts)
dockOptions = opts;
-#if QT_CONFIG(dockwidget)
+#if QT_CONFIG(dockwidget) && QT_CONFIG(tabbar)
setVerticalTabsEnabled(opts & QMainWindow::VerticalTabs);
#endif
@@ -2413,7 +2422,7 @@ static bool unplugGroup(QMainWindowLayout *layout, QLayoutItem **item,
*/
QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
{
-#if QT_CONFIG(dockwidget) && QT_CONFIG(tabbar)
+#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
auto *groupWindow = qobject_cast<const QDockWidgetGroupWindow *>(widget->parentWidget());
if (!widget->isWindow() && groupWindow) {
if (group && groupWindow->tabLayoutInfo()) {
@@ -2525,10 +2534,10 @@ void QMainWindowLayout::updateGapIndicator()
#endif // QT_CONFIG(rubberband)
}
+#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
{
QTabBar::Shape result = QTabBar::RoundedSouth;
-#if QT_CONFIG(tabwidget)
if (qobject_cast<QDockWidget *>(w)) {
switch (static_cast<QDockWidgetPrivate *>(qt_widget_private(w))->tabPosition) {
case QTabWidget::North:
@@ -2545,9 +2554,9 @@ static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
break;
}
}
-#endif // tabwidget
return result;
}
+#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
{
@@ -2584,13 +2593,14 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
}
}
for (QWidget *w : candidates) {
- QWindow *handle1 = widget->windowHandle();
- QWindow *handle2 = w->windowHandle();
- if (handle1 && handle2 && handle1->screen() != handle2->screen())
+ const QScreen *screen1 = qt_widget_private(widget)->associatedScreen();
+ const QScreen *screen2 = qt_widget_private(w)->associatedScreen();
+ if (screen1 && screen2 && screen1 != screen2)
continue;
if (!w->geometry().contains(mousePos))
continue;
+#if QT_CONFIG(tabwidget)
if (auto dropTo = qobject_cast<QDockWidget *>(w)) {
// dropping to a normal widget, we mutate it in a QDockWidgetGroupWindow with two
// tabs
@@ -2612,6 +2622,7 @@ void QMainWindowLayout::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
w = floatingTabs;
widget->raise(); // raise, as our newly created drop target is now on top
}
+#endif
Q_ASSERT(qobject_cast<QDockWidgetGroupWindow *>(w));
auto group = static_cast<QDockWidgetGroupWindow *>(w);
if (group->hover(widgetItem, group->mapFromGlobal(mousePos))) {
diff --git a/src/widgets/widgets/qmainwindowlayout_p.h b/src/widgets/widgets/qmainwindowlayout_p.h
index a375d856bb..967b713096 100644
--- a/src/widgets/widgets/qmainwindowlayout_p.h
+++ b/src/widgets/widgets/qmainwindowlayout_p.h
@@ -122,7 +122,7 @@ template <typename Layout>
QCursor QMainWindowLayoutSeparatorHelper<Layout>::separatorCursor(const QList<int> &path)
{
const QDockAreaLayoutInfo *info = layout()->dockAreaLayoutInfo()->info(path);
- Q_ASSERT(info != 0);
+ Q_ASSERT(info != nullptr);
if (path.size() == 1) { // is this the "top-level" separator which separates a dock area
// from the central widget?
switch (path.first()) {
@@ -334,11 +334,13 @@ class QDockWidgetGroupWindow : public QWidget
{
Q_OBJECT
public:
- explicit QDockWidgetGroupWindow(QWidget* parent = 0, Qt::WindowFlags f = 0)
+ explicit QDockWidgetGroupWindow(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr)
: QWidget(parent, f) {}
QDockAreaLayoutInfo *layoutInfo() const;
+#if QT_CONFIG(tabbar)
const QDockAreaLayoutInfo *tabLayoutInfo() const;
QDockWidget *activeTabbedDockWidget() const;
+#endif
void destroyOrHideIfEmpty();
void adjustFlags();
bool hasNativeDecos() const;
@@ -430,7 +432,7 @@ public:
bool isValid() const;
QLayoutItem *plug(const QList<int> &path);
- QLayoutItem *unplug(const QList<int> &path, QMainWindowLayoutState *savedState = 0);
+ QLayoutItem *unplug(const QList<int> &path, QMainWindowLayoutState *savedState = nullptr);
void saveState(QDataStream &stream) const;
bool checkFormat(QDataStream &stream);
@@ -494,13 +496,13 @@ public:
void splitDockWidget(QDockWidget *after,
QDockWidget *dockwidget,
Qt::Orientation orientation);
- void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
Qt::DockWidgetArea dockWidgetArea(QWidget* widget) const;
+ bool restoreDockWidget(QDockWidget *dockwidget);
+#if QT_CONFIG(tabbar)
+ void tabifyDockWidget(QDockWidget *first, QDockWidget *second);
void raise(QDockWidget *widget);
void setVerticalTabsEnabled(bool enabled);
- bool restoreDockWidget(QDockWidget *dockwidget);
-#if QT_CONFIG(tabbar)
QDockAreaLayoutInfo *dockInfo(QWidget *w);
bool _documentMode;
bool documentMode() const;
diff --git a/src/widgets/widgets/qmdiarea.cpp b/src/widgets/widgets/qmdiarea.cpp
index 8b201dcf9d..6e3de1b1ff 100644
--- a/src/widgets/widgets/qmdiarea.cpp
+++ b/src/widgets/widgets/qmdiarea.cpp
@@ -1988,9 +1988,11 @@ QMdiSubWindow *QMdiArea::addSubWindow(QWidget *widget, Qt::WindowFlags windowFla
Q_ASSERT(child->testAttribute(Qt::WA_DeleteOnClose));
}
+ d->appendChild(child);
+
if (childFocus)
childFocus->setFocus();
- d->appendChild(child);
+
return child;
}
@@ -2491,13 +2493,6 @@ bool QMdiArea::event(QEvent *event)
{
Q_D(QMdiArea);
switch (event->type()) {
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- // QWidgetPrivate::hide_helper activates another sub-window when closing a
- // modal dialog on Windows (see activateWindow() inside the ifdef).
- case QEvent::WindowUnblocked:
- d->activateCurrentWindow();
- break;
-#endif
case QEvent::WindowActivate: {
d->isActivated = true;
if (d->childWindows.isEmpty())
@@ -2523,7 +2518,7 @@ bool QMdiArea::event(QEvent *event)
case QEvent::WindowIconChange:
foreach (QMdiSubWindow *window, d->childWindows) {
if (sanityCheck(window, "QMdiArea::WindowIconChange"))
- QApplication::sendEvent(window, event);
+ QCoreApplication::sendEvent(window, event);
}
break;
case QEvent::Hide:
@@ -2555,11 +2550,7 @@ bool QMdiArea::eventFilter(QObject *object, QEvent *event)
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
// Ingore key events without a Ctrl modifier (except for press/release on the modifier itself).
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (!(keyEvent->modifiers() & Qt::MetaModifier) && keyEvent->key() != Qt::Key_Meta)
-#else
if (!(keyEvent->modifiers() & Qt::ControlModifier) && keyEvent->key() != Qt::Key_Control)
-#endif
return QAbstractScrollArea::eventFilter(object, event);
// Find closest mdi area (in case we have a nested workspace).
@@ -2574,11 +2565,7 @@ bool QMdiArea::eventFilter(QObject *object, QEvent *event)
// 3) Ctrl-Shift-Tab (Tab, Tab, ...) -> iterate through all windows in the opposite
// direction (activatePreviousSubWindow())
switch (keyEvent->key()) {
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- case Qt::Key_Meta:
-#else
case Qt::Key_Control:
-#endif
if (keyPress)
area->d_func()->startTabToPreviousTimer();
else
diff --git a/src/widgets/widgets/qmdiarea_p.h b/src/widgets/widgets/qmdiarea_p.h
index fd00118ec6..0a6368044a 100644
--- a/src/widgets/widgets/qmdiarea_p.h
+++ b/src/widgets/widgets/qmdiarea_p.h
@@ -183,7 +183,7 @@ public:
int tabToPreviousTimerId;
// Slots.
- void _q_deactivateAllWindows(QMdiSubWindow *aboutToActivate = 0);
+ void _q_deactivateAllWindows(QMdiSubWindow *aboutToActivate = nullptr);
void _q_processWindowStateChanged(Qt::WindowStates oldState, Qt::WindowStates newState);
void _q_currentTabChanged(int index);
void _q_closeTab(int index);
@@ -198,7 +198,7 @@ public:
void activateCurrentWindow();
void activateHighlightedWindow();
void emitWindowActivated(QMdiSubWindow *child);
- void resetActiveWindow(QMdiSubWindow *child = 0);
+ void resetActiveWindow(QMdiSubWindow *child = nullptr);
void updateActiveWindow(int removedIndex, bool activeRemoved);
void updateScrollBars();
void internalRaise(QMdiSubWindow *child) const;
diff --git a/src/widgets/widgets/qmdisubwindow.cpp b/src/widgets/widgets/qmdisubwindow.cpp
index 685c5e159e..d58a1d06db 100644
--- a/src/widgets/widgets/qmdisubwindow.cpp
+++ b/src/widgets/widgets/qmdisubwindow.cpp
@@ -288,13 +288,6 @@ static inline bool isHoverControl(QStyle::SubControl control)
return control != QStyle::SC_None && control != QStyle::SC_TitleBarLabel;
}
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
-static inline QRgb colorref2qrgb(COLORREF col)
-{
- return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
-}
-#endif
-
#ifndef QT_NO_TOOLTIP
static void showToolTip(QHelpEvent *helpEvent, QWidget *widget, const QStyleOptionComplex &opt,
QStyle::ComplexControl complexControl, QStyle::SubControl subControl)
@@ -1826,7 +1819,7 @@ void QMdiSubWindowPrivate::showButtonsInMenuBar(QMenuBar *menuBar)
// Make sure topLevelWindow->contentsRect returns correct geometry.
// topLevelWidget->updateGeoemtry will not do the trick here since it will post the event.
QEvent event(QEvent::LayoutRequest);
- QApplication::sendEvent(topLevelWindow, &event);
+ QCoreApplication::sendEvent(topLevelWindow, &event);
}
}
@@ -1926,43 +1919,7 @@ QPalette QMdiSubWindowPrivate::desktopPalette() const
QPalette newPalette = q->palette();
bool colorsInitialized = false;
-#if 0 // Used to be included in Qt4 for Q_WS_WIN // ask system properties on windows
-#ifndef SPI_GETGRADIENTCAPTIONS
-#define SPI_GETGRADIENTCAPTIONS 0x1008
-#endif
-#ifndef COLOR_GRADIENTACTIVECAPTION
-#define COLOR_GRADIENTACTIVECAPTION 27
-#endif
-#ifndef COLOR_GRADIENTINACTIVECAPTION
-#define COLOR_GRADIENTINACTIVECAPTION 28
-#endif
- if (QApplication::desktopSettingsAware()) {
- newPalette.setColor(QPalette::Active, QPalette::Highlight,
- colorref2qrgb(GetSysColor(COLOR_ACTIVECAPTION)));
- newPalette.setColor(QPalette::Inactive, QPalette::Highlight,
- colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTION)));
- newPalette.setColor(QPalette::Active, QPalette::HighlightedText,
- colorref2qrgb(GetSysColor(COLOR_CAPTIONTEXT)));
- newPalette.setColor(QPalette::Inactive, QPalette::HighlightedText,
- colorref2qrgb(GetSysColor(COLOR_INACTIVECAPTIONTEXT)));
- colorsInitialized = true;
- BOOL hasGradient = false;
- SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, &hasGradient, 0);
-
- if (hasGradient) {
- newPalette.setColor(QPalette::Active, QPalette::Base,
- colorref2qrgb(GetSysColor(COLOR_GRADIENTACTIVECAPTION)));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- colorref2qrgb(GetSysColor(COLOR_GRADIENTINACTIVECAPTION)));
- } else {
- newPalette.setColor(QPalette::Active, QPalette::Base,
- newPalette.color(QPalette::Active, QPalette::Highlight));
- newPalette.setColor(QPalette::Inactive, QPalette::Base,
- newPalette.color(QPalette::Inactive, QPalette::Highlight));
- }
- }
-#endif
if (!colorsInitialized) {
newPalette.setColor(QPalette::Active, QPalette::Highlight,
newPalette.color(QPalette::Active, QPalette::Highlight));
@@ -1986,7 +1943,7 @@ void QMdiSubWindowPrivate::updateActions()
for (int i = 0; i < NumWindowStateActions; ++i)
setVisible(WindowStateAction(i), false);
-#ifdef Q_OS_MACOS
+#if defined(Q_OS_MACOS) && QT_CONFIG(action)
if (q_func()->style()->inherits("QMacStyle"))
for (int i = 0; i < NumWindowStateActions; ++i)
if (QAction *action = actions[i])
@@ -3050,7 +3007,7 @@ void QMdiSubWindow::closeEvent(QCloseEvent *closeEvent)
d->setActive(false);
if (parentWidget() && testAttribute(Qt::WA_DeleteOnClose)) {
QChildEvent childRemoved(QEvent::ChildRemoved, this);
- QApplication::sendEvent(parentWidget(), &childRemoved);
+ QCoreApplication::sendEvent(parentWidget(), &childRemoved);
}
closeEvent->accept();
}
diff --git a/src/widgets/widgets/qmdisubwindow_p.h b/src/widgets/widgets/qmdisubwindow_p.h
index 719984c8d4..d3513b6708 100644
--- a/src/widgets/widgets/qmdisubwindow_p.h
+++ b/src/widgets/widgets/qmdisubwindow_p.h
@@ -78,7 +78,7 @@ template<typename T>
class ControlElement : public T
{
public:
- ControlElement(QMdiSubWindow *child) : T(child, 0)
+ ControlElement(QMdiSubWindow *child) : T(child, nullptr)
{
Q_ASSERT(child);
mdiChild = child;
@@ -88,7 +88,7 @@ public:
{
if (classname && strcmp(classname, "ControlElement") == 0)
return this;
- return 0;
+ return nullptr;
}
QPointer<QMdiSubWindow> mdiChild;
@@ -102,7 +102,7 @@ public:
#if QT_CONFIG(menubar)
void showButtonsInMenuBar(QMenuBar *menuBar);
- void removeButtonsFromMenuBar(QMenuBar *menuBar = 0);
+ void removeButtonsFromMenuBar(QMenuBar *menuBar = nullptr);
QMenuBar *menuBar() const { return m_menuBar; }
#endif
void updateWindowIcon(const QIcon &windowIcon);
@@ -331,7 +331,7 @@ public:
inline bool autoRaise() const
{
Q_Q(const QMdiSubWindow);
- return q->style()->styleHint(QStyle::SH_TitleBar_AutoRaise, 0, q);
+ return q->style()->styleHint(QStyle::SH_TitleBar_AutoRaise, nullptr, q);
}
inline bool isResizeOperation() const
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index c61b68e10a..51b458f03a 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -142,9 +142,7 @@ public:
#endif
if (style() != p->style())
setStyle(p->style());
- int leftMargin, topMargin, rightMargin, bottomMargin;
- p->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
- setContentsMargins(leftMargin, topMargin, rightMargin, bottomMargin);
+ setContentsMargins(p->contentsMargins());
setLayoutDirection(p->layoutDirection());
//QObject::connect(this, SIGNAL(triggered(QAction*)), this, SLOT(onTrigger(QAction*)));
//QObject::connect(this, SIGNAL(hovered(QAction*)), this, SLOT(onHovered(QAction*)));
@@ -264,7 +262,7 @@ void QMenuPrivate::copyActionToPlatformItem(const QAction *action, QPlatformMenu
item->setIconSize(w->style()->pixelMetric(QStyle::PM_SmallIconSize, &opt, w));
} else {
QStyleOption opt;
- item->setIconSize(qApp->style()->pixelMetric(QStyle::PM_SmallIconSize, &opt, 0));
+ item->setIconSize(QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize, &opt, 0));
}
} else {
item->setIcon(QIcon());
@@ -907,7 +905,7 @@ void QMenuPrivate::updateLayoutDirection()
else if (QWidget *w = q->parentWidget())
setLayoutDirection_helper(w->layoutDirection());
else
- setLayoutDirection_helper(QApplication::layoutDirection());
+ setLayoutDirection_helper(QGuiApplication::layoutDirection());
}
}
@@ -1335,7 +1333,7 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e)
if (e->type() != QEvent::MouseButtonRelease || mouseDown == caused) {
QMouseEvent new_e(e->type(), cpos, caused->mapTo(caused->topLevelWidget(), cpos), e->screenPos(),
e->button(), e->buttons(), e->modifiers(), e->source());
- QApplication::sendEvent(caused, &new_e);
+ QCoreApplication::sendEvent(caused, &new_e);
return true;
}
}
@@ -1543,7 +1541,7 @@ void QMenu::initStyleOption(QStyleOptionMenuItem *option, const QAction *action)
if (d->currentAction && d->currentAction == action && !d->currentAction->isSeparator()) {
option->state |= QStyle::State_Selected
- | (d->mouseDown ? QStyle::State_Sunken : QStyle::State_None);
+ | (QMenuPrivate::mouseDown ? QStyle::State_Sunken : QStyle::State_None);
}
option->menuHasCheckableItems = d->hasCheckableItems;
@@ -2334,14 +2332,17 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
// However if the QMenu was constructed with a QDesktopScreenWidget as its parent,
// then initialScreenIndex was set, so we should respect that for the lifetime of this menu.
// Use d->popupScreen to remember, because initialScreenIndex will be reset after the first showing.
- const int screenIndex = d->topData()->initialScreenIndex;
- if (screenIndex >= 0)
- d->popupScreen = screenIndex;
- if (auto s = QGuiApplication::screens().value(d->popupScreen)) {
- if (d->setScreen(s))
+ // However if eventLoop exists, then exec() already did this by calling createWinId(); so leave it alone. (QTBUG-76162)
+ if (!d->eventLoop) {
+ const int screenIndex = d->topData()->initialScreenIndex;
+ if (screenIndex >= 0)
+ d->popupScreen = screenIndex;
+ if (auto s = QGuiApplication::screens().value(d->popupScreen)) {
+ if (d->setScreen(s))
+ d->itemsDirty = true;
+ } else if (d->setScreenForPoint(p)) {
d->itemsDirty = true;
- } else if (d->setScreenForPoint(p)) {
- d->itemsDirty = true;
+ }
}
const bool contextMenu = d->isContextMenu();
@@ -2362,7 +2363,7 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
QRect screen;
#if QT_CONFIG(graphicsview)
- bool isEmbedded = !bypassGraphicsProxyWidget(this) && d->nearestGraphicsProxyWidget(this);
+ bool isEmbedded = !bypassGraphicsProxyWidget(this) && QMenuPrivate::nearestGraphicsProxyWidget(this);
if (isEmbedded)
screen = d->popupGeometry();
else
@@ -2392,7 +2393,7 @@ void QMenu::popup(const QPoint &p, QAction *atAction)
}
#ifdef QT_KEYPAD_NAVIGATION
- if (!atAction && QApplication::keypadNavigationEnabled()) {
+ if (!atAction && QApplicationPrivate::keypadNavigationEnabled()) {
// Try to have one item activated
if (d->defaultAction && d->defaultAction->isEnabled()) {
atAction = d->defaultAction;
@@ -2698,8 +2699,8 @@ void QMenu::hideEvent(QHideEvent *)
if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->causedPopup.widget))
mb->d_func()->setCurrentAction(0);
#endif
- if (d->mouseDown == this)
- d->mouseDown = 0;
+ if (QMenuPrivate::mouseDown == this)
+ QMenuPrivate::mouseDown = nullptr;
d->hasHadMouse = false;
if (d->activeMenu)
d->hideMenu(d->activeMenu);
@@ -2847,8 +2848,8 @@ void QMenu::paintEvent(QPaintEvent *e)
void QMenu::wheelEvent(QWheelEvent *e)
{
Q_D(QMenu);
- if (d->scroll && rect().contains(e->pos()))
- d->scrollMenu(e->delta() > 0 ?
+ if (d->scroll && rect().contains(e->position().toPoint()))
+ d->scrollMenu(e->angleDelta().y() > 0 ?
QMenuPrivate::QMenuScroller::ScrollUp : QMenuPrivate::QMenuScroller::ScrollDown);
}
#endif
@@ -2874,7 +2875,7 @@ void QMenu::mousePressEvent(QMouseEvent *e)
d->hideUpToMenuBar();
return;
}
- d->mouseDown = this;
+ QMenuPrivate::mouseDown = this;
QAction *action = d->actionAt(e->pos());
d->setCurrentAction(action, 20);
@@ -2889,12 +2890,12 @@ void QMenu::mouseReleaseEvent(QMouseEvent *e)
Q_D(QMenu);
if (d->aboutToHide || d->mouseEventTaken(e))
return;
- if(d->mouseDown != this) {
- d->mouseDown = 0;
+ if (QMenuPrivate::mouseDown != this) {
+ QMenuPrivate::mouseDown = nullptr;
return;
}
- d->mouseDown = 0;
+ QMenuPrivate::mouseDown = nullptr;
d->setSyncAction();
QAction *action = d->actionAt(e->pos());
@@ -2995,7 +2996,7 @@ QMenu::event(QEvent *e)
d->updateActionRects();
break; }
case QEvent::Show:
- d->mouseDown = 0;
+ QMenuPrivate::mouseDown = nullptr;
d->updateActionRects();
d->sloppyState.reset();
if (d->currentAction)
@@ -3385,7 +3386,7 @@ void QMenu::keyPressEvent(QKeyEvent *e)
#if QT_CONFIG(menubar)
if (QMenuBar *mb = qobject_cast<QMenuBar*>(d->topCausedWidget())) {
QAction *oldAct = mb->d_func()->currentAction;
- QApplication::sendEvent(mb, e);
+ QCoreApplication::sendEvent(mb, e);
if (mb->d_func()->currentAction != oldAct)
key_consumed = true;
}
@@ -3428,7 +3429,7 @@ void QMenu::mouseMoveEvent(QMouseEvent *e)
}
if (e->buttons())
- d->mouseDown = this;
+ QMenuPrivate::mouseDown = this;
if (d->activeMenu)
d->activeMenu->d_func()->setCurrentAction(0);
@@ -3593,7 +3594,7 @@ void QMenu::internalDelayedPopup()
QRect screen;
#if QT_CONFIG(graphicsview)
- bool isEmbedded = !bypassGraphicsProxyWidget(this) && d->nearestGraphicsProxyWidget(this);
+ bool isEmbedded = !bypassGraphicsProxyWidget(this) && QMenuPrivate::nearestGraphicsProxyWidget(this);
if (isEmbedded)
screen = d->popupGeometry();
else
diff --git a/src/widgets/widgets/qmenu_p.h b/src/widgets/widgets/qmenu_p.h
index a72592824b..efbbc099a1 100644
--- a/src/widgets/widgets/qmenu_p.h
+++ b/src/widgets/widgets/qmenu_p.h
@@ -135,9 +135,9 @@ public:
void initialize(QMenu *menu)
{
m_menu = menu;
- m_uni_directional = menu->style()->styleHint(QStyle::SH_Menu_SubMenuUniDirection, 0, menu);
- m_uni_dir_fail_at_count = short(menu->style()->styleHint(QStyle::SH_Menu_SubMenuUniDirectionFailCount, 0, menu));
- m_select_other_actions = menu->style()->styleHint(QStyle::SH_Menu_SubMenuSloppySelectOtherActions, 0 , menu);
+ m_uni_directional = menu->style()->styleHint(QStyle::SH_Menu_SubMenuUniDirection, nullptr, menu);
+ m_uni_dir_fail_at_count = short(menu->style()->styleHint(QStyle::SH_Menu_SubMenuUniDirectionFailCount, nullptr, menu));
+ m_select_other_actions = menu->style()->styleHint(QStyle::SH_Menu_SubMenuSloppySelectOtherActions, nullptr , menu);
m_timeout = short(menu->style()->styleHint(QStyle::SH_Menu_SubMenuSloppyCloseTimeout));
m_discard_state_when_entering_parent = menu->style()->styleHint(QStyle::SH_Menu_SubMenuResetWhenReenteringParent);
m_dont_start_time_on_leave = menu->style()->styleHint(QStyle::SH_Menu_SubMenuDontStartSloppyOnLeave);
@@ -378,7 +378,7 @@ public:
}
void stop()
{
- action = 0;
+ action = nullptr;
timer.stop();
}
diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp
index 9a60f1477d..3d31a3b73a 100644
--- a/src/widgets/widgets/qmenubar.cpp
+++ b/src/widgets/widgets/qmenubar.cpp
@@ -404,7 +404,7 @@ void QMenuBarPrivate::setCurrentAction(QAction *action, bool popup, bool activat
} else if (previousAction) {
QString empty;
QStatusTipEvent tip(empty);
- QApplication::sendEvent(q, &tip);
+ QCoreApplication::sendEvent(q, &tip);
#endif
}
if (fw)
@@ -701,7 +701,7 @@ void QMenuBarPrivate::init()
q->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
q->setAttribute(Qt::WA_CustomWhatsThis);
- if (!QApplication::instance()->testAttribute(Qt::AA_DontUseNativeMenuBar))
+ if (!QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuBar))
platformMenuBar = QGuiApplicationPrivate::platformTheme()->createPlatformMenuBar();
if (platformMenuBar)
diff --git a/src/widgets/widgets/qmenubar_p.h b/src/widgets/widgets/qmenubar_p.h
index c276a4512d..e3db16d190 100644
--- a/src/widgets/widgets/qmenubar_p.h
+++ b/src/widgets/widgets/qmenubar_p.h
@@ -65,9 +65,9 @@ class QMenuBarPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QMenuBar)
public:
- QMenuBarPrivate() : itemsDirty(0), currentAction(0), mouseDown(0),
+ QMenuBarPrivate() : itemsDirty(0), currentAction(nullptr), mouseDown(0),
closePopupMode(0), defaultPopDown(1), popupState(0), keyboardState(0), altPressed(0),
- doChildEffects(false), platformMenuBar(0)
+ doChildEffects(false), platformMenuBar(nullptr)
{ }
~QMenuBarPrivate()
diff --git a/src/widgets/widgets/qplaintextedit.cpp b/src/widgets/widgets/qplaintextedit.cpp
index 4a875975a4..0a81931b57 100644
--- a/src/widgets/widgets/qplaintextedit.cpp
+++ b/src/widgets/widgets/qplaintextedit.cpp
@@ -54,6 +54,7 @@
#endif
#include <qstyle.h>
#include <qtimer.h>
+#include "private/qapplication_p.h"
#include "private/qtextdocumentlayout_p.h"
#include "private/qabstracttextdocumentlayout_p.h"
#include "qtextdocument.h"
@@ -824,9 +825,6 @@ void QPlainTextEditPrivate::init(const QString &txt)
viewport->setCursor(Qt::IBeamCursor);
#endif
originalOffsetY = 0;
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- setSingleFingerPanEnabled(true);
-#endif
}
void QPlainTextEditPrivate::_q_textChanged()
@@ -1573,7 +1571,7 @@ bool QPlainTextEdit::event(QEvent *e)
}
#ifdef QT_KEYPAD_NAVIGATION
else if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
d->sendControlEvent(e);
}
#endif
@@ -1588,7 +1586,7 @@ bool QPlainTextEdit::event(QEvent *e)
d->originalOffsetY = vBar->value();
QPointF offset = g->offset();
if (!offset.isNull()) {
- if (QApplication::isRightToLeft())
+ if (QGuiApplication::isRightToLeft())
offset.rx() *= -1;
// QPlainTextEdit scrolls by lines only in vertical direction
QFontMetrics fm(document()->defaultFont());
@@ -1691,7 +1689,7 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
switch (e->key()) {
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!(d->control->textInteractionFlags() & Qt::LinksAccessibleByKeyboard))
setEditFocus(!hasEditFocus());
else {
@@ -1709,14 +1707,14 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Back:
case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled()
- || (QApplication::keypadNavigationEnabled() && !hasEditFocus())) {
+ if (!QApplicationPrivate::keypadNavigationEnabled()
+ || (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())) {
e->ignore();
return;
}
break;
default:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
if (e->text()[0].isPrint()) {
setEditFocus(true);
@@ -1792,7 +1790,7 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
switch (e->key()) {
case Qt::Key_Up:
case Qt::Key_Down:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// Cursor position didn't change, so we want to leave
// these keys to change focus.
e->ignore();
@@ -1801,7 +1799,7 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Left:
case Qt::Key_Right:
- if (QApplication::keypadNavigationEnabled()
+ if (QApplicationPrivate::keypadNavigationEnabled()
&& QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
// Same as for Key_Up and Key_Down.
e->ignore();
@@ -1810,7 +1808,7 @@ void QPlainTextEdit::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Back:
if (!e->isAutoRepeat()) {
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (document()->isEmpty()) {
setEditFocus(false);
e->accept();
@@ -1836,7 +1834,7 @@ void QPlainTextEdit::keyReleaseEvent(QKeyEvent *e)
{
#ifdef QT_KEYPAD_NAVIGATION
Q_D(QPlainTextEdit);
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
&& d->deleteAllTimer.isActive()) {
d->deleteAllTimer.stop();
@@ -2080,7 +2078,7 @@ void QPlainTextEdit::mousePressEvent(QMouseEvent *e)
{
Q_D(QPlainTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())
setEditFocus(true);
#endif
d->sendControlEvent(e);
@@ -2212,7 +2210,7 @@ void QPlainTextEdit::inputMethodEvent(QInputMethodEvent *e)
Q_D(QPlainTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
if (d->control->textInteractionFlags() & Qt::TextEditable
- && QApplication::keypadNavigationEnabled()
+ && QApplicationPrivate::keypadNavigationEnabled()
&& !hasEditFocus()) {
setEditFocus(true);
selectAll(); // so text is replaced rather than appended to
@@ -2649,7 +2647,7 @@ void QPlainTextEdit::setReadOnly(bool ro)
d->control->setTextInteractionFlags(flags);
setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
QEvent event(QEvent::ReadOnlyChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
/*!
diff --git a/src/widgets/widgets/qpushbutton.cpp b/src/widgets/widgets/qpushbutton.cpp
index b578aa0b18..f48b5706f7 100644
--- a/src/widgets/widgets/qpushbutton.cpp
+++ b/src/widgets/widgets/qpushbutton.cpp
@@ -684,38 +684,6 @@ bool QPushButton::event(QEvent *e)
return QAbstractButton::event(e);
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-/* \reimp */
-bool QPushButton::hitButton(const QPoint &pos) const
-{
- QStyleOptionButton opt;
- initStyleOption(&opt);
- if (qt_mac_buttonIsRenderedFlat(this, &opt))
- return QAbstractButton::hitButton(pos);
-
- // Now that we know we are using the native style, let's proceed.
- Q_D(const QPushButton);
- QPushButtonPrivate *nonConst = const_cast<QPushButtonPrivate *>(d);
- // In OSX buttons are round, which causes the hit method to be special.
- // We cannot simply relay on detecting if something is inside the rect or not,
- // we need to check if it is inside the "rounded area" or not. A point might
- // be inside the rect but not inside the rounded area.
- // Notice this method is only reimplemented for OSX.
- return nonConst->hitButton(pos);
-}
-
-bool QPushButtonPrivate::hitButton(const QPoint &pos)
-{
- Q_Q(QPushButton);
- QRect roundedRect(q->rect().left() + QMacStylePrivate::PushButtonLeftOffset,
- q->rect().top() + QMacStylePrivate::PushButtonContentPadding,
- q->rect().width() - QMacStylePrivate::PushButtonRightOffset,
- q->rect().height() - QMacStylePrivate::PushButtonBottomOffset);
- return roundedRect.contains(pos);
-}
-#endif
-
-
QT_END_NAMESPACE
#include "moc_qpushbutton.cpp"
diff --git a/src/widgets/widgets/qpushbutton_p.h b/src/widgets/widgets/qpushbutton_p.h
index a58675fe64..439b6e35d6 100644
--- a/src/widgets/widgets/qpushbutton_p.h
+++ b/src/widgets/widgets/qpushbutton_p.h
@@ -73,9 +73,6 @@ public:
inline void init() { resetLayoutItemMargins(); }
static QPushButtonPrivate* get(QPushButton *b) { return b->d_func(); }
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- bool hitButton(const QPoint &pos);
-#endif
#if QT_CONFIG(menu)
QPoint adjustedMenuPosition();
#endif
diff --git a/src/widgets/widgets/qrubberband.cpp b/src/widgets/widgets/qrubberband.cpp
index ade8675db8..af730f8023 100644
--- a/src/widgets/widgets/qrubberband.cpp
+++ b/src/widgets/widgets/qrubberband.cpp
@@ -45,10 +45,6 @@
#include "qstyle.h"
#include "qstyleoption.h"
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-# include <private/qt_mac_p.h>
-# include <private/qt_cocoa_helpers_mac_p.h>
-#endif
#include <qdebug.h>
@@ -140,18 +136,9 @@ QRubberBand::QRubberBand(Shape s, QWidget *p)
Q_D(QRubberBand);
d->shape = s;
setAttribute(Qt::WA_TransparentForMouseEvents);
-#if 1 // Used to be excluded in Qt4 for Q_WS_WIN
setAttribute(Qt::WA_NoSystemBackground);
-#endif
setAttribute(Qt::WA_WState_ExplicitShowHide);
setVisible(false);
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (isWindow()) {
- createWinId();
- extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
- macWindowSetHasShadow(qt_mac_window_for(this), false);
- }
-#endif
}
/*!
diff --git a/src/widgets/widgets/qscrollarea.cpp b/src/widgets/widgets/qscrollarea.cpp
index 9994344d79..68aa545082 100644
--- a/src/widgets/widgets/qscrollarea.cpp
+++ b/src/widgets/widgets/qscrollarea.cpp
@@ -46,6 +46,7 @@
#include "qapplication.h"
#include "qvariant.h"
#include "qdebug.h"
+#include "private/qapplication_p.h"
#include "private/qlayoutengine_p.h"
QT_BEGIN_NAMESPACE
@@ -300,7 +301,7 @@ bool QScrollArea::event(QEvent *e)
d->updateScrollBars();
}
#ifdef QT_KEYPAD_NAVIGATION
- else if (QApplication::keypadNavigationEnabled()) {
+ else if (QApplicationPrivate::keypadNavigationEnabled()) {
if (e->type() == QEvent::Show)
QApplication::instance()->installEventFilter(this);
else if (e->type() == QEvent::Hide)
@@ -319,7 +320,7 @@ bool QScrollArea::eventFilter(QObject *o, QEvent *e)
Q_D(QScrollArea);
#ifdef QT_KEYPAD_NAVIGATION
if (d->widget && o != d->widget && e->type() == QEvent::FocusIn
- && QApplication::keypadNavigationEnabled()) {
+ && QApplicationPrivate::keypadNavigationEnabled()) {
if (o->isWidgetType())
ensureWidgetVisible(static_cast<QWidget *>(o));
}
diff --git a/src/widgets/widgets/qscrollarea_p.h b/src/widgets/widgets/qscrollarea_p.h
index fa2e0241cf..2bdf9ed596 100644
--- a/src/widgets/widgets/qscrollarea_p.h
+++ b/src/widgets/widgets/qscrollarea_p.h
@@ -65,7 +65,7 @@ class QScrollAreaPrivate: public QAbstractScrollAreaPrivate
Q_DECLARE_PUBLIC(QScrollArea)
public:
- QScrollAreaPrivate(): resizable(false), alignment(0){}
+ QScrollAreaPrivate(): resizable(false), alignment(nullptr){}
void updateScrollBars();
void updateWidgetPosition();
QPointer<QWidget> widget;
diff --git a/src/widgets/widgets/qscrollbar.cpp b/src/widgets/widgets/qscrollbar.cpp
index b4168268a0..08d771a27a 100644
--- a/src/widgets/widgets/qscrollbar.cpp
+++ b/src/widgets/widgets/qscrollbar.cpp
@@ -497,16 +497,14 @@ bool QScrollBar::event(QEvent *event)
void QScrollBar::wheelEvent(QWheelEvent *event)
{
event->ignore();
- int delta = event->delta();
// scrollbar is a special case - in vertical mode it reaches minimum
// value in the upper position, however QSlider's minimum value is on
- // the bottom. So we need to invert a value, but since the scrollbar is
- // inverted by default, we need to inverse the delta value for the
+ // the bottom. So we need to invert the value, but since the scrollbar is
+ // inverted by default, we need to invert the delta value only for the
// horizontal orientation.
- if (event->orientation() == Qt::Horizontal)
- delta = -delta;
+ int delta = (orientation() == Qt::Horizontal ? -event->angleDelta().x() : event->angleDelta().y());
Q_D(QScrollBar);
- if (d->scrollByDelta(event->orientation(), event->modifiers(), delta))
+ if (d->scrollByDelta(orientation(), event->modifiers(), delta))
event->accept();
if (event->phase() == Qt::ScrollBegin)
diff --git a/src/widgets/widgets/qsizegrip.cpp b/src/widgets/widgets/qsizegrip.cpp
index dc5a7158dd..835af9c7b8 100644
--- a/src/widgets/widgets/qsizegrip.cpp
+++ b/src/widgets/widgets/qsizegrip.cpp
@@ -50,10 +50,6 @@
#include "qdebug.h"
#include <QDesktopWidget>
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-#include <private/qt_mac_p.h>
-#endif
-
#include <private/qwidget_p.h>
#include <private/qdesktopwidget_p.h>
#include <QtWidgets/qabstractscrollarea.h>
@@ -81,9 +77,7 @@ public:
Qt::Corner m_corner;
bool gotMousePress;
QPointer<QWidget> tlw;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- void updateMacSizer(bool hide) const;
-#endif
+
Qt::Corner corner() const;
inline bool atBottom() const
{
@@ -119,9 +113,7 @@ public:
updateTopLevelWidget();
if (tlw && showSizeGrip) {
Qt::WindowStates sizeGripNotVisibleState = Qt::WindowFullScreen;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
sizeGripNotVisibleState |= Qt::WindowMaximized;
-#endif
// Don't show the size grip if the tlw is maximized or in full screen mode.
showSizeGrip = !(tlw->windowState() & sizeGripNotVisibleState);
}
@@ -141,18 +133,6 @@ QSizeGripPrivate::QSizeGripPrivate()
{
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-void QSizeGripPrivate::updateMacSizer(bool hide) const
-{
- Q_Q(const QSizeGrip);
- if (QApplication::closingDown() || !parent)
- return;
- QWidget *topLevelWindow = qt_sizegrip_topLevelWidget(const_cast<QSizeGrip *>(q));
- if(topLevelWindow && topLevelWindow->isWindow())
- QWidgetPrivate::qt_mac_update_sizer(topLevelWindow, hide ? -1 : 1);
-}
-#endif
-
Qt::Corner QSizeGripPrivate::corner() const
{
Q_Q(const QSizeGrip);
@@ -227,7 +207,7 @@ void QSizeGripPrivate::init()
Q_Q(QSizeGrip);
m_corner = q->isLeftToRight() ? Qt::BottomRightCorner : Qt::BottomLeftCorner;
-#if !defined(QT_NO_CURSOR) && !0 /* Used to be included in Qt4 for Q_WS_MAC */
+#if !defined(QT_NO_CURSOR)
q->setCursor(m_corner == Qt::TopLeftCorner || m_corner == Qt::BottomRightCorner
? Qt::SizeFDiagCursor : Qt::SizeBDiagCursor);
#endif
@@ -440,7 +420,7 @@ void QSizeGrip::moveEvent(QMoveEvent * /*moveEvent*/)
return;
d->m_corner = d->corner();
-#if !defined(QT_NO_CURSOR) && !0 /* Used to be included in Qt4 for Q_WS_MAC */
+#if !defined(QT_NO_CURSOR)
setCursor(d->m_corner == Qt::TopLeftCorner || d->m_corner == Qt::BottomRightCorner
? Qt::SizeFDiagCursor : Qt::SizeBDiagCursor);
#endif
@@ -451,9 +431,6 @@ void QSizeGrip::moveEvent(QMoveEvent * /*moveEvent*/)
*/
void QSizeGrip::showEvent(QShowEvent *showEvent)
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- d_func()->updateMacSizer(false);
-#endif
QWidget::showEvent(showEvent);
}
@@ -462,9 +439,6 @@ void QSizeGrip::showEvent(QShowEvent *showEvent)
*/
void QSizeGrip::hideEvent(QHideEvent *hideEvent)
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- d_func()->updateMacSizer(true);
-#endif
QWidget::hideEvent(hideEvent);
}
@@ -486,9 +460,7 @@ bool QSizeGrip::eventFilter(QObject *o, QEvent *e)
return QWidget::eventFilter(o, e);
}
Qt::WindowStates sizeGripNotVisibleState = Qt::WindowFullScreen;
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
sizeGripNotVisibleState |= Qt::WindowMaximized;
-#endif
// Don't show the size grip if the tlw is maximized or in full screen mode.
setVisible(!(d->tlw->windowState() & sizeGripNotVisibleState));
setAttribute(Qt::WA_WState_ExplicitShowHide, false);
diff --git a/src/widgets/widgets/qslider.cpp b/src/widgets/widgets/qslider.cpp
index 47d3b2fb81..161e4ba27a 100644
--- a/src/widgets/widgets/qslider.cpp
+++ b/src/widgets/widgets/qslider.cpp
@@ -46,6 +46,7 @@
#include "qpainter.h"
#include "qstyle.h"
#include "qstyleoption.h"
+#include "private/qapplication_p.h"
#include "private/qabstractslider_p.h"
#include "qdebug.h"
@@ -360,7 +361,7 @@ void QSlider::mousePressEvent(QMouseEvent *ev)
return;
}
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
setEditFocus(true);
#endif
ev->accept();
diff --git a/src/widgets/widgets/qspinbox.cpp b/src/widgets/widgets/qspinbox.cpp
index 7d454c6359..61ea81c892 100644
--- a/src/widgets/widgets/qspinbox.cpp
+++ b/src/widgets/widgets/qspinbox.cpp
@@ -128,9 +128,10 @@ public:
manually. The spin box supports integer values but can be extended to
use different strings with validate(), textFromValue() and valueFromText().
- Every time the value changes QSpinBox emits two valueChanged() signals,
- one providing an int and the other a QString. The QString overload
- provides the value with both prefix() and suffix().
+ Every time the value changes QSpinBox emits valueChanged() and
+ textChanged() signals, the former providing a int and the latter
+ a QString. The textChanged() signal provides the value with both
+ prefix() and suffix().
The current value can be fetched with value() and set with setValue().
Clicking the up/down buttons or using the keyboard accelerator's
@@ -183,12 +184,23 @@ public:
*/
/*!
+ \fn void QSpinBox::textChanged(const QString &text)
+ \since 5.14
+
+ This signal is emitted whenever the spin box's text is changed.
+ The new text is passed in \a text with prefix() and suffix().
+*/
+
+#if QT_DEPRECATED_SINCE(5, 14)
+/*!
\fn void QSpinBox::valueChanged(const QString &text)
\overload
+ \obsolete Use textChanged(QString) instead
The new value is passed in \a text with prefix() and suffix().
*/
+#endif
/*!
Constructs a spin box with 0 as minimum value and 99 as maximum value, a
@@ -372,7 +384,7 @@ void QSpinBox::setMinimum(int minimum)
{
Q_D(QSpinBox);
const QVariant m(minimum);
- d->setRange(m, (d->variantCompare(d->maximum, m) > 0 ? d->maximum : m));
+ d->setRange(m, (QSpinBoxPrivate::variantCompare(d->maximum, m) > 0 ? d->maximum : m));
}
/*!
@@ -400,7 +412,7 @@ void QSpinBox::setMaximum(int maximum)
{
Q_D(QSpinBox);
const QVariant m(maximum);
- d->setRange((d->variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
+ d->setRange((QSpinBoxPrivate::variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
}
/*!
@@ -594,9 +606,9 @@ void QSpinBox::fixup(QString &input) const
values but can be extended to use different strings with
validate(), textFromValue() and valueFromText().
- Every time the value changes QDoubleSpinBox emits two
- valueChanged() signals, one taking providing a double and the other
- a QString. The QString overload provides the value with both
+ Every time the value changes QDoubleSpinBox emits valueChanged() and
+ textChanged() signals, the former providing a double and the latter
+ a QString. The textChanged() signal provides the value with both
prefix() and suffix(). The current value can be fetched with
value() and set with setValue().
@@ -644,12 +656,23 @@ void QSpinBox::fixup(QString &input) const
*/
/*!
+ \fn void QDoubleSpinBox::textChanged(const QString &text)
+ \since 5.14
+
+ This signal is emitted whenever the spin box's text is changed.
+ The new text is passed in \a text with prefix() and suffix().
+*/
+
+#if QT_DEPRECATED_SINCE(5, 14)
+/*!
\fn void QDoubleSpinBox::valueChanged(const QString &text);
\overload
+ \obsolete Use textChanged(QString) instead
The new value is passed in \a text with prefix() and suffix().
*/
+#endif
/*!
Constructs a spin box with 0.0 as minimum value and 99.99 as maximum value,
@@ -841,7 +864,7 @@ void QDoubleSpinBox::setMinimum(double minimum)
Q_D(QDoubleSpinBox);
d->actualMin = minimum;
const QVariant m(d->round(minimum));
- d->setRange(m, (d->variantCompare(d->maximum, m) > 0 ? d->maximum : m));
+ d->setRange(m, (QDoubleSpinBoxPrivate::variantCompare(d->maximum, m) > 0 ? d->maximum : m));
}
/*!
@@ -872,7 +895,7 @@ void QDoubleSpinBox::setMaximum(double maximum)
Q_D(QDoubleSpinBox);
d->actualMax = maximum;
const QVariant m(d->round(maximum));
- d->setRange((d->variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
+ d->setRange((QDoubleSpinBoxPrivate::variantCompare(d->minimum, m) < 0 ? d->minimum : m), m);
}
/*!
@@ -1072,7 +1095,13 @@ void QSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
if (ep != NeverEmit) {
pendingEmit = false;
if (ep == AlwaysEmit || value != old) {
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
emit q->valueChanged(edit->displayText());
+QT_WARNING_POP
+#endif
+ emit q->textChanged(edit->displayText());
emit q->valueChanged(value.toInt());
}
}
@@ -1223,7 +1252,13 @@ void QDoubleSpinBoxPrivate::emitSignals(EmitPolicy ep, const QVariant &old)
if (ep != NeverEmit) {
pendingEmit = false;
if (ep == AlwaysEmit || value != old) {
+#if QT_DEPRECATED_SINCE(5, 14)
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
emit q->valueChanged(edit->displayText());
+QT_WARNING_POP
+#endif
+ emit q->textChanged(edit->displayText());
emit q->valueChanged(value.toDouble());
}
}
diff --git a/src/widgets/widgets/qspinbox.h b/src/widgets/widgets/qspinbox.h
index d2eac903fb..762dd4a46a 100644
--- a/src/widgets/widgets/qspinbox.h
+++ b/src/widgets/widgets/qspinbox.h
@@ -106,7 +106,11 @@ public Q_SLOTS:
Q_SIGNALS:
void valueChanged(int);
+ void textChanged(const QString &);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("Use textChanged(QString) instead")
void valueChanged(const QString &);
+#endif
private:
Q_DISABLE_COPY(QSpinBox)
@@ -168,7 +172,11 @@ public Q_SLOTS:
Q_SIGNALS:
void valueChanged(double);
+ void textChanged(const QString &);
+#if QT_DEPRECATED_SINCE(5, 14)
+ QT_DEPRECATED_X("Use textChanged(QString) instead")
void valueChanged(const QString &);
+#endif
private:
Q_DISABLE_COPY(QDoubleSpinBox)
diff --git a/src/widgets/widgets/qsplashscreen.cpp b/src/widgets/widgets/qsplashscreen.cpp
index bf6bf1c7c9..e39ef6d1cd 100644
--- a/src/widgets/widgets/qsplashscreen.cpp
+++ b/src/widgets/widgets/qsplashscreen.cpp
@@ -111,7 +111,7 @@ public:
The user can hide the splash screen by clicking on it with the
mouse. Since the splash screen is typically displayed before the
event loop has started running, it is necessary to periodically
- call QApplication::processEvents() to receive the mouse clicks.
+ call QCoreApplication::processEvents() to receive the mouse clicks.
It is sometimes useful to update the splash screen with messages,
for example, announcing connections established or modules loaded
@@ -170,13 +170,13 @@ void QSplashScreen::mousePressEvent(QMouseEvent *)
/*!
This overrides QWidget::repaint(). It differs from the standard repaint
- function in that it also calls QApplication::processEvents() to ensure
+ function in that it also calls QCoreApplication::processEvents() to ensure
the updates are displayed, even when there is no event loop present.
*/
void QSplashScreen::repaint()
{
QWidget::repaint();
- QApplication::processEvents();
+ QCoreApplication::processEvents();
}
/*!
diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp
index de838a8f93..e7a4889996 100644
--- a/src/widgets/widgets/qsplitter.cpp
+++ b/src/widgets/widgets/qsplitter.cpp
@@ -771,14 +771,13 @@ void QSplitterPrivate::setGeo(QSplitterLayoutStruct *sls, int p, int s, bool all
if (!sls->handle->isHidden()) {
QSplitterHandle *h = sls->handle;
QSize hs = h->sizeHint();
- int left, top, right, bottom;
- h->getContentsMargins(&left, &top, &right, &bottom);
+ const QMargins m = h->contentsMargins();
if (orient==Qt::Horizontal) {
if (q->isRightToLeft())
p = contents.width() - p + hs.width();
- h->setGeometry(p-hs.width() - left, contents.y(), hs.width() + left + right, contents.height());
+ h->setGeometry(p-hs.width() - m.left(), contents.y(), hs.width() + m.left() + m.right(), contents.height());
} else {
- h->setGeometry(contents.x(), p-hs.height() - top, contents.width(), hs.height() + top + bottom);
+ h->setGeometry(contents.x(), p-hs.height() - m.top(), contents.width(), hs.height() + m.top() + m.bottom());
}
}
}
@@ -1378,7 +1377,7 @@ bool QSplitter::event(QEvent *e)
default:
;
}
- return QWidget::event(e);
+ return QFrame::event(e);
}
/*!
@@ -1793,7 +1792,7 @@ void QSplitter::setStretchFactor(int index, int stretch)
QTextStream& operator<<(QTextStream& ts, const QSplitter& splitter)
{
- ts << splitter.saveState() << endl;
+ ts << splitter.saveState() << Qt::endl;
return ts;
}
diff --git a/src/widgets/widgets/qsplitter_p.h b/src/widgets/widgets/qsplitter_p.h
index f0d621004f..871406a51d 100644
--- a/src/widgets/widgets/qsplitter_p.h
+++ b/src/widgets/widgets/qsplitter_p.h
@@ -70,7 +70,7 @@ public:
QWidget *widget;
QSplitterHandle *handle;
- QSplitterLayoutStruct() : sizer(-1), collapsed(false), collapsible(Default), widget(0), handle(0) {}
+ QSplitterLayoutStruct() : sizer(-1), collapsed(false), collapsible(Default), widget(nullptr), handle(nullptr) {}
~QSplitterLayoutStruct() { delete handle; }
int getWidgetSize(Qt::Orientation orient);
int getHandleSize(Qt::Orientation orient);
@@ -84,7 +84,7 @@ class QSplitterPrivate : public QFramePrivate
public:
QSplitterPrivate() :
#if QT_CONFIG(rubberband)
- rubberBand(0),
+ rubberBand(nullptr),
#endif
opaque(true), firstShow(true),
childrenCollapsible(true), compatMode(false), handleWidth(-1), blockChildAdd(false), opaqueResizeSet(false) {}
@@ -140,7 +140,7 @@ class QSplitterHandlePrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QSplitterHandle)
public:
- QSplitterHandlePrivate() : s(0), orient(Qt::Horizontal), mouseOffset(0), opaq(false), hover(false), pressed(false) {}
+ QSplitterHandlePrivate() : s(nullptr), orient(Qt::Horizontal), mouseOffset(0), opaq(false), hover(false), pressed(false) {}
inline int pick(const QPoint &pos) const
{ return orient == Qt::Horizontal ? pos.x() : pos.y(); }
diff --git a/src/widgets/widgets/qstatusbar.cpp b/src/widgets/widgets/qstatusbar.cpp
index e9044e6cad..39f0f11daf 100644
--- a/src/widgets/widgets/qstatusbar.cpp
+++ b/src/widgets/widgets/qstatusbar.cpp
@@ -90,10 +90,6 @@ public:
int savedStrut;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- QPoint dragStart;
-#endif
-
int indexToLastNonPermanentWidget() const
{
int i = items.size() - 1;
@@ -747,44 +743,7 @@ bool QStatusBar::event(QEvent *e)
}
}
-// On Mac OS X Leopard it is possible to drag the window by clicking
-// on the tool bar on most applications.
-#if 1 // Used to be excluded in Qt4 for Q_WS_MAC
return QWidget::event(e);
-#else
- // Enable drag-click only if the status bar is the status bar for a
- // QMainWindow with a unifed toolbar.
- if (parent() == 0 || qobject_cast<QMainWindow *>(parent()) == 0 ||
- qobject_cast<QMainWindow *>(parent())->unifiedTitleAndToolBarOnMac() == false )
- return QWidget::event(e);
-
- // Check for mouse events.
- QMouseEvent *mouseEvent;
- if (e->type() == QEvent::MouseButtonPress ||
- e->type() == QEvent::MouseMove ||
- e->type() == QEvent::MouseButtonRelease) {
- mouseEvent = static_cast <QMouseEvent*>(e);
- } else {
- return QWidget::event(e);
- }
-
- // The following is a standard mouse drag handler.
- if (e->type() == QEvent::MouseButtonPress && (mouseEvent->button() == Qt::LeftButton)) {
- d->dragStart = mouseEvent->pos();
- } else if (e->type() == QEvent::MouseMove){
- if (d->dragStart == QPoint())
- return QWidget::event(e);
- QPoint pos = mouseEvent->pos();
- QPoint delta = (pos - d->dragStart);
- window()->move(window()->pos() + delta);
- } else if (e->type() == QEvent::MouseButtonRelease && (mouseEvent->button() == Qt::LeftButton)){
- d->dragStart = QPoint();
- } else {
- return QWidget::event(e);
- }
-
- return true;
-#endif
}
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qtabbar.cpp b/src/widgets/widgets/qtabbar.cpp
index b13f4da9d2..7e1794efef 100644
--- a/src/widgets/widgets/qtabbar.cpp
+++ b/src/widgets/widgets/qtabbar.cpp
@@ -65,13 +65,9 @@
#endif
#include "qdebug.h"
+#include "private/qapplication_p.h"
#include "private/qtabbar_p.h"
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
-#include <private/qt_mac_p.h>
-#include <private/qt_cocoa_helpers_mac_p.h>
-#endif
-
QT_BEGIN_NAMESPACE
namespace {
@@ -415,7 +411,7 @@ void QTabBarPrivate::init()
QObject::connect(rightB, SIGNAL(clicked()), q, SLOT(_q_scrollTabs()));
rightB->hide();
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
leftB->setFocusPolicy(Qt::NoFocus);
rightB->setFocusPolicy(Qt::NoFocus);
q->setFocusPolicy(Qt::NoFocus);
@@ -843,7 +839,7 @@ void QTabBarPrivate::refresh()
// be safe in case a subclass is also handling move with the tabs
if (pressedIndex != -1
&& movable
- && QApplication::mouseButtons() == Qt::NoButton) {
+ && QGuiApplication::mouseButtons() == Qt::NoButton) {
moveTabFinished(pressedIndex);
if (!validIndex(pressedIndex))
pressedIndex = -1;
@@ -1975,9 +1971,7 @@ void QTabBar::mousePressEvent(QMouseEvent *event)
d->moveTabFinished(d->pressedIndex);
d->pressedIndex = d->indexAtPos(event->pos());
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- d->previousPressedIndex = d->pressedIndex;
-#endif
+
if (d->validIndex(d->pressedIndex)) {
QStyleOptionTabBarBase optTabBase;
optTabBase.init(this);
@@ -2057,17 +2051,6 @@ void QTabBar::mouseMoveEvent(QMouseEvent *event)
update();
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- } else if (!d->documentMode && event->buttons() == Qt::LeftButton && d->previousPressedIndex != -1) {
- int newPressedIndex = d->indexAtPos(event->pos());
- if (d->pressedIndex == -1 && d->previousPressedIndex == newPressedIndex) {
- d->pressedIndex = d->previousPressedIndex;
- update(tabRect(d->pressedIndex));
- } else if(d->pressedIndex != newPressedIndex) {
- d->pressedIndex = -1;
- update(tabRect(d->previousPressedIndex));
- }
-#endif
}
if (event->buttons() != Qt::LeftButton) {
@@ -2161,9 +2144,7 @@ void QTabBar::mouseReleaseEvent(QMouseEvent *event)
event->ignore();
return;
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- d->previousPressedIndex = -1;
-#endif
+
if (d->movable && d->dragInProgress && d->validIndex(d->pressedIndex)) {
int length = d->tabList[d->pressedIndex].dragOffset;
int width = verticalTabs(d->shape)
@@ -2210,7 +2191,9 @@ void QTabBar::wheelEvent(QWheelEvent *event)
{
#ifndef Q_OS_MAC
Q_D(QTabBar);
- int offset = event->delta() > 0 ? -1 : 1;
+ int delta = (qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y()) ?
+ event->angleDelta().x() : event->angleDelta().y());
+ int offset = delta > 0 ? -1 : 1;
d->setCurrentNextEnabledIndex(offset);
QWidget::wheelEvent(event);
#else
diff --git a/src/widgets/widgets/qtabbar_p.h b/src/widgets/widgets/qtabbar_p.h
index 9b798e89c9..5552c43548 100644
--- a/src/widgets/widgets/qtabbar_p.h
+++ b/src/widgets/widgets/qtabbar_p.h
@@ -92,10 +92,7 @@ public:
drawBase(true), scrollOffset(0), hoverIndex(-1), elideModeSetByUser(false), useScrollButtonsSetByUser(false), expanding(true), closeButtonOnTabs(false),
selectionBehaviorOnRemove(QTabBar::SelectRightTab), paintWithOffsets(true), movable(false),
dragInProgress(false), documentMode(false), autoHide(false), changeCurrentOnDrag(false),
- switchTabCurrentIndex(-1), switchTabTimerId(0), movingTab(0)
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- , previousPressedIndex(-1)
-#endif
+ switchTabCurrentIndex(-1), switchTabTimerId(0), movingTab(nullptr)
{}
int currentIndex;
@@ -182,7 +179,7 @@ public:
int indexAtPos(const QPoint &p) const;
- inline bool isAnimated() const { Q_Q(const QTabBar); return q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, 0, q) > 0; }
+ inline bool isAnimated() const { Q_Q(const QTabBar); return q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, q) > 0; }
inline bool validIndex(int index) const { return index >= 0 && index < tabList.count(); }
void setCurrentNextEnabledIndex(int offset);
@@ -232,9 +229,6 @@ public:
int switchTabTimerId;
QMovableTabWidget *movingTab;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- int previousPressedIndex;
-#endif
// shared by tabwidget and qtabbar
static void initStyleBaseOption(QStyleOptionTabBarBase *optTabBase, QTabBar *tabbar, QSize size)
{
diff --git a/src/widgets/widgets/qtabwidget.cpp b/src/widgets/widgets/qtabwidget.cpp
index 547b8a82f9..4d7b39ae01 100644
--- a/src/widgets/widgets/qtabwidget.cpp
+++ b/src/widgets/widgets/qtabwidget.cpp
@@ -39,6 +39,7 @@
#include "qtabwidget.h"
+#include "private/qapplication_p.h"
#include "private/qwidget_p.h"
#include "private/qtabbar_p.h"
#include "qapplication.h"
@@ -241,7 +242,7 @@ void QTabWidgetPrivate::init()
q->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding,
QSizePolicy::TabWidget));
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
q->setFocusPolicy(Qt::NoFocus);
else
#endif
@@ -1108,14 +1109,14 @@ void QTabWidget::keyPressEvent(QKeyEvent *e)
if (((e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab) &&
count() > 1 && e->modifiers() & Qt::ControlModifier)
#ifdef QT_KEYPAD_NAVIGATION
- || QApplication::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) && count() > 1
+ || QApplicationPrivate::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right) && count() > 1
#endif
) {
int pageCount = d->tabs->count();
int page = currentIndex();
int dx = (e->key() == Qt::Key_Backtab || e->modifiers() & Qt::ShiftModifier) ? -1 : 1;
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
+ if (QApplicationPrivate::keypadNavigationEnabled() && (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right))
dx = e->key() == (isRightToLeft() ? Qt::Key_Right : Qt::Key_Left) ? -1 : 1;
#endif
for (int pass = 0; pass < pageCount; ++pass) {
diff --git a/src/widgets/widgets/qtextbrowser.cpp b/src/widgets/widgets/qtextbrowser.cpp
index bb9a4fed91..3e49390315 100644
--- a/src/widgets/widgets/qtextbrowser.cpp
+++ b/src/widgets/widgets/qtextbrowser.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -42,6 +42,7 @@
#include <qstack.h>
#include <qapplication.h>
+#include <private/qapplication_p.h>
#include <qevent.h>
#include <qdesktopwidget.h>
#include <qdebug.h>
@@ -60,6 +61,8 @@
QT_BEGIN_NAMESPACE
+Q_LOGGING_CATEGORY(lcBrowser, "qt.text.browser")
+
class QTextBrowserPrivate : public QTextEditPrivate
{
Q_DECLARE_PUBLIC(QTextBrowser)
@@ -83,6 +86,7 @@ public:
int hpos;
int vpos;
int focusIndicatorPosition, focusIndicatorAnchor;
+ QTextDocument::ResourceType type = QTextDocument::UnknownResource;
};
HistoryEntry history(int i) const
@@ -119,6 +123,8 @@ public:
bool openExternalLinks;
bool openLinks;
+ QTextDocument::ResourceType currentType;
+
#ifndef QT_NO_CURSOR
QCursor oldCursor;
#endif
@@ -134,7 +140,7 @@ public:
void _q_activateAnchor(const QString &href);
void _q_highlightLink(const QString &href);
- void setSource(const QUrl &url);
+ void setSource(const QUrl &url, QTextDocument::ResourceType type);
// re-imlemented from QTextEditPrivate
virtual QUrl resolveUrl(const QUrl &url) const override;
@@ -271,7 +277,7 @@ void QTextBrowserPrivate::_q_highlightLink(const QString &anchor)
}
}
-void QTextBrowserPrivate::setSource(const QUrl &url)
+void QTextBrowserPrivate::setSource(const QUrl &url, QTextDocument::ResourceType type)
{
Q_Q(QTextBrowser);
#ifndef QT_NO_CURSOR
@@ -288,20 +294,36 @@ void QTextBrowserPrivate::setSource(const QUrl &url)
currentUrlWithoutFragment.setFragment(QString());
QUrl newUrlWithoutFragment = currentURL.resolved(url);
newUrlWithoutFragment.setFragment(QString());
+ QString fileName = url.fileName();
+ if (type == QTextDocument::UnknownResource) {
+#if QT_CONFIG(textmarkdownreader)
+ if (fileName.endsWith(QLatin1String(".md")) ||
+ fileName.endsWith(QLatin1String(".mkd")) ||
+ fileName.endsWith(QLatin1String(".markdown")))
+ type = QTextDocument::MarkdownResource;
+ else
+#endif
+ type = QTextDocument::HtmlResource;
+ }
+ currentType = type;
if (url.isValid()
&& (newUrlWithoutFragment != currentUrlWithoutFragment || forceLoadOnSourceChange)) {
- QVariant data = q->loadResource(QTextDocument::HtmlResource, resolveUrl(url));
+ QVariant data = q->loadResource(type, resolveUrl(url));
if (data.type() == QVariant::String) {
txt = data.toString();
} else if (data.type() == QVariant::ByteArray) {
+ if (type == QTextDocument::HtmlResource) {
#if QT_CONFIG(textcodec)
- QByteArray ba = data.toByteArray();
- QTextCodec *codec = Qt::codecForHtml(ba);
- txt = codec->toUnicode(ba);
+ QByteArray ba = data.toByteArray();
+ QTextCodec *codec = Qt::codecForHtml(ba);
+ txt = codec->toUnicode(ba);
#else
- txt = data.toString();
+ txt = data.toString();
#endif
+ } else {
+ txt = QString::fromUtf8(data.toByteArray());
+ }
}
if (Q_UNLIKELY(txt.isEmpty()))
qWarning("QTextBrowser: No document for %s", url.toString().toLatin1().constData());
@@ -327,9 +349,21 @@ void QTextBrowserPrivate::setSource(const QUrl &url)
home = url;
if (doSetText) {
+ // Setting the base URL helps QTextDocument::resource() to find resources with relative paths.
+ // But don't set it unless it contains the document's path, because QTextBrowserPrivate::resolveUrl()
+ // can already deal with local files on the filesystem in case the base URL was not set.
+ QUrl baseUrl = currentURL.adjusted(QUrl::RemoveFilename);
+ if (!baseUrl.path().isEmpty())
+ q->document()->setBaseUrl(baseUrl);
+ q->document()->setMetaInformation(QTextDocument::DocumentUrl, currentURL.toString());
+ qCDebug(lcBrowser) << "loading" << currentURL << "base" << q->document()->baseUrl() << "type" << type << txt.size() << "chars";
+#if QT_CONFIG(textmarkdownreader)
+ if (type == QTextDocument::MarkdownResource)
+ q->QTextEdit::setMarkdown(txt);
+ else
+#endif
#ifndef QT_NO_TEXTHTMLPARSER
q->QTextEdit::setHtml(txt);
- q->document()->setMetaInformation(QTextDocument::DocumentUrl, currentURL.toString());
#else
q->QTextEdit::setPlainText(txt);
#endif
@@ -551,6 +585,7 @@ QTextBrowserPrivate::HistoryEntry QTextBrowserPrivate::createHistoryEntry() cons
{
HistoryEntry entry;
entry.url = q_func()->source();
+ entry.type = q_func()->sourceType();
entry.title = q_func()->documentTitle();
entry.hpos = hbar->value();
entry.vpos = vbar->value();
@@ -567,7 +602,7 @@ QTextBrowserPrivate::HistoryEntry QTextBrowserPrivate::createHistoryEntry() cons
void QTextBrowserPrivate::restoreHistoryEntry(const HistoryEntry &entry)
{
- setSource(entry.url);
+ setSource(entry.url, entry.type);
hbar->setValue(entry.hpos);
vbar->setValue(entry.vpos);
if (entry.focusIndicatorAnchor != -1 && entry.focusIndicatorPosition != -1) {
@@ -709,7 +744,13 @@ QTextBrowser::~QTextBrowser()
document is displayed as a popup rather than as new document in
the browser window itself. Otherwise, the document is displayed
normally in the text browser with the text set to the contents of
- the named document with setHtml().
+ the named document with \l QTextDocument::setHtml() or
+ \l QTextDocument::setMarkdown(), depending on whether the filename ends
+ with any of the known Markdown file extensions.
+
+ If you would like to avoid automatic type detection
+ and specify the type explicitly, call setSource() rather than
+ setting this property.
By default, this property contains an empty URL.
*/
@@ -723,6 +764,23 @@ QUrl QTextBrowser::source() const
}
/*!
+ \property QTextBrowser::sourceType
+ \brief the type of the displayed document
+
+ This is QTextDocument::UnknownResource if no document is displayed or if
+ the type of the source is unknown. Otherwise it holds the type that was
+ detected, or the type that was specified when setSource() was called.
+*/
+QTextDocument::ResourceType QTextBrowser::sourceType() const
+{
+ Q_D(const QTextBrowser);
+ if (d->stack.isEmpty())
+ return QTextDocument::UnknownResource;
+ else
+ return d->stack.top().type;
+}
+
+/*!
\property QTextBrowser::searchPaths
\brief the search paths used by the text browser to find supporting
content
@@ -752,16 +810,46 @@ void QTextBrowser::reload()
Q_D(QTextBrowser);
QUrl s = d->currentURL;
d->currentURL = QUrl();
- setSource(s);
+ setSource(s, d->currentType);
}
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
void QTextBrowser::setSource(const QUrl &url)
{
+ setSource(url, QTextDocument::UnknownResource);
+}
+#endif
+
+/*!
+ Attempts to load the document at the given \a url with the specified \a type.
+
+ If \a type is \l {QTextDocument::ResourceType::UnknownResource}{UnknownResource}
+ (the default), the document type will be detected: that is, if the url ends
+ with an extension of \c{.md}, \c{.mkd} or \c{.markdown}, the document will be
+ loaded via \l QTextDocument::setMarkdown(); otherwise it will be loaded via
+ \l QTextDocument::setHtml(). This detection can be bypassed by specifying
+ the \a type explicitly.
+*/
+void QTextBrowser::setSource(const QUrl &url, QTextDocument::ResourceType type)
+{
+ doSetSource(url, type);
+}
+
+#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
+/*!
+ Attempts to load the document at the given \a url with the specified \a type.
+
+ setSource() calls doSetSource. In Qt 5, setSource(const QUrl &url) was virtual.
+ In Qt 6, doSetSource() is virtual instead, so that it can be overridden in subclasses.
+*/
+#endif
+void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type)
+{
Q_D(QTextBrowser);
const QTextBrowserPrivate::HistoryEntry historyEntry = d->createHistoryEntry();
- d->setSource(url);
+ d->setSource(url, type);
if (!url.isValid())
return;
@@ -775,6 +863,7 @@ void QTextBrowser::setSource(const QUrl &url)
QTextBrowserPrivate::HistoryEntry entry;
entry.url = url;
+ entry.type = d->currentType;
entry.title = documentTitle();
entry.hpos = 0;
entry.vpos = 0;
@@ -928,7 +1017,7 @@ void QTextBrowser::keyPressEvent(QKeyEvent *ev)
Q_D(QTextBrowser);
switch (ev->key()) {
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus()) {
setEditFocus(true);
return;
@@ -943,7 +1032,7 @@ void QTextBrowser::keyPressEvent(QKeyEvent *ev)
}
break;
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (hasEditFocus()) {
setEditFocus(false);
ev->accept();
@@ -953,7 +1042,7 @@ void QTextBrowser::keyPressEvent(QKeyEvent *ev)
QTextEdit::keyPressEvent(ev);
return;
default:
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus()) {
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus()) {
ev->ignore();
return;
}
@@ -1086,6 +1175,7 @@ void QTextBrowser::paintEvent(QPaintEvent *e)
\row \li QTextDocument::HtmlResource \li QString or QByteArray
\row \li QTextDocument::ImageResource \li QImage, QPixmap or QByteArray
\row \li QTextDocument::StyleSheetResource \li QString or QByteArray
+ \row \li QTextDocument::MarkdownResource \li QString or QByteArray
\endtable
*/
QVariant QTextBrowser::loadResource(int /*type*/, const QUrl &name)
diff --git a/src/widgets/widgets/qtextbrowser.h b/src/widgets/widgets/qtextbrowser.h
index ea81256f50..33e5b3980c 100644
--- a/src/widgets/widgets/qtextbrowser.h
+++ b/src/widgets/widgets/qtextbrowser.h
@@ -55,6 +55,7 @@ class Q_WIDGETS_EXPORT QTextBrowser : public QTextEdit
Q_OBJECT
Q_PROPERTY(QUrl source READ source WRITE setSource)
+ Q_PROPERTY(QTextDocument::ResourceType sourceType READ sourceType)
Q_OVERRIDE(bool modified SCRIPTABLE false)
Q_OVERRIDE(bool readOnly DESIGNABLE false SCRIPTABLE false)
Q_OVERRIDE(bool undoRedoEnabled DESIGNABLE false SCRIPTABLE false)
@@ -67,6 +68,7 @@ public:
virtual ~QTextBrowser();
QUrl source() const;
+ QTextDocument::ResourceType sourceType() const;
QStringList searchPaths() const;
void setSearchPaths(const QStringList &paths);
@@ -88,7 +90,12 @@ public:
void setOpenLinks(bool open);
public Q_SLOTS:
+#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
virtual void setSource(const QUrl &name);
+ void setSource(const QUrl &name, QTextDocument::ResourceType type);
+#else
+ void setSource(const QUrl &name, QTextDocument::ResourceType type = QTextDocument::UnknownResource);
+#endif
virtual void backward();
virtual void forward();
virtual void home();
@@ -112,6 +119,10 @@ protected:
virtual void focusOutEvent(QFocusEvent *ev) override;
virtual bool focusNextPrevChild(bool next) override;
virtual void paintEvent(QPaintEvent *e) override;
+#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
+ virtual
+#endif
+ void doSetSource(const QUrl &name, QTextDocument::ResourceType type = QTextDocument::UnknownResource);
private:
Q_DISABLE_COPY(QTextBrowser)
diff --git a/src/widgets/widgets/qtextedit.cpp b/src/widgets/widgets/qtextedit.cpp
index 2b3a46ae56..dd2ea3f18f 100644
--- a/src/widgets/widgets/qtextedit.cpp
+++ b/src/widgets/widgets/qtextedit.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -70,6 +70,7 @@
#include <qtextformat.h>
#include <qdatetime.h>
#include <qapplication.h>
+#include <private/qapplication_p.h>
#include <limits.h>
#include <qtexttable.h>
#include <qvariant.h>
@@ -167,6 +168,9 @@ void QTextEditPrivate::init(const QString &html)
QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));
QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));
QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(_q_cursorPositionChanged()));
+#if QT_CONFIG(cursor)
+ QObject::connect(control, SIGNAL(blockMarkerHovered(QTextBlock)), q, SLOT(_q_hoveredBlockWithMarkerChanged(QTextBlock)));
+#endif
QObject::connect(control, SIGNAL(textChanged()), q, SLOT(updateMicroFocus()));
@@ -187,6 +191,7 @@ void QTextEditPrivate::init(const QString &html)
vbar->setSingleStep(20);
viewport->setBackgroundRole(QPalette::Base);
+ q->setMouseTracking(true);
q->setAcceptDrops(true);
q->setFocusPolicy(Qt::StrongFocus);
q->setAttribute(Qt::WA_KeyCompression);
@@ -195,9 +200,6 @@ void QTextEditPrivate::init(const QString &html)
#ifndef QT_NO_CURSOR
viewport->setCursor(Qt::IBeamCursor);
#endif
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- setSingleFingerPanEnabled(true);
-#endif
}
void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect)
@@ -228,6 +230,23 @@ void QTextEditPrivate::_q_cursorPositionChanged()
#endif
}
+#if QT_CONFIG(cursor)
+void QTextEditPrivate::_q_hoveredBlockWithMarkerChanged(const QTextBlock &block)
+{
+ Q_Q(QTextEdit);
+ Qt::CursorShape cursor = cursorToRestoreAfterHover;
+ if (block.isValid() && !q->isReadOnly()) {
+ QTextBlockFormat::MarkerType marker = block.blockFormat().marker();
+ if (marker != QTextBlockFormat::MarkerType::NoMarker) {
+ if (viewport->cursor().shape() != Qt::PointingHandCursor)
+ cursorToRestoreAfterHover = viewport->cursor().shape();
+ cursor = Qt::PointingHandCursor;
+ }
+ }
+ viewport->setCursor(cursor);
+}
+#endif
+
void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode)
{
QTextCursor cursor = control->textCursor();
@@ -366,8 +385,8 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
\section1 Introduction and Concepts
QTextEdit is an advanced WYSIWYG viewer/editor supporting rich
- text formatting using HTML-style tags. It is optimized to handle
- large documents and to respond quickly to user input.
+ text formatting using HTML-style tags, or Markdown format. It is optimized
+ to handle large documents and to respond quickly to user input.
QTextEdit works on paragraphs and characters. A paragraph is a
formatted string which is word-wrapped to fit into the width of
@@ -381,7 +400,7 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
QTextEdit can display images, lists and tables. If the text is
too large to view within the text edit's viewport, scroll bars will
appear. The text edit can load both plain text and rich text files.
- Rich text is described using a subset of HTML 4 markup, refer to the
+ Rich text can be described using a subset of HTML 4 markup; refer to the
\l {Supported HTML Subset} page for more information.
If you just need to display a small piece of rich text use QLabel.
@@ -401,12 +420,19 @@ void QTextEditPrivate::_q_ensureVisible(const QRectF &_rect)
QTextEdit can display a large HTML subset, including tables and
images.
- The text is set or replaced using setHtml() which deletes any
+ The text can be set or replaced using \l setHtml() which deletes any
existing text and replaces it with the text passed in the
setHtml() call. If you call setHtml() with legacy HTML, and then
call toHtml(), the text that is returned may have different markup,
but will render the same. The entire text can be deleted with clear().
+ Text can also be set or replaced using \l setMarkdown(), and the same
+ caveats apply: if you then call \l toMarkdown(), the text that is returned
+ may be different, but the meaning is preserved as much as possible.
+ Markdown with some embedded HTML can be parsed, with the same limitations
+ that \l setHtml() has; but \l toMarkdown() only writes "pure" Markdown,
+ without any embedded HTML.
+
Text itself can be inserted using the QTextCursor class or using the
convenience functions insertHtml(), insertPlainText(), append() or
paste(). QTextCursor is also able to insert complex objects like tables
@@ -1089,7 +1115,7 @@ bool QTextEdit::event(QEvent *e)
#endif // QT_NO_CONTEXTMENU
#ifdef QT_KEYPAD_NAVIGATION
if (e->type() == QEvent::EnterEditFocus || e->type() == QEvent::LeaveEditFocus) {
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
d->sendControlEvent(e);
}
#endif
@@ -1214,6 +1240,56 @@ QString QTextEdit::toHtml() const
}
#endif
+#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
+/*!
+ \property QTextEdit::markdown
+
+ This property provides a Markdown interface to the text of the text edit.
+
+ \c toMarkdown() returns the text of the text edit as "pure" Markdown,
+ without any embedded HTML formatting. Some features that QTextDocument
+ supports (such as the use of specific colors and named fonts) cannot be
+ expressed in "pure" Markdown, and they will be omitted.
+
+ \c setMarkdown() changes the text of the text edit. Any previous text is
+ removed and the undo/redo history is cleared. The input text is
+ interpreted as rich text in Markdown format.
+
+ Parsing of HTML included in the \a markdown string is handled in the same
+ way as in \l setHtml; however, Markdown formatting inside HTML blocks is
+ not supported.
+
+ Some features of the parser can be enabled or disabled via the \a features
+ argument:
+
+ \value MarkdownNoHTML
+ Any HTML tags in the Markdown text will be discarded
+ \value MarkdownDialectCommonMark
+ The parser supports only the features standardized by CommonMark
+ \value MarkdownDialectGitHub
+ The parser supports the GitHub dialect
+
+ The default is \c MarkdownDialectGitHub.
+
+ \sa plainText, html, QTextDocument::toMarkdown(), QTextDocument::setMarkdown()
+*/
+#endif
+
+#if QT_CONFIG(textmarkdownreader)
+void QTextEdit::setMarkdown(const QString &markdown)
+{
+ Q_D(const QTextEdit);
+ d->control->setMarkdown(markdown);
+}
+#endif
+
+#if QT_CONFIG(textmarkdownwriter)
+QString QTextEdit::toMarkdown(QTextDocument::MarkdownFeatures features) const
+{
+ Q_D(const QTextEdit);
+ return d->control->toMarkdown(features);
+}
+#endif
/*! \reimp
*/
@@ -1224,7 +1300,7 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
#ifdef QT_KEYPAD_NAVIGATION
switch (e->key()) {
case Qt::Key_Select:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// code assumes linksaccessible + editable isn't meaningful
if (d->control->textInteractionFlags() & Qt::TextEditable) {
setEditFocus(!hasEditFocus());
@@ -1245,14 +1321,14 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Back:
case Qt::Key_No:
- if (!QApplication::keypadNavigationEnabled()
- || (QApplication::keypadNavigationEnabled() && !hasEditFocus())) {
+ if (!QApplicationPrivate::keypadNavigationEnabled()
+ || (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())) {
e->ignore();
return;
}
break;
default:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!hasEditFocus() && !(e->modifiers() & Qt::ControlModifier)) {
if (e->text()[0].isPrint())
setEditFocus(true);
@@ -1341,7 +1417,7 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
switch (e->key()) {
case Qt::Key_Up:
case Qt::Key_Down:
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
// Cursor position didn't change, so we want to leave
// these keys to change focus.
e->ignore();
@@ -1350,7 +1426,7 @@ void QTextEdit::keyPressEvent(QKeyEvent *e)
break;
case Qt::Key_Back:
if (!e->isAutoRepeat()) {
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (document()->isEmpty() || !(d->control->textInteractionFlags() & Qt::TextEditable)) {
setEditFocus(false);
e->accept();
@@ -1376,7 +1452,7 @@ void QTextEdit::keyReleaseEvent(QKeyEvent *e)
{
#ifdef QT_KEYPAD_NAVIGATION
Q_D(QTextEdit);
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (!e->isAutoRepeat() && e->key() == Qt::Key_Back
&& d->deleteAllTimer.isActive()) {
d->deleteAllTimer.stop();
@@ -1588,7 +1664,7 @@ void QTextEdit::mousePressEvent(QMouseEvent *e)
{
Q_D(QTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
- if (QApplication::keypadNavigationEnabled() && !hasEditFocus())
+ if (QApplicationPrivate::keypadNavigationEnabled() && !hasEditFocus())
setEditFocus(true);
#endif
d->sendControlEvent(e);
@@ -1719,7 +1795,7 @@ void QTextEdit::inputMethodEvent(QInputMethodEvent *e)
Q_D(QTextEdit);
#ifdef QT_KEYPAD_NAVIGATION
if (d->control->textInteractionFlags() & Qt::TextEditable
- && QApplication::keypadNavigationEnabled()
+ && QApplicationPrivate::keypadNavigationEnabled()
&& !hasEditFocus())
setEditFocus(true);
#endif
@@ -2187,7 +2263,7 @@ void QTextEdit::setReadOnly(bool ro)
d->control->setTextInteractionFlags(flags);
setAttribute(Qt::WA_InputMethodEnabled, shouldEnableInputMethod(this));
QEvent event(QEvent::ReadOnlyChange);
- QApplication::sendEvent(this, &event);
+ QCoreApplication::sendEvent(this, &event);
}
/*!
diff --git a/src/widgets/widgets/qtextedit.h b/src/widgets/widgets/qtextedit.h
index 3aa23aaace..5c8a3c7793 100644
--- a/src/widgets/widgets/qtextedit.h
+++ b/src/widgets/widgets/qtextedit.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -71,6 +71,9 @@ class Q_WIDGETS_EXPORT QTextEdit : public QAbstractScrollArea
QDOC_PROPERTY(QTextOption::WrapMode wordWrapMode READ wordWrapMode WRITE setWordWrapMode)
Q_PROPERTY(int lineWrapColumnOrWidth READ lineWrapColumnOrWidth WRITE setLineWrapColumnOrWidth)
Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly)
+#if QT_CONFIG(textmarkdownreader) && QT_CONFIG(textmarkdownwriter)
+ Q_PROPERTY(QString markdown READ toMarkdown WRITE setMarkdown NOTIFY textChanged)
+#endif
#ifndef QT_NO_TEXTHTMLPARSER
Q_PROPERTY(QString html READ toHtml WRITE setHtml NOTIFY textChanged USER true)
#endif
@@ -174,6 +177,9 @@ public:
#ifndef QT_NO_TEXTHTMLPARSER
QString toHtml() const;
#endif
+#if QT_CONFIG(textmarkdownwriter)
+ QString toMarkdown(QTextDocument::MarkdownFeatures features = QTextDocument::MarkdownDialectGitHub) const;
+#endif
void ensureCursorVisible();
@@ -238,6 +244,9 @@ public Q_SLOTS:
#ifndef QT_NO_TEXTHTMLPARSER
void setHtml(const QString &text);
#endif
+#if QT_CONFIG(textmarkdownreader)
+ void setMarkdown(const QString &markdown);
+#endif
void setText(const QString &text);
#ifndef QT_NO_CLIPBOARD
@@ -322,6 +331,9 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_adjustScrollbars())
Q_PRIVATE_SLOT(d_func(), void _q_ensureVisible(const QRectF &))
Q_PRIVATE_SLOT(d_func(), void _q_cursorPositionChanged())
+#if QT_CONFIG(cursor)
+ Q_PRIVATE_SLOT(d_func(), void _q_hoveredBlockWithMarkerChanged(const QTextBlock &))
+#endif
friend class QTextEditControl;
friend class QTextDocument;
friend class QWidgetTextControl;
diff --git a/src/widgets/widgets/qtextedit_p.h b/src/widgets/widgets/qtextedit_p.h
index c4ee75c78d..f7b4d15318 100644
--- a/src/widgets/widgets/qtextedit_p.h
+++ b/src/widgets/widgets/qtextedit_p.h
@@ -104,6 +104,7 @@ public:
void _q_currentCharFormatChanged(const QTextCharFormat &format);
void _q_cursorPositionChanged();
+ void _q_hoveredBlockWithMarkerChanged(const QTextBlock &block);
void updateDefaultTextOption();
@@ -136,6 +137,8 @@ public:
QString placeholderText;
+ Qt::CursorShape cursorToRestoreAfterHover = Qt::IBeamCursor;
+
#ifdef QT_KEYPAD_NAVIGATION
QBasicTimer deleteAllTimer;
#endif
diff --git a/src/widgets/widgets/qtoolbar.cpp b/src/widgets/widgets/qtoolbar.cpp
index bcf5a40ae3..58e9c4fd87 100644
--- a/src/widgets/widgets/qtoolbar.cpp
+++ b/src/widgets/widgets/qtoolbar.cpp
@@ -53,7 +53,6 @@
#if QT_CONFIG(rubberband)
#include <qrubberband.h>
#endif
-#include <qsignalmapper.h>
#include <qstylepainter.h>
#include <qstyleoption.h>
#include <qtoolbutton.h>
@@ -325,13 +324,8 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event)
event->y() >= 0 && event->y() < q->height());
startDrag(moving);
- if (!moving && !wasDragging) {
-#if 0 // Used to be included in Qt4 for Q_WS_WIN
- grabMouseWhileInWindow();
-#else
+ if (!moving && !wasDragging)
q->grabMouse();
-#endif
- }
}
if (state->dragging) {
@@ -1172,7 +1166,7 @@ bool QToolBar::event(QEvent *event)
// This is a workaround for loosing the mouse on Vista.
QPoint pos = QCursor::pos();
QMouseEvent fake(QEvent::MouseMove, mapFromGlobal(pos), pos, Qt::NoButton,
- QApplication::mouseButtons(), QApplication::keyboardModifiers());
+ QGuiApplication::mouseButtons(), QGuiApplication::keyboardModifiers());
d->mouseMoveEvent(&fake);
#endif
} else {
diff --git a/src/widgets/widgets/qtoolbar_p.h b/src/widgets/widgets/qtoolbar_p.h
index 4db75762c8..8cb5850903 100644
--- a/src/widgets/widgets/qtoolbar_p.h
+++ b/src/widgets/widgets/qtoolbar_p.h
@@ -73,7 +73,7 @@ public:
: explicitIconSize(false), explicitToolButtonStyle(false), movable(true), floatable(true),
allowedAreas(Qt::AllToolBarAreas), orientation(Qt::Horizontal),
toolButtonStyle(Qt::ToolButtonIconOnly),
- layout(0), state(0)
+ layout(nullptr), state(nullptr)
#ifdef Q_OS_OSX
, macWindowDragging(false)
#endif
diff --git a/src/widgets/widgets/qtoolbararealayout_p.h b/src/widgets/widgets/qtoolbararealayout_p.h
index 17747ef29b..5df95a3038 100644
--- a/src/widgets/widgets/qtoolbararealayout_p.h
+++ b/src/widgets/widgets/qtoolbararealayout_p.h
@@ -69,7 +69,7 @@ class QStyleOptionToolBar;
class QToolBarAreaLayoutItem
{
public:
- QToolBarAreaLayoutItem(QLayoutItem *item = 0)
+ QToolBarAreaLayoutItem(QLayoutItem *item = nullptr)
: widgetItem(item), pos(0), size(-1), preferredSize(-1), gap(false) {}
bool skip() const;
diff --git a/src/widgets/widgets/qtoolbarlayout_p.h b/src/widgets/widgets/qtoolbarlayout_p.h
index a788d30450..b5dc121b93 100644
--- a/src/widgets/widgets/qtoolbarlayout_p.h
+++ b/src/widgets/widgets/qtoolbarlayout_p.h
@@ -79,7 +79,7 @@ class QToolBarLayout : public QLayout
Q_OBJECT
public:
- QToolBarLayout(QWidget *parent = 0);
+ QToolBarLayout(QWidget *parent = nullptr);
~QToolBarLayout();
void addItem(QLayoutItem *item) override;
diff --git a/src/widgets/widgets/qtoolbox.cpp b/src/widgets/widgets/qtoolbox.cpp
index 1c83485bff..4d7f543a99 100644
--- a/src/widgets/widgets/qtoolbox.cpp
+++ b/src/widgets/widgets/qtoolbox.cpp
@@ -50,6 +50,8 @@
#include <qtooltip.h>
#include <qabstractbutton.h>
+#include <private/qmemory_p.h>
+
#include "qframe_p.h"
QT_BEGIN_NAMESPACE
@@ -106,7 +108,7 @@ public:
return widget == other.widget;
}
};
- typedef QList<Page> PageList;
+ typedef std::vector<std::unique_ptr<Page>> PageList;
inline QToolBoxPrivate()
: currentPage(0)
@@ -130,26 +132,27 @@ public:
const QToolBoxPrivate::Page *QToolBoxPrivate::page(const QObject *widget) const
{
if (!widget)
- return 0;
+ return nullptr;
- for (PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i)
- if ((*i).widget == widget)
- return (const Page*) &(*i);
- return 0;
+ for (const auto &page : pageList) {
+ if (page->widget == widget)
+ return page.get();
+ }
+ return nullptr;
}
QToolBoxPrivate::Page *QToolBoxPrivate::page(int index)
{
- if (index >= 0 && index < pageList.size())
- return &pageList[index];
- return 0;
+ if (index >= 0 && index < static_cast<int>(pageList.size()))
+ return pageList[index].get();
+ return nullptr;
}
const QToolBoxPrivate::Page *QToolBoxPrivate::page(int index) const
{
- if (index >= 0 && index < pageList.size())
- return &pageList.at(index);
- return 0;
+ if (index >= 0 && index < static_cast<int>(pageList.size()))
+ return pageList[index].get();
+ return nullptr;
}
void QToolBoxPrivate::updateTabs()
@@ -157,13 +160,12 @@ void QToolBoxPrivate::updateTabs()
QToolBoxButton *lastButton = currentPage ? currentPage->button : 0;
bool after = false;
int index = 0;
- for (index = 0; index < pageList.count(); ++index) {
- const Page &page = pageList.at(index);
- QToolBoxButton *tB = page.button;
+ for (const auto &page : pageList) {
+ QToolBoxButton *tB = page->button;
// update indexes, since the updates are delayed, the indexes will be correct
// when we actually paint.
tB->setIndex(index);
- QWidget *tW = page.widget;
+ QWidget *tW = page->widget;
if (after) {
QPalette p = tB->palette();
p.setColor(tB->backgroundRole(), tW->palette().color(tW->backgroundRole()));
@@ -174,6 +176,7 @@ void QToolBoxPrivate::updateTabs()
tB->update();
}
after = tB == lastButton;
+ ++index;
}
}
@@ -345,7 +348,8 @@ int QToolBox::insertItem(int index, QWidget *widget, const QIcon &icon, const QS
Q_D(QToolBox);
connect(widget, SIGNAL(destroyed(QObject*)), this, SLOT(_q_widgetDestroyed(QObject*)));
- QToolBoxPrivate::Page c;
+ auto newPage = qt_make_unique<QToolBoxPrivate::Page>();
+ auto &c = *newPage;
c.widget = widget;
c.button = new QToolBoxButton(this);
c.button->setObjectName(QLatin1String("qt_toolbox_toolboxbutton"));
@@ -360,15 +364,15 @@ int QToolBox::insertItem(int index, QWidget *widget, const QIcon &icon, const QS
c.setText(text);
c.setIcon(icon);
- if (index < 0 || index >= (int)d->pageList.count()) {
- index = d->pageList.count();
- d->pageList.append(c);
+ if (index < 0 || index >= static_cast<int>(d->pageList.size())) {
+ index = static_cast<int>(d->pageList.size());
+ d->pageList.push_back(std::move(newPage));
d->layout->addWidget(c.button);
d->layout->addWidget(c.sv);
if (index == 0)
setCurrentIndex(index);
} else {
- d->pageList.insert(index, c);
+ d->pageList.insert(d->pageList.cbegin() + index, std::move(newPage));
d->relayout();
if (d->currentPage) {
QWidget *current = d->currentPage->widget;
@@ -391,12 +395,13 @@ void QToolBoxPrivate::_q_buttonClicked()
{
Q_Q(QToolBox);
QToolBoxButton *tb = qobject_cast<QToolBoxButton*>(q->sender());
- QWidget* item = 0;
- for (QToolBoxPrivate::PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i)
- if ((*i).button == tb) {
- item = (*i).widget;
+ QWidget* item = nullptr;
+ for (const auto &page : pageList) {
+ if (page->button == tb) {
+ item = page->widget;
break;
}
+ }
q->setCurrentIndex(q->indexOf(item));
}
@@ -411,7 +416,7 @@ void QToolBoxPrivate::_q_buttonClicked()
int QToolBox::count() const
{
Q_D(const QToolBox);
- return d->pageList.count();
+ return static_cast<int>(d->pageList.size());
}
void QToolBox::setCurrentIndex(int index)
@@ -438,12 +443,18 @@ void QToolBoxPrivate::relayout()
delete layout;
layout = new QVBoxLayout(q);
layout->setContentsMargins(QMargins());
- for (QToolBoxPrivate::PageList::ConstIterator i = pageList.constBegin(); i != pageList.constEnd(); ++i) {
- layout->addWidget((*i).button);
- layout->addWidget((*i).sv);
+ for (const auto &page : pageList) {
+ layout->addWidget(page->button);
+ layout->addWidget(page->sv);
}
}
+auto pageEquals = [](const QToolBoxPrivate::Page *page) {
+ return [page](const std::unique_ptr<QToolBoxPrivate::Page> &ptr) {
+ return ptr.get() == page;
+ };
+};
+
void QToolBoxPrivate::_q_widgetDestroyed(QObject *object)
{
Q_Q(QToolBox);
@@ -458,9 +469,9 @@ void QToolBoxPrivate::_q_widgetDestroyed(QObject *object)
delete c->button;
bool removeCurrent = c == currentPage;
- pageList.removeAll(*c);
+ pageList.erase(std::remove_if(pageList.begin(), pageList.end(), pageEquals(c)), pageList.end());
- if (!pageList.count()) {
+ if (pageList.empty()) {
currentPage = 0;
emit q->currentChanged(-1);
} else if (removeCurrent) {
@@ -538,9 +549,9 @@ void QToolBox::setCurrentWidget(QWidget *widget)
QWidget *QToolBox::widget(int index) const
{
Q_D(const QToolBox);
- if (index < 0 || index >= (int) d->pageList.size())
+ if (index < 0 || index >= static_cast<int>(d->pageList.size()))
return nullptr;
- return d->pageList.at(index).widget;
+ return d->pageList[index]->widget;
}
/*!
@@ -552,7 +563,12 @@ int QToolBox::indexOf(QWidget *widget) const
{
Q_D(const QToolBox);
const QToolBoxPrivate::Page *c = (widget ? d->page(widget) : 0);
- return c ? d->pageList.indexOf(*c) : -1;
+ if (!c)
+ return -1;
+ const auto it = std::find_if(d->pageList.cbegin(), d->pageList.cend(), pageEquals(c));
+ if (it == d->pageList.cend())
+ return -1;
+ return static_cast<int>(it - d->pageList.cbegin());
}
/*!
@@ -571,7 +587,7 @@ void QToolBox::setItemEnabled(int index, bool enabled)
if (!enabled && c == d->currentPage) {
int curIndexUp = index;
int curIndexDown = curIndexUp;
- const int count = d->pageList.count();
+ const int count = static_cast<int>(d->pageList.size());
while (curIndexUp > 0 || curIndexDown < count-1) {
if (curIndexDown < count-1) {
if (d->page(++curIndexDown)->button->isEnabled()) {
diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp
index cf2d885b52..9cdae4f28f 100644
--- a/src/widgets/widgets/qwidgetlinecontrol.cpp
+++ b/src/widgets/widgets/qwidgetlinecontrol.cpp
@@ -54,6 +54,7 @@
#endif
#include "qapplication.h"
+#include "private/qapplication_p.h"
#if QT_CONFIG(graphicsview)
#include "qgraphicssceneevent.h"
#endif
@@ -77,11 +78,6 @@ int QWidgetLineControl::redoTextLayout() const
QTextLine l = m_textLayout.createLine();
m_textLayout.endLayout();
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (m_threadChecks)
- m_textLayoutThread = QThread::currentThread();
-#endif
-
return qRound(l.ascent());
}
@@ -158,7 +154,7 @@ void QWidgetLineControl::copy(QClipboard::Mode mode) const
{
QString t = selectedText();
if (!t.isEmpty() && m_echoMode == QLineEdit::Normal) {
- QApplication::clipboard()->setText(t, mode);
+ QGuiApplication::clipboard()->setText(t, mode);
}
}
@@ -172,7 +168,7 @@ void QWidgetLineControl::copy(QClipboard::Mode mode) const
*/
void QWidgetLineControl::paste(QClipboard::Mode clipboardMode)
{
- QString clip = QApplication::clipboard()->text(clipboardMode);
+ QString clip = QGuiApplication::clipboard()->text(clipboardMode);
if (!clip.isEmpty() || hasSelectedText()) {
separate(); //make it a separate undo/redo command
insert(clip);
@@ -1524,9 +1520,9 @@ void QWidgetLineControl::setBlinkingCursorEnabled(bool enable)
m_blinkEnabled = enable;
if (enable)
- connect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetLineControl::updateCursorBlinking);
+ connect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetLineControl::updateCursorBlinking);
else
- disconnect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetLineControl::updateCursorBlinking);
+ disconnect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetLineControl::updateCursorBlinking);
updateCursorBlinking();
}
@@ -1662,7 +1658,7 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
case Qt::Key_F4:
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Select:
- if (!QApplication::keypadNavigationEnabled())
+ if (!QApplicationPrivate::keypadNavigationEnabled())
break;
#endif
if (!m_completer->currentCompletion().isEmpty() && hasSelectedText()
@@ -1680,7 +1676,7 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
if (hasAcceptableInput() || fixup()) {
- QInputMethod *inputMethod = QApplication::inputMethod();
+ QInputMethod *inputMethod = QGuiApplication::inputMethod();
inputMethod->commit();
QWidget *lineEdit = qobject_cast<QWidget *>(parent());
if (!(lineEdit && lineEdit->inputMethodHints() & Qt::ImhMultiLine))
@@ -1912,7 +1908,7 @@ void QWidgetLineControl::processKeyEvent(QKeyEvent* event)
break;
#ifdef QT_KEYPAD_NAVIGATION
case Qt::Key_Back:
- if (QApplication::keypadNavigationEnabled() && !event->isAutoRepeat()
+ if (QApplicationPrivate::keypadNavigationEnabled() && !event->isAutoRepeat()
&& !isReadOnly()) {
if (text().length() == 0) {
setText(m_cancelText);
diff --git a/src/widgets/widgets/qwidgetlinecontrol_p.h b/src/widgets/widgets/qwidgetlinecontrol_p.h
index f4df95865d..8ebed25084 100644
--- a/src/widgets/widgets/qwidgetlinecontrol_p.h
+++ b/src/widgets/widgets/qwidgetlinecontrol_p.h
@@ -91,19 +91,15 @@ public:
m_dragEnabled(0), m_echoMode(0), m_textDirty(0), m_selDirty(0),
m_validInput(1), m_blinkStatus(0), m_blinkEnabled(false), m_blinkTimer(0), m_deleteAllTimer(0),
m_ascent(0), m_maxLength(32767), m_lastCursorPos(-1),
- m_tripleClickTimer(0), m_maskData(0), m_modifiedState(0), m_undoState(0),
+ m_tripleClickTimer(0), m_maskData(nullptr), m_modifiedState(0), m_undoState(0),
m_selstart(0), m_selend(0), m_passwordEchoEditing(false)
, m_passwordEchoTimer(0)
, m_passwordMaskDelay(-1)
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- , m_threadChecks(false)
- , m_textLayoutThread(0)
- #endif
#if defined(QT_BUILD_INTERNAL)
, m_passwordMaskDelayOverride(-1)
#endif
, m_keyboardScheme(0)
- , m_accessibleObject(0)
+ , m_accessibleObject(nullptr)
{
init(txt);
}
@@ -404,25 +400,9 @@ public:
QTextLayout *textLayout() const
{
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- if (m_threadChecks && QThread::currentThread() != m_textLayoutThread)
- redoTextLayout();
-#endif
return &m_textLayout;
}
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- void setThreadChecks(bool threadChecks)
- {
- m_threadChecks = threadChecks;
- }
-
- bool threadChecks() const
- {
- return m_threadChecks;
- }
-#endif
-
private:
void init(const QString &txt);
void removeSelectedText();
@@ -534,10 +514,6 @@ private:
}
int redoTextLayout() const;
-#if 0 // Used to be included in Qt4 for Q_WS_MAC
- bool m_threadChecks;
- mutable QThread *m_textLayoutThread;
-#endif
public:
#if defined(QT_BUILD_INTERNAL)
diff --git a/src/widgets/widgets/qwidgetresizehandler.cpp b/src/widgets/widgets/qwidgetresizehandler.cpp
index e8d435429f..9dbba12aba 100644
--- a/src/widgets/widgets/qwidgetresizehandler.cpp
+++ b/src/widgets/widgets/qwidgetresizehandler.cpp
@@ -124,21 +124,6 @@ bool QWidgetResizeHandler::eventFilter(QObject *o, QEvent *ee)
if (!widgetRect.contains(cursorPoint))
return false;
if (e->button() == Qt::LeftButton) {
-#if 0 // Used to be included in Qt4 for Q_WS_X11
- /*
- Implicit grabs do not stop the X server from changing
- the cursor in children, which looks *really* bad when
- doing resizingk, so we grab the cursor. Note that we do
- not do this on Windows since double clicks are lost due
- to the grab (see change 198463).
- */
- if (e->spontaneous())
-# if !defined(QT_NO_CURSOR)
- widget->grabMouse(widget->cursor());
-# else
- widget->grabMouse();
-# endif // QT_NO_CURSOR
-#endif
buttonDown = false;
emit activate();
bool me = movingEnabled;
diff --git a/src/widgets/widgets/qwidgetresizehandler_p.h b/src/widgets/widgets/qwidgetresizehandler_p.h
index 89bc759cc2..df3ac7cb8a 100644
--- a/src/widgets/widgets/qwidgetresizehandler_p.h
+++ b/src/widgets/widgets/qwidgetresizehandler_p.h
@@ -73,7 +73,7 @@ public:
Any = Move|Resize
};
- explicit QWidgetResizeHandler(QWidget *parent, QWidget *cw = 0);
+ explicit QWidgetResizeHandler(QWidget *parent, QWidget *cw = nullptr);
void setActive(bool b) { setActive(Any, b); }
void setActive(Action ac, bool b);
bool isActive() const { return isActive(Any); }
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index f86a747b0f..1c169c3325 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -55,6 +55,7 @@
#endif
#include <qstyle.h>
#include <qtimer.h>
+#include "private/qapplication_p.h"
#include "private/qtextdocumentlayout_p.h"
#include "private/qabstracttextdocumentlayout_p.h"
#include "qtextdocument.h"
@@ -97,7 +98,7 @@
#include <qkeysequence.h>
#define ACCEL_KEY(k) ((!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus) \
&& QGuiApplication::styleHints()->showShortcutsInContextMenus()) \
- && !qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? \
+ && !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ? \
QLatin1Char('\t') + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
#else
@@ -294,7 +295,7 @@ bool QWidgetTextControlPrivate::cursorMoveKeyEvent(QKeyEvent *e)
bool isNavigationEvent = e->key() == Qt::Key_Up || e->key() == Qt::Key_Down;
#ifdef QT_KEYPAD_NAVIGATION
- ignoreNavigationEvents = ignoreNavigationEvents || QApplication::keypadNavigationEnabled();
+ ignoreNavigationEvents = ignoreNavigationEvents || QApplicationPrivate::keypadNavigationEnabled();
isNavigationEvent = isNavigationEvent ||
(QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional
&& (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right));
@@ -494,6 +495,11 @@ void QWidgetTextControlPrivate::setContent(Qt::TextFormat format, const QString
formatCursor.select(QTextCursor::Document);
formatCursor.setCharFormat(charFormatForInsertion);
formatCursor.endEditBlock();
+#if QT_CONFIG(textmarkdownreader)
+ } else if (format == Qt::MarkdownText) {
+ doc->setMarkdown(text);
+ doc->setUndoRedoEnabled(false);
+#endif
} else {
#ifndef QT_NO_TEXTHTMLPARSER
doc->setHtml(text);
@@ -643,7 +649,7 @@ void QWidgetTextControlPrivate::_q_updateCurrentCharFormatAndSelection()
#ifndef QT_NO_CLIPBOARD
void QWidgetTextControlPrivate::setClipboardSelection()
{
- QClipboard *clipboard = QApplication::clipboard();
+ QClipboard *clipboard = QGuiApplication::clipboard();
if (!cursor.hasSelection() || !clipboard->supportsSelection())
return;
Q_Q(QWidgetTextControl);
@@ -714,9 +720,9 @@ void QWidgetTextControlPrivate::setCursorVisible(bool visible)
updateCursorBlinking();
if (cursorVisible)
- connect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
+ connect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
else
- disconnect(qApp->styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
+ disconnect(QGuiApplication::styleHints(), &QStyleHints::cursorFlashTimeChanged, this, &QWidgetTextControlPrivate::updateCursorBlinking);
}
void QWidgetTextControlPrivate::updateCursorBlinking()
@@ -954,12 +960,12 @@ void QWidgetTextControl::copy()
if (!d->cursor.hasSelection())
return;
QMimeData *data = createMimeDataFromSelection();
- QApplication::clipboard()->setMimeData(data);
+ QGuiApplication::clipboard()->setMimeData(data);
}
void QWidgetTextControl::paste(QClipboard::Mode mode)
{
- const QMimeData *md = QApplication::clipboard()->mimeData(mode);
+ const QMimeData *md = QGuiApplication::clipboard()->mimeData(mode);
if (md)
insertFromMimeData(md);
}
@@ -1154,7 +1160,7 @@ void QWidgetTextControl::processEvent(QEvent *e, const QMatrix &matrix, QWidget
#ifdef QT_KEYPAD_NAVIGATION
case QEvent::EnterEditFocus:
case QEvent::LeaveEditFocus:
- if (QApplication::keypadNavigationEnabled())
+ if (QApplicationPrivate::keypadNavigationEnabled())
d->editFocusEvent(e);
break;
#endif
@@ -1197,6 +1203,14 @@ void QWidgetTextControl::setPlainText(const QString &text)
d->setContent(Qt::PlainText, text);
}
+#if QT_CONFIG(textmarkdownreader)
+void QWidgetTextControl::setMarkdown(const QString &text)
+{
+ Q_D(QWidgetTextControl);
+ d->setContent(Qt::MarkdownText, text);
+}
+#endif
+
void QWidgetTextControl::setHtml(const QString &text)
{
Q_D(QWidgetTextControl);
@@ -1571,6 +1585,11 @@ void QWidgetTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton butto
e->ignore();
return;
}
+ bool wasValid = blockWithMarkerUnderMouse.isValid();
+ blockWithMarkerUnderMouse = q->blockWithMarkerAt(pos);
+ if (wasValid != blockWithMarkerUnderMouse.isValid())
+ emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
+
cursorIsFocusIndicator = false;
const QTextCursor oldSelection = cursor;
@@ -1589,6 +1608,8 @@ void QWidgetTextControlPrivate::mousePressEvent(QEvent *e, Qt::MouseButton butto
selectedBlockOnTrippleClick = cursor;
anchorOnMousePress = QString();
+ blockWithMarkerUnderMouse = QTextBlock();
+ emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
trippleClickTimer.stop();
} else {
@@ -1728,6 +1749,11 @@ void QWidgetTextControlPrivate::mouseMoveEvent(QEvent *e, Qt::MouseButton button
}
selectionChanged(true);
repaintOldAndNewSelection(oldSelection);
+ } else {
+ bool wasValid = blockWithMarkerUnderMouse.isValid();
+ blockWithMarkerUnderMouse = q->blockWithMarkerAt(mousePos);
+ if (wasValid != blockWithMarkerUnderMouse.isValid())
+ emit q->blockMarkerHovered(blockWithMarkerUnderMouse);
}
sendMouseEventToInputContext(e, QEvent::MouseMove, button, mousePos, modifiers, buttons, globalPos);
@@ -1762,9 +1788,9 @@ void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton but
selectionChanged(true);
} else if (button == Qt::MidButton
&& (interactionFlags & Qt::TextEditable)
- && QApplication::clipboard()->supportsSelection()) {
+ && QGuiApplication::clipboard()->supportsSelection()) {
setCursorPosition(pos);
- const QMimeData *md = QApplication::clipboard()->mimeData(QClipboard::Selection);
+ const QMimeData *md = QGuiApplication::clipboard()->mimeData(QClipboard::Selection);
if (md)
q->insertFromMimeData(md);
#endif
@@ -1777,6 +1803,26 @@ void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton but
emit q->microFocusChanged();
}
+ // toggle any checkbox that the user clicks
+ if ((interactionFlags & Qt::TextEditable) && (button & Qt::LeftButton) &&
+ (blockWithMarkerUnderMouse.isValid()) && !cursor.hasSelection()) {
+ QTextBlock markerBlock = q->blockWithMarkerAt(pos);
+ if (markerBlock == blockWithMarkerUnderMouse) {
+ auto fmt = blockWithMarkerUnderMouse.blockFormat();
+ switch (fmt.marker()) {
+ case QTextBlockFormat::MarkerType::Unchecked :
+ fmt.setMarker(QTextBlockFormat::MarkerType::Checked);
+ break;
+ case QTextBlockFormat::MarkerType::Checked:
+ fmt.setMarker(QTextBlockFormat::MarkerType::Unchecked);
+ break;
+ default:
+ break;
+ }
+ cursor.setBlockFormat(fmt);
+ }
+ }
+
if (interactionFlags & Qt::LinksAccessibleByMouse) {
if (!(button & Qt::LeftButton))
return;
@@ -2173,7 +2219,7 @@ void QWidgetTextControlPrivate::focusEvent(QFocusEvent *e)
emit q->updateRequest(q->selectionRect());
if (e->gotFocus()) {
#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason))) {
+ if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus && (e->reason() == Qt::PopupFocusReason))) {
#endif
cursorOn = (interactionFlags & (Qt::TextSelectableByKeyboard | Qt::TextEditable));
if (interactionFlags & Qt::TextEditable) {
@@ -2214,7 +2260,7 @@ void QWidgetTextControlPrivate::editFocusEvent(QEvent *e)
{
Q_Q(QWidgetTextControl);
- if (QApplication::keypadNavigationEnabled()) {
+ if (QApplicationPrivate::keypadNavigationEnabled()) {
if (e->type() == QEvent::EnterEditFocus && interactionFlags & Qt::TextEditable) {
const QTextCursor oldSelection = cursor;
const int oldCursorPos = cursor.position();
@@ -2316,6 +2362,7 @@ QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget
a = menu->addAction(tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll), this, SLOT(selectAll()));
a->setEnabled(!d->doc->isEmpty());
a->setObjectName(QStringLiteral("select-all"));
+ setActionIcon(a, QStringLiteral("edit-select-all"));
}
if ((d->interactionFlags & Qt::TextEditable) && QGuiApplication::styleHints()->useRtlExtensions()) {
@@ -2375,6 +2422,12 @@ QString QWidgetTextControl::anchorAtCursor() const
return d->anchorForCursor(d->cursor);
}
+QTextBlock QWidgetTextControl::blockWithMarkerAt(const QPointF &pos) const
+{
+ Q_D(const QWidgetTextControl);
+ return d->doc->documentLayout()->blockWithMarkerAt(pos);
+}
+
bool QWidgetTextControl::overwriteMode() const
{
Q_D(const QWidgetTextControl);
@@ -2428,10 +2481,10 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio
{
Q_D(QWidgetTextControl);
- QHash<int, int> hash;
+ QMultiHash<int, int> hash;
for (int i = 0; i < d->extraSelections.count(); ++i) {
const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i);
- hash.insertMulti(esel.cursor.anchor(), i);
+ hash.insert(esel.cursor.anchor(), i);
}
for (int i = 0; i < selections.count(); ++i) {
@@ -2547,7 +2600,7 @@ bool QWidgetTextControl::canPaste() const
#ifndef QT_NO_CLIPBOARD
Q_D(const QWidgetTextControl);
if (d->interactionFlags & Qt::TextEditable) {
- const QMimeData *md = QApplication::clipboard()->mimeData();
+ const QMimeData *md = QGuiApplication::clipboard()->mimeData();
return md && canInsertFromMimeData(md);
}
#endif
@@ -3124,6 +3177,13 @@ QString QWidgetTextControl::toHtml() const
}
#endif
+#if QT_CONFIG(textmarkdownwriter)
+QString QWidgetTextControl::toMarkdown(QTextDocument::MarkdownFeatures features) const
+{
+ return document()->toMarkdown(features);
+}
+#endif
+
void QWidgetTextControlPrivate::append(const QString &text, Qt::TextFormat format)
{
QTextCursor tmp(doc);
@@ -3222,7 +3282,7 @@ QAbstractTextDocumentLayout::PaintContext QWidgetTextControl::getPaintContext(QW
if (!d->dndFeedbackCursor.isNull())
ctx.cursorPosition = d->dndFeedbackCursor.position();
#ifdef QT_KEYPAD_NAVIGATION
- if (!QApplication::keypadNavigationEnabled() || d->hasEditFocus)
+ if (!QApplicationPrivate::keypadNavigationEnabled() || d->hasEditFocus)
#endif
if (d->cursor.hasSelection()) {
QAbstractTextDocumentLayout::Selection selection;
@@ -3273,7 +3333,7 @@ void QWidgetTextControlPrivate::_q_copyLink()
#ifndef QT_NO_CLIPBOARD
QMimeData *md = new QMimeData;
md->setText(linkToCopy);
- QApplication::clipboard()->setMimeData(md);
+ QGuiApplication::clipboard()->setMimeData(md);
#endif
}
diff --git a/src/widgets/widgets/qwidgettextcontrol_p.h b/src/widgets/widgets/qwidgettextcontrol_p.h
index 202ba36454..59bf5466e6 100644
--- a/src/widgets/widgets/qwidgettextcontrol_p.h
+++ b/src/widgets/widgets/qwidgettextcontrol_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -97,9 +97,9 @@ class Q_WIDGETS_EXPORT QWidgetTextControl : public QInputControl
Q_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
Q_PROPERTY(bool ignoreUnusedNavigationEvents READ ignoreUnusedNavigationEvents WRITE setIgnoreUnusedNavigationEvents)
public:
- explicit QWidgetTextControl(QObject *parent = 0);
- explicit QWidgetTextControl(const QString &text, QObject *parent = 0);
- explicit QWidgetTextControl(QTextDocument *doc, QObject *parent = 0);
+ explicit QWidgetTextControl(QObject *parent = nullptr);
+ explicit QWidgetTextControl(const QString &text, QObject *parent = nullptr);
+ explicit QWidgetTextControl(QTextDocument *doc, QObject *parent = nullptr);
virtual ~QWidgetTextControl();
void setDocument(QTextDocument *document);
@@ -116,18 +116,21 @@ public:
void setCurrentCharFormat(const QTextCharFormat &format);
QTextCharFormat currentCharFormat() const;
- bool find(const QString &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QString &exp, QTextDocument::FindFlags options = nullptr);
#ifndef QT_NO_REGEXP
- bool find(const QRegExp &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QRegExp &exp, QTextDocument::FindFlags options = nullptr);
#endif
#if QT_CONFIG(regularexpression)
- bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = 0);
+ bool find(const QRegularExpression &exp, QTextDocument::FindFlags options = nullptr);
#endif
QString toPlainText() const;
#ifndef QT_NO_TEXTHTMLPARSER
QString toHtml() const;
#endif
+#if QT_CONFIG(textmarkdownwriter)
+ QString toMarkdown(QTextDocument::MarkdownFeatures features = QTextDocument::MarkdownDialectGitHub) const;
+#endif
virtual void ensureCursorVisible();
@@ -147,6 +150,8 @@ public:
QString anchorAtCursor() const;
+ QTextBlock blockWithMarkerAt(const QPointF &pos) const;
+
bool overwriteMode() const;
void setOverwriteMode(bool overwrite);
@@ -194,6 +199,9 @@ public:
public Q_SLOTS:
void setPlainText(const QString &text);
+#if QT_CONFIG(textmarkdownreader)
+ void setMarkdown(const QString &text);
+#endif
void setHtml(const QString &text);
#ifndef QT_NO_CLIPBOARD
@@ -236,6 +244,7 @@ Q_SIGNALS:
void microFocusChanged();
void linkActivated(const QString &link);
void linkHovered(const QString &);
+ void blockMarkerHovered(const QTextBlock &block);
void modificationChanged(bool m);
public:
@@ -243,11 +252,11 @@ public:
QPalette palette() const;
void setPalette(const QPalette &pal);
- virtual void processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget = 0);
- void processEvent(QEvent *e, const QPointF &coordinateOffset = QPointF(), QWidget *contextWidget = 0);
+ virtual void processEvent(QEvent *e, const QMatrix &matrix, QWidget *contextWidget = nullptr);
+ void processEvent(QEvent *e, const QPointF &coordinateOffset = QPointF(), QWidget *contextWidget = nullptr);
// control methods
- void drawContents(QPainter *painter, const QRectF &rect = QRectF(), QWidget *widget = 0);
+ void drawContents(QPainter *painter, const QRectF &rect = QRectF(), QWidget *widget = nullptr);
void setFocus(bool focus, Qt::FocusReason = Qt::OtherFocusReason);
diff --git a/src/widgets/widgets/qwidgettextcontrol_p_p.h b/src/widgets/widgets/qwidgettextcontrol_p_p.h
index 232dab180f..c77a31bedf 100644
--- a/src/widgets/widgets/qwidgettextcontrol_p_p.h
+++ b/src/widgets/widgets/qwidgettextcontrol_p_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
@@ -55,6 +55,7 @@
#include "QtGui/qtextdocumentfragment.h"
#include "QtGui/qtextcursor.h"
#include "QtGui/qtextformat.h"
+#include "QtGui/qtextobject.h"
#if QT_CONFIG(menu)
#include "QtWidgets/qmenu.h"
#endif
@@ -89,9 +90,9 @@ public:
void createAutoBulletList();
void init(Qt::TextFormat format = Qt::RichText, const QString &text = QString(),
- QTextDocument *document = 0);
+ QTextDocument *document = nullptr);
void setContent(Qt::TextFormat format = Qt::RichText, const QString &text = QString(),
- QTextDocument *document = 0);
+ QTextDocument *document = nullptr);
void startDrag();
void paste(const QMimeData *source);
@@ -227,6 +228,7 @@ public:
QString highlightedAnchor; // Anchor below cursor
QString anchorOnMousePress;
+ QTextBlock blockWithMarkerUnderMouse;
bool hadSelectionOnMousePress;
bool ignoreUnusedNavigationEvents;