aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick
diff options
context:
space:
mode:
Diffstat (limited to 'src/quick')
-rw-r--r--src/quick/configure.json12
-rw-r--r--src/quick/designer/qqmldesignermetaobject.cpp4
-rw-r--r--src/quick/designer/qquickdesignercustomparserobject.cpp4
-rw-r--r--src/quick/designer/qquickdesignercustomparserobject_p.h4
-rw-r--r--src/quick/doc/images/9BcAYDlpuT8.jpgbin0 -> 8788 bytes
-rw-r--r--src/quick/doc/images/pointDistanceThreshold.pngbin8661 -> 0 bytes
-rw-r--r--src/quick/doc/images/pointerHandlerMargin.pngbin0 -> 11410 bytes
-rw-r--r--src/quick/doc/images/pointerHandlerMargin.svg (renamed from src/quick/doc/images/pointDistanceThreshold.svg)46
-rw-r--r--src/quick/doc/images/qml-item-canvas-lineDash.pngbin0 -> 6254 bytes
-rw-r--r--src/quick/doc/images/qtlabs-wavefrontmesh.pngbin0 -> 2881 bytes
-rw-r--r--src/quick/doc/qtquick.qdocconf4
-rw-r--r--src/quick/doc/snippets/pointerHandlers/dragHandler.qml3
-rw-r--r--src/quick/doc/snippets/pointerHandlers/dragHandlerDifferentTarget.qml9
-rw-r--r--src/quick/doc/snippets/pointerHandlers/dragHandlerNullTarget.qml11
-rw-r--r--src/quick/doc/snippets/pointerHandlers/pinchHandler.qml3
-rw-r--r--src/quick/doc/snippets/pointerHandlers/pinchHandlerDifferentTarget.qml3
-rw-r--r--src/quick/doc/snippets/pointerHandlers/pinchHandlerNullTarget.qml3
-rw-r--r--src/quick/doc/snippets/pointerHandlers/pointHandler.qml3
-rw-r--r--src/quick/doc/snippets/qml/mousearea/mousearea-snippet.qml4
-rw-r--r--src/quick/doc/snippets/qml/pathview/pathview.qml4
-rw-r--r--src/quick/doc/snippets/qml/rectangle/rectangle-gradient.qml12
-rw-r--r--src/quick/doc/snippets/qml/tableview/reusabledelegate.qml82
-rw-r--r--src/quick/doc/snippets/qml/tableview/tablemodel.cpp103
-rw-r--r--src/quick/doc/snippets/qml/tableview/tablemodel.qml (renamed from src/quick/doc/snippets/qml/models/visual-model-and-view.qml)33
-rw-r--r--src/quick/doc/snippets/qml/tableview/tableviewwithheader.qml64
-rw-r--r--src/quick/doc/snippets/qml/tableview/tableviewwithprovider.qml69
-rw-r--r--src/quick/doc/snippets/qml/transition-reversible.qml14
-rw-r--r--src/quick/doc/src/concepts/effects/particles.qdoc18
-rw-r--r--src/quick/doc/src/concepts/input/mouse.qdoc25
-rw-r--r--src/quick/doc/src/concepts/input/topic.qdoc30
-rw-r--r--src/quick/doc/src/concepts/inputhandlers/qtquickhandlers-index.qdoc (renamed from src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers-index.qdoc)41
-rw-r--r--src/quick/doc/src/concepts/layouts/qtquicklayouts.qdoc8
-rw-r--r--src/quick/doc/src/concepts/modelviewsdata/cppmodels.qdoc83
-rw-r--r--src/quick/doc/src/concepts/modelviewsdata/modelview.qdoc38
-rw-r--r--src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers.qdoc44
-rw-r--r--src/quick/doc/src/concepts/positioning/righttoleft.qdoc4
-rw-r--r--src/quick/doc/src/concepts/visualcanvas/scenegraph.qdoc8
-rw-r--r--src/quick/doc/src/guidelines/qtquick-bestpractices.qdoc16
-rw-r--r--src/quick/doc/src/qmltypereference.qdoc21
-rw-r--r--src/quick/handlers/handlers.pri11
-rw-r--r--src/quick/handlers/qquickdragaxis.cpp (renamed from src/quick/scenegraph/compressedtexture/qsgpkmhandler_p.h)51
-rw-r--r--src/quick/handlers/qquickdragaxis_p.h (renamed from src/quick/scenegraph/compressedtexture/qsgtexturefilehandler_p.h)50
-rw-r--r--src/quick/handlers/qquickdraghandler.cpp243
-rw-r--r--src/quick/handlers/qquickdraghandler_p.h53
-rw-r--r--src/quick/handlers/qquickhandlerpoint.cpp352
-rw-r--r--src/quick/handlers/qquickhandlerpoint_p.h121
-rw-r--r--src/quick/handlers/qquickhandlersmodule.cpp106
-rw-r--r--src/quick/handlers/qquickhoverhandler.cpp106
-rw-r--r--src/quick/handlers/qquickhoverhandler_p.h (renamed from src/quick/scenegraph/compressedtexture/qsgktxhandler_p.h)41
-rw-r--r--src/quick/handlers/qquickmultipointhandler.cpp198
-rw-r--r--src/quick/handlers/qquickmultipointhandler_p.h24
-rw-r--r--src/quick/handlers/qquickpinchhandler.cpp242
-rw-r--r--src/quick/handlers/qquickpinchhandler_p.h66
-rw-r--r--src/quick/handlers/qquickpointerdevicehandler.cpp112
-rw-r--r--src/quick/handlers/qquickpointerdevicehandler_p.h29
-rw-r--r--src/quick/handlers/qquickpointerdevicehandler_p_p.h75
-rw-r--r--src/quick/handlers/qquickpointerhandler.cpp243
-rw-r--r--src/quick/handlers/qquickpointerhandler_p.h44
-rw-r--r--src/quick/handlers/qquickpointerhandler_p_p.h84
-rw-r--r--src/quick/handlers/qquickpointhandler.cpp23
-rw-r--r--src/quick/handlers/qquickpointhandler_p.h3
-rw-r--r--src/quick/handlers/qquicksinglepointhandler.cpp327
-rw-r--r--src/quick/handlers/qquicksinglepointhandler_p.h71
-rw-r--r--src/quick/handlers/qquicktaphandler.cpp99
-rw-r--r--src/quick/handlers/qquicktaphandler_p.h25
-rw-r--r--src/quick/items/context2d/qquickcanvasitem.cpp2
-rw-r--r--src/quick/items/context2d/qquickcontext2d.cpp192
-rw-r--r--src/quick/items/context2d/qquickcontext2d_p.h5
-rw-r--r--src/quick/items/context2d/qquickcontext2dcommandbuffer.cpp26
-rw-r--r--src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h14
-rw-r--r--src/quick/items/items.pri10
-rw-r--r--src/quick/items/qquickanchors_p.h1
-rw-r--r--src/quick/items/qquickanimatedsprite.cpp11
-rw-r--r--src/quick/items/qquickanimatedsprite_p.h2
-rw-r--r--src/quick/items/qquickborderimage.cpp26
-rw-r--r--src/quick/items/qquickevents.cpp214
-rw-r--r--src/quick/items/qquickevents_p_p.h183
-rw-r--r--src/quick/items/qquickflickable.cpp104
-rw-r--r--src/quick/items/qquickflickable_p.h19
-rw-r--r--src/quick/items/qquickflickable_p_p.h2
-rw-r--r--src/quick/items/qquickgridview.cpp35
-rw-r--r--src/quick/items/qquickitem.cpp68
-rw-r--r--src/quick/items/qquickitem.h1
-rw-r--r--src/quick/items/qquickitem_p.h24
-rw-r--r--src/quick/items/qquickitemsmodule.cpp48
-rw-r--r--src/quick/items/qquickitemview.cpp115
-rw-r--r--src/quick/items/qquickitemview_p_p.h37
-rw-r--r--src/quick/items/qquickitemviewfxitem.cpp165
-rw-r--r--src/quick/items/qquickitemviewfxitem_p_p.h108
-rw-r--r--src/quick/items/qquickitemviewtransition.cpp2
-rw-r--r--src/quick/items/qquicklistview.cpp56
-rw-r--r--src/quick/items/qquickloader.cpp19
-rw-r--r--src/quick/items/qquickloader_p_p.h3
-rw-r--r--src/quick/items/qquickmultipointtoucharea.cpp3
-rw-r--r--src/quick/items/qquickmultipointtoucharea_p.h4
-rw-r--r--src/quick/items/qquickpainteditem.h1
-rw-r--r--src/quick/items/qquickpositioners.cpp24
-rw-r--r--src/quick/items/qquickrectangle.cpp121
-rw-r--r--src/quick/items/qquickrectangle_p.h17
-rw-r--r--src/quick/items/qquickrectangle_p_p.h2
-rw-r--r--src/quick/items/qquickrendercontrol.cpp9
-rw-r--r--src/quick/items/qquickscalegrid.cpp4
-rw-r--r--src/quick/items/qquickscalegrid_p_p.h12
-rw-r--r--src/quick/items/qquickscreen.cpp40
-rw-r--r--src/quick/items/qquickshadereffectmesh.cpp5
-rw-r--r--src/quick/items/qquickshadereffectmesh_p.h7
-rw-r--r--src/quick/items/qquickspriteengine_p.h2
-rw-r--r--src/quick/items/qquicktableview.cpp2034
-rw-r--r--src/quick/items/qquicktableview_p.h173
-rw-r--r--src/quick/items/qquicktableview_p_p.h388
-rw-r--r--src/quick/items/qquicktext.cpp51
-rw-r--r--src/quick/items/qquicktext_p.h12
-rw-r--r--src/quick/items/qquicktext_p_p.h1
-rw-r--r--src/quick/items/qquickwindow.cpp258
-rw-r--r--src/quick/items/qquickwindow.h1
-rw-r--r--src/quick/items/qquickwindow_p.h10
-rw-r--r--src/quick/qtquick2.cpp7
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer.cpp5
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer_p.h1
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwareadaptation.cpp2
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwareglyphnode.cpp34
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode.cpp12
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode_p.h2
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwarepublicnodes.cpp12
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwarerenderablenode_p.h4
-rw-r--r--src/quick/scenegraph/adaptations/software/qsgsoftwarerenderer.cpp4
-rw-r--r--src/quick/scenegraph/adaptations/software/software.pri13
-rw-r--r--src/quick/scenegraph/compressedtexture/qsgcompressedatlastexture.cpp14
-rw-r--r--src/quick/scenegraph/compressedtexture/qsgcompressedtexture.cpp79
-rw-r--r--src/quick/scenegraph/compressedtexture/qsgcompressedtexture_p.h31
-rw-r--r--src/quick/scenegraph/compressedtexture/qsgktxhandler.cpp186
-rw-r--r--src/quick/scenegraph/compressedtexture/qsgpkmhandler.cpp118
-rw-r--r--src/quick/scenegraph/coreapi/qsgabstractrenderer.h1
-rw-r--r--src/quick/scenegraph/qsgadaptationlayer.cpp27
-rw-r--r--src/quick/scenegraph/qsgadaptationlayer_p.h19
-rw-r--r--src/quick/scenegraph/qsgbasicinternalimagenode.cpp2
-rw-r--r--src/quick/scenegraph/qsgbasicinternalrectanglenode.cpp225
-rw-r--r--src/quick/scenegraph/qsgbasicinternalrectanglenode_p.h2
-rw-r--r--src/quick/scenegraph/qsgcontextplugin.cpp7
-rw-r--r--src/quick/scenegraph/qsgdefaultcontext.cpp7
-rw-r--r--src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp295
-rw-r--r--src/quick/scenegraph/qsgdefaultdistancefieldglyphcache_p.h4
-rw-r--r--src/quick/scenegraph/qsgdefaultrendercontext.cpp3
-rw-r--r--src/quick/scenegraph/qsgrenderloop.cpp2
-rw-r--r--src/quick/scenegraph/scenegraph.pri18
-rw-r--r--src/quick/scenegraph/util/qsgareaallocator.cpp144
-rw-r--r--src/quick/scenegraph/util/qsgareaallocator_p.h4
-rw-r--r--src/quick/scenegraph/util/qsgatlastexture.cpp25
-rw-r--r--src/quick/scenegraph/util/qsgdepthstencilbuffer.cpp25
-rw-r--r--src/quick/scenegraph/util/qsgengine.h1
-rw-r--r--src/quick/scenegraph/util/qsgtexture.cpp13
-rw-r--r--src/quick/scenegraph/util/qsgtexturereader.cpp61
-rw-r--r--src/quick/scenegraph/util/qsgtexturereader_p.h8
-rw-r--r--src/quick/util/qquickanimation.cpp22
-rw-r--r--src/quick/util/qquickanimation_p.h1
-rw-r--r--src/quick/util/qquickglobal.cpp2
-rw-r--r--src/quick/util/qquickimageprovider.cpp7
-rw-r--r--src/quick/util/qquickimageprovider.h6
-rw-r--r--src/quick/util/qquickimageprovider_p.h (renamed from src/quick/handlers/qquickhandlersmodule_p.h)18
-rw-r--r--src/quick/util/qquickpixmapcache.cpp19
-rw-r--r--src/quick/util/qquickprofiler.cpp3
-rw-r--r--src/quick/util/qquickprofiler_p.h2
-rw-r--r--src/quick/util/qquickpropertychanges.cpp38
-rw-r--r--src/quick/util/qquickpropertychanges_p.h6
-rw-r--r--src/quick/util/qquickstate.cpp2
-rw-r--r--src/quick/util/qquickstate_p_p.h4
-rw-r--r--src/quick/util/qquickstategroup.cpp9
-rw-r--r--src/quick/util/qquicksvgparser.cpp3
-rw-r--r--src/quick/util/qquicktransitionmanager.cpp59
-rw-r--r--src/quick/util/qquickutilmodule.cpp3
-rw-r--r--src/quick/util/util.pri1
171 files changed, 7200 insertions, 2722 deletions
diff --git a/src/quick/configure.json b/src/quick/configure.json
index 2c57c3318f..9ec3531ef4 100644
--- a/src/quick/configure.json
+++ b/src/quick/configure.json
@@ -15,6 +15,7 @@
"quick-flipable": "boolean",
"quick-gridview": "boolean",
"quick-listview": "boolean",
+ "quick-tableview": "boolean",
"quick-path": "boolean",
"quick-pathview": "boolean",
"quick-positioners": "boolean",
@@ -86,7 +87,7 @@
},
"quick-itemview": {
"label": "ItemView item",
- "condition": "features.quick-gridview || features.quick-listview",
+ "condition": "features.quick-gridview || features.quick-listview || features.quick-tableview",
"output": [
"privateFeature"
]
@@ -107,6 +108,14 @@
"privateFeature"
]
},
+ "quick-tableview": {
+ "label": "TableView item",
+ "purpose": "Provides the TableView item.",
+ "section": "Qt Quick",
+ "output": [
+ "privateFeature"
+ ]
+ },
"quick-particles": {
"label": "Particle support",
"purpose": "Provides a particle system.",
@@ -183,6 +192,7 @@
"quick-flipable",
"quick-gridview",
"quick-listview",
+ "quick-tableview",
"quick-path",
"quick-pathview",
"quick-positioners",
diff --git a/src/quick/designer/qqmldesignermetaobject.cpp b/src/quick/designer/qqmldesignermetaobject.cpp
index 09493c30d6..2efcdada8b 100644
--- a/src/quick/designer/qqmldesignermetaobject.cpp
+++ b/src/quick/designer/qqmldesignermetaobject.cpp
@@ -83,7 +83,7 @@ static QQmlPropertyCache *cacheForObject(QObject *object, QQmlEngine *engine)
{
QQmlVMEMetaObject *metaObject = QQmlVMEMetaObject::get(object);
if (metaObject)
- return metaObject->cache;
+ return metaObject->cache.data();
return QQmlEnginePrivate::get(engine)->cache(object);
}
@@ -139,7 +139,7 @@ QQmlDesignerMetaObject::QQmlDesignerMetaObject(QObject *object, QQmlEngine *engi
cache->setParent(ddata->propertyCache);
cache->invalidate(engine, this);
ddata->propertyCache->release();
- ddata->propertyCache = cache;
+ ddata->propertyCache = cache.data();
ddata->propertyCache->addref();
}
diff --git a/src/quick/designer/qquickdesignercustomparserobject.cpp b/src/quick/designer/qquickdesignercustomparserobject.cpp
index 9145b1367a..50a8b6a25b 100644
--- a/src/quick/designer/qquickdesignercustomparserobject.cpp
+++ b/src/quick/designer/qquickdesignercustomparserobject.cpp
@@ -46,12 +46,12 @@ QQuickDesignerCustomParserObject::QQuickDesignerCustomParserObject()
}
-void QQuickDesignerCustomParser::verifyBindings(const QV4::CompiledData::Unit *, const QList<const QV4::CompiledData::Binding *> &)
+void QQuickDesignerCustomParser::verifyBindings(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &, const QList<const QV4::CompiledData::Binding *> &)
{
/* Nothing to do we accept anything */
}
-void QQuickDesignerCustomParser::applyBindings(QObject *, QV4::CompiledData::CompilationUnit *, const QList<const QV4::CompiledData::Binding *> &)
+void QQuickDesignerCustomParser::applyBindings(QObject *, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &, const QList<const QV4::CompiledData::Binding *> &)
{
/* Nothing to do we accept anything */
}
diff --git a/src/quick/designer/qquickdesignercustomparserobject_p.h b/src/quick/designer/qquickdesignercustomparserobject_p.h
index e4d0765277..b38417d102 100644
--- a/src/quick/designer/qquickdesignercustomparserobject_p.h
+++ b/src/quick/designer/qquickdesignercustomparserobject_p.h
@@ -70,8 +70,8 @@ public:
QQuickDesignerCustomParser()
: QQmlCustomParser(AcceptsAttachedProperties | AcceptsSignalHandlers) {}
- void verifyBindings(const QV4::CompiledData::Unit *qmlUnit, const QList<const QV4::CompiledData::Binding *> &props) override;
- void applyBindings(QObject *obj, QV4::CompiledData::CompilationUnit *compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings) override;
+ void verifyBindings(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &props) override;
+ void applyBindings(QObject *obj, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings) override;
};
QT_END_NAMESPACE
diff --git a/src/quick/doc/images/9BcAYDlpuT8.jpg b/src/quick/doc/images/9BcAYDlpuT8.jpg
new file mode 100644
index 0000000000..0a69ab0034
--- /dev/null
+++ b/src/quick/doc/images/9BcAYDlpuT8.jpg
Binary files differ
diff --git a/src/quick/doc/images/pointDistanceThreshold.png b/src/quick/doc/images/pointDistanceThreshold.png
deleted file mode 100644
index c883f5f8a1..0000000000
--- a/src/quick/doc/images/pointDistanceThreshold.png
+++ /dev/null
Binary files differ
diff --git a/src/quick/doc/images/pointerHandlerMargin.png b/src/quick/doc/images/pointerHandlerMargin.png
new file mode 100644
index 0000000000..e996f57bf1
--- /dev/null
+++ b/src/quick/doc/images/pointerHandlerMargin.png
Binary files differ
diff --git a/src/quick/doc/images/pointDistanceThreshold.svg b/src/quick/doc/images/pointerHandlerMargin.svg
index 30d04e0df6..3e8b05f3f9 100644
--- a/src/quick/doc/images/pointDistanceThreshold.svg
+++ b/src/quick/doc/images/pointerHandlerMargin.svg
@@ -10,17 +10,17 @@
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
id="svg6318"
- inkscape:version="0.92.2 5c3e80d, 2017-08-06"
- viewBox="0 0 249.99999 100"
+ inkscape:version="0.92.2 2405546, 2018-03-11"
+ viewBox="0 0 148.46917 100.37263"
version="1.1"
- sodipodi:docname="pointDistanceThreshold.svg"
- width="250"
- height="100"
- inkscape:export-filename="/home/rutledge/dev/qt510/qtdeclarative/src/quick/doc/images/pointDistanceThreshold.png"
+ sodipodi:docname="pointerHandlerMargin.svg"
+ width="148.46918"
+ height="100.37263"
+ inkscape:export-filename="/home/rutledge/dev/qt5/qtdeclarative/src/quick/doc/images/pointerHandlerMargin.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<title
- id="title892">pointDistanceThreshold</title>
+ id="title892">pointerHandlerMargin</title>
<defs
id="defs20">
<marker
@@ -104,18 +104,18 @@
id="base"
bordercolor="#666666"
inkscape:pageshadow="2"
- inkscape:window-y="10"
+ inkscape:window-y="0"
pagecolor="#ffffff"
inkscape:zoom="2.1818696"
- inkscape:window-width="3025"
+ inkscape:window-width="1920"
inkscape:window-maximized="0"
- inkscape:window-x="275"
+ inkscape:window-x="0"
showgrid="false"
borderopacity="1.0"
inkscape:current-layer="layer1"
- inkscape:cx="-180.21887"
- inkscape:cy="-3.6626369"
- inkscape:window-height="2115"
+ inkscape:cx="-22.660169"
+ inkscape:cy="58.210886"
+ inkscape:window-height="1080"
inkscape:pageopacity="0.0"
inkscape:document-units="px"
fit-margin-top="0"
@@ -126,7 +126,7 @@
id="layer1"
inkscape:label="Camada 1"
inkscape:groupmode="layer"
- transform="translate(14.90473,-165.12199)">
+ transform="translate(-86.411864,-164.74934)">
<rect
style="opacity:1;fill:none;fill-opacity:1;stroke:#006eed;stroke-width:0.99999994;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect4231"
@@ -174,15 +174,15 @@
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-start:url(#marker1145)" />
<text
id="text1335"
- y="227.02623"
- x="-37.15416"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:12px;line-height:125%;font-family:Sans;-inkscape-font-specification:Sans;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+ y="226.88364"
+ x="104.81705"
+ style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:12px;line-height:125%;font-family:Sans;-inkscape-font-specification:'Sans, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:end;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:end;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
xml:space="preserve"
transform="rotate(-6.0579549)"><tspan
- y="227.02623"
- x="-37.15416"
- id="tspan1333"
- sodipodi:role="line">pointDistanceThreshold</tspan></text>
+ y="226.88364"
+ x="104.81705"
+ sodipodi:role="line"
+ id="tspan862">margin</tspan></text>
</g>
<metadata
id="metadata19">
@@ -196,10 +196,10 @@
<dc:publisher>
<cc:Agent
rdf:about="http://openclipart.org/">
- <dc:title></dc:title>
+ <dc:title />
</cc:Agent>
</dc:publisher>
- <dc:title>pointDistanceThreshold</dc:title>
+ <dc:title>pointerHandlerMargin</dc:title>
<dc:creator>
<cc:Agent>
<dc:title>The Qt Company</dc:title>
diff --git a/src/quick/doc/images/qml-item-canvas-lineDash.png b/src/quick/doc/images/qml-item-canvas-lineDash.png
new file mode 100644
index 0000000000..a2a038abe0
--- /dev/null
+++ b/src/quick/doc/images/qml-item-canvas-lineDash.png
Binary files differ
diff --git a/src/quick/doc/images/qtlabs-wavefrontmesh.png b/src/quick/doc/images/qtlabs-wavefrontmesh.png
new file mode 100644
index 0000000000..e8ec3642fa
--- /dev/null
+++ b/src/quick/doc/images/qtlabs-wavefrontmesh.png
Binary files differ
diff --git a/src/quick/doc/qtquick.qdocconf b/src/quick/doc/qtquick.qdocconf
index ad5e47002d..34ec66bf1d 100644
--- a/src/quick/doc/qtquick.qdocconf
+++ b/src/quick/doc/qtquick.qdocconf
@@ -89,3 +89,7 @@ navigation.qmltypespage = "Qt Quick QML Types"
# \svgcolor {#ffdead}
macro.svgcolor.HTML = "<div style=\"padding:10px;color:#fff;background:\1;\"></div>"
+
+# youtube video thumbnails that show up in offline and online docs
+HTML.extraimages += images/9BcAYDlpuT8.jpg
+qhp.QtQuick.extraFiles += images/9BcAYDlpuT8.jpg
diff --git a/src/quick/doc/snippets/pointerHandlers/dragHandler.qml b/src/quick/doc/snippets/pointerHandlers/dragHandler.qml
index 78a7db5b0c..04ea3967a0 100644
--- a/src/quick/doc/snippets/pointerHandlers/dragHandler.qml
+++ b/src/quick/doc/snippets/pointerHandlers/dragHandler.qml
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.10
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Rectangle {
width: 100
diff --git a/src/quick/doc/snippets/pointerHandlers/dragHandlerDifferentTarget.qml b/src/quick/doc/snippets/pointerHandlers/dragHandlerDifferentTarget.qml
index 4c4168de83..7e7662539f 100644
--- a/src/quick/doc/snippets/pointerHandlers/dragHandlerDifferentTarget.qml
+++ b/src/quick/doc/snippets/pointerHandlers/dragHandlerDifferentTarget.qml
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.10
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Item {
width: 640
@@ -58,8 +57,8 @@ Item {
Rectangle {
id: feedback
border.color: "red"
- width: Math.max(10, handler.point.ellipseDiameters.width)
- height: Math.max(10, handler.point.ellipseDiameters.height)
+ width: Math.max(10, handler.centroid.ellipseDiameters.width)
+ height: Math.max(10, handler.centroid.ellipseDiameters.height)
radius: Math.max(width, height) / 2
visible: handler.active
}
diff --git a/src/quick/doc/snippets/pointerHandlers/dragHandlerNullTarget.qml b/src/quick/doc/snippets/pointerHandlers/dragHandlerNullTarget.qml
index 09429ec1d2..c33f2b2782 100644
--- a/src/quick/doc/snippets/pointerHandlers/dragHandlerNullTarget.qml
+++ b/src/quick/doc/snippets/pointerHandlers/dragHandlerNullTarget.qml
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.10
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Item {
width: 640
@@ -62,9 +61,9 @@ Item {
Text {
color: handler.active ? "darkgreen" : "black"
- text: handler.point.position.x.toFixed(1) + "," + handler.point.position.y.toFixed(1)
- x: handler.point.position.x - width / 2
- y: handler.point.position.y - height
+ text: handler.centroid.centroid.x.toFixed(1) + "," + handler.centroid.position.y.toFixed(1)
+ x: handler.centroid.position.x - width / 2
+ y: handler.centroid.position.y - height
}
}
//![0]
diff --git a/src/quick/doc/snippets/pointerHandlers/pinchHandler.qml b/src/quick/doc/snippets/pointerHandlers/pinchHandler.qml
index 955047d115..dd0542a953 100644
--- a/src/quick/doc/snippets/pointerHandlers/pinchHandler.qml
+++ b/src/quick/doc/snippets/pointerHandlers/pinchHandler.qml
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.8
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Rectangle {
width: 400
diff --git a/src/quick/doc/snippets/pointerHandlers/pinchHandlerDifferentTarget.qml b/src/quick/doc/snippets/pointerHandlers/pinchHandlerDifferentTarget.qml
index a5255a64e3..b071e294af 100644
--- a/src/quick/doc/snippets/pointerHandlers/pinchHandlerDifferentTarget.qml
+++ b/src/quick/doc/snippets/pointerHandlers/pinchHandlerDifferentTarget.qml
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.8
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Item {
width: 640
diff --git a/src/quick/doc/snippets/pointerHandlers/pinchHandlerNullTarget.qml b/src/quick/doc/snippets/pointerHandlers/pinchHandlerNullTarget.qml
index 7d21efcb84..ade59d29f0 100644
--- a/src/quick/doc/snippets/pointerHandlers/pinchHandlerNullTarget.qml
+++ b/src/quick/doc/snippets/pointerHandlers/pinchHandlerNullTarget.qml
@@ -48,8 +48,7 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.8
-import Qt.labs.handlers 1.0
+import QtQuick 2.12
Item {
width: 640
diff --git a/src/quick/doc/snippets/pointerHandlers/pointHandler.qml b/src/quick/doc/snippets/pointerHandlers/pointHandler.qml
index 262eb607b6..20be120120 100644
--- a/src/quick/doc/snippets/pointerHandlers/pointHandler.qml
+++ b/src/quick/doc/snippets/pointerHandlers/pointHandler.qml
@@ -48,9 +48,8 @@
**
****************************************************************************/
//![0]
-import QtQuick 2.10
+import QtQuick 2.12
import QtQuick.Window 2.2
-import Qt.labs.handlers 1.0
Window {
width: 480
diff --git a/src/quick/doc/snippets/qml/mousearea/mousearea-snippet.qml b/src/quick/doc/snippets/qml/mousearea/mousearea-snippet.qml
index 0306c2de0f..13ef779d08 100644
--- a/src/quick/doc/snippets/qml/mousearea/mousearea-snippet.qml
+++ b/src/quick/doc/snippets/qml/mousearea/mousearea-snippet.qml
@@ -90,7 +90,7 @@ Rectangle {
Rectangle {
width: 100; height: 100
- //! [mouse handlers]
+ //! [signal handlers]
MouseArea {
anchors.fill: parent
onClicked: console.log("area clicked")
@@ -98,7 +98,7 @@ Rectangle {
onEntered: console.log("mouse entered the area")
onExited: console.log("mouse left the area")
}
- //! [mouse handlers]
+ //! [signal handlers]
}
} //end of column
diff --git a/src/quick/doc/snippets/qml/pathview/pathview.qml b/src/quick/doc/snippets/qml/pathview/pathview.qml
index 1a31f1372b..58d19b1a0c 100644
--- a/src/quick/doc/snippets/qml/pathview/pathview.qml
+++ b/src/quick/doc/snippets/qml/pathview/pathview.qml
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -59,6 +59,7 @@ Rectangle {
id: delegate
Column {
id: wrapper
+ opacity: PathView.isCurrentItem ? 1 : 0.5
Image {
anchors.horizontalCenter: nameText.horizontalCenter
width: 64; height: 64
@@ -68,7 +69,6 @@ Rectangle {
id: nameText
text: name
font.pointSize: 16
- color: wrapper.PathView.isCurrentItem ? "red" : "black"
}
}
}
diff --git a/src/quick/doc/snippets/qml/rectangle/rectangle-gradient.qml b/src/quick/doc/snippets/qml/rectangle/rectangle-gradient.qml
index 031bee960d..e52a0ce0ef 100644
--- a/src/quick/doc/snippets/qml/rectangle/rectangle-gradient.qml
+++ b/src/quick/doc/snippets/qml/rectangle/rectangle-gradient.qml
@@ -80,5 +80,17 @@ Rectangle {
}
}
//! [rectangles]
+
+//! [presets]
+Rectangle {
+ y: 0; width: 80; height: 80
+ gradient: Gradient.NightFade
+}
+
+Rectangle {
+ y: 0; width: 80; height: 80
+ gradient: "NightFade"
+}
+//! [presets]
}
}
diff --git a/src/quick/doc/snippets/qml/tableview/reusabledelegate.qml b/src/quick/doc/snippets/qml/tableview/reusabledelegate.qml
new file mode 100644
index 0000000000..4a49e809cc
--- /dev/null
+++ b/src/quick/doc/snippets/qml/tableview/reusabledelegate.qml
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** 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.
+**
+** BSD License Usage
+** Alternatively, you may use this file under the terms of the BSD license
+** as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in
+** the documentation and/or other materials provided with the
+** distribution.
+** * Neither the name of The Qt Company Ltd nor the names of its
+** contributors may be used to endorse or promote products derived
+** from this software without specific prior written permission.
+**
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+import QtQuick 2.12
+
+//![0]
+Component {
+ id: tableViewDelegate
+ Rectangle {
+ implicitWidth: 100
+ implicitHeight: 50
+
+ TableView.onPooled: rotationAnimation.pause()
+ TableView.onReused: rotationAnimation.resume()
+
+ Rectangle {
+ id: rect
+ anchors.centerIn: parent
+ width: 40
+ height: 5
+ color: "green"
+
+ RotationAnimation {
+ id: rotationAnimation
+ target: rect
+ duration: (Math.random() * 2000) + 200
+ from: 0
+ to: 359
+ running: true
+ loops: Animation.Infinite
+ }
+ }
+ }
+}
+//![0]
diff --git a/src/quick/doc/snippets/qml/tableview/tablemodel.cpp b/src/quick/doc/snippets/qml/tableview/tablemodel.cpp
new file mode 100644
index 0000000000..ea9f76f131
--- /dev/null
+++ b/src/quick/doc/snippets/qml/tableview/tablemodel.cpp
@@ -0,0 +1,103 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2018 The Qt Company Ltd.
+ ** Contact: https://www.qt.io/licensing/
+ **
+ ** This file is part of the documentation of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:BSD$
+ ** 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.
+ **
+ ** BSD License Usage
+ ** Alternatively, you may use this file under the terms of the BSD license
+ ** as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * Redistributions in binary form must reproduce the above copyright
+ ** notice, this list of conditions and the following disclaimer in
+ ** the documentation and/or other materials provided with the
+ ** distribution.
+ ** * Neither the name of The Qt Company Ltd nor the names of its
+ ** contributors may be used to endorse or promote products derived
+ ** from this software without specific prior written permission.
+ **
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+//![0]
+#include <QGuiApplication>
+#include <QQmlApplicationEngine>
+#include <QAbstractTableModel>
+
+class TableModel : public QAbstractTableModel
+{
+ Q_OBJECT
+
+public:
+
+ int rowCount(const QModelIndex & = QModelIndex()) const override
+ {
+ return 200;
+ }
+
+ int columnCount(const QModelIndex & = QModelIndex()) const override
+ {
+ return 200;
+ }
+
+ QVariant data(const QModelIndex &index, int role) const override
+ {
+ switch (role) {
+ case Qt::DisplayRole:
+ return QString("%1, %2").arg(index.column()).arg(index.row());
+ default:
+ break;
+ }
+
+ return QVariant();
+ }
+
+ QHash<int, QByteArray> roleNames() const override
+ {
+ return { {Qt::DisplayRole, "display"} };
+ }
+};
+
+int main(int argc, char *argv[])
+{
+ QGuiApplication app(argc, argv);
+
+ qmlRegisterType<TableModel>("TableModel", 0, 1, "TableModel");
+
+ QQmlApplicationEngine engine;
+ engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
+
+ return app.exec();
+}
+
+#include "main.moc"
+//![0]
diff --git a/src/quick/doc/snippets/qml/models/visual-model-and-view.qml b/src/quick/doc/snippets/qml/tableview/tablemodel.qml
index baf489f8b9..8a8ec94958 100644
--- a/src/quick/doc/snippets/qml/models/visual-model-and-view.qml
+++ b/src/quick/doc/snippets/qml/tableview/tablemodel.qml
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -47,22 +47,25 @@
** $QT_END_LICENSE$
**
****************************************************************************/
-import QtQuick 2.0
-Rectangle {
- width: 200; height: 200
+//![0]
+import QtQuick 2.12
+import TableModel 0.1
- //! [visual model and view]
- VisualItemModel {
- id: itemModel
- Rectangle { height: 30; width: 80; color: "red" }
- Rectangle { height: 30; width: 80; color: "green" }
- Rectangle { height: 30; width: 80; color: "blue" }
- }
+TableView {
+ anchors.fill: parent
+ columnSpacing: 1
+ rowSpacing: 1
+ clip: true
+
+ model: TableModel {}
- ListView {
- anchors.fill: parent
- model: itemModel
+ delegate: Rectangle {
+ implicitWidth: 100
+ implicitHeight: 50
+ Text {
+ text: display
+ }
}
- //! [visual model and view]
}
+//![0]
diff --git a/src/quick/doc/snippets/qml/tableview/tableviewwithheader.qml b/src/quick/doc/snippets/qml/tableview/tableviewwithheader.qml
new file mode 100644
index 0000000000..2214328ee7
--- /dev/null
+++ b/src/quick/doc/snippets/qml/tableview/tableviewwithheader.qml
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** 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.
+**
+** BSD License Usage
+** Alternatively, you may use this file under the terms of the BSD license
+** as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in
+** the documentation and/or other materials provided with the
+** distribution.
+** * Neither the name of The Qt Company Ltd nor the names of its
+** contributors may be used to endorse or promote products derived
+** from this software without specific prior written permission.
+**
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+import QtQuick 2.12
+
+//![0]
+TableView {
+ id: tableView
+
+ topMargin: header.implicitHeight
+
+ Text {
+ id: header
+ text: "A table header"
+ }
+}
+//![0]
diff --git a/src/quick/doc/snippets/qml/tableview/tableviewwithprovider.qml b/src/quick/doc/snippets/qml/tableview/tableviewwithprovider.qml
new file mode 100644
index 0000000000..028b12ca6c
--- /dev/null
+++ b/src/quick/doc/snippets/qml/tableview/tableviewwithprovider.qml
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the documentation of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** 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.
+**
+** BSD License Usage
+** Alternatively, you may use this file under the terms of the BSD license
+** as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * Redistributions in binary form must reproduce the above copyright
+** notice, this list of conditions and the following disclaimer in
+** the documentation and/or other materials provided with the
+** distribution.
+** * Neither the name of The Qt Company Ltd nor the names of its
+** contributors may be used to endorse or promote products derived
+** from this software without specific prior written permission.
+**
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+import QtQuick 2.12
+
+//![0]
+TableView {
+ id: tableView
+
+ property var columnWidths: [100, 50, 80, 150]
+ columnWidthProvider: function (column) { return columnWidths[column] }
+
+ Timer {
+ running: true
+ interval: 2000
+ onTriggered: {
+ tableView.columnWidths[2] = 150
+ tableView.forceLayout();
+ }
+ }
+}
+//![0]
diff --git a/src/quick/doc/snippets/qml/transition-reversible.qml b/src/quick/doc/snippets/qml/transition-reversible.qml
index 58a88621c4..f74b6bffb3 100644
--- a/src/quick/doc/snippets/qml/transition-reversible.qml
+++ b/src/quick/doc/snippets/qml/transition-reversible.qml
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -47,24 +47,26 @@
** $QT_END_LICENSE$
**
****************************************************************************/
-import QtQuick 2.0
+import QtQuick 2.12
//![0]
Rectangle {
id: rect
width: 100; height: 100
- color: "red"
+ color: "steelblue"
- MouseArea { id: mouseArea; anchors.fill: parent }
+ TapHandler { id: tapHandler }
states: State {
name: "brighter"
- when: mouseArea.pressed
- PropertyChanges { target: rect; color: "yellow"; x: 50 }
+ when: tapHandler.pressed
+ PropertyChanges { target: rect; color: "lightsteelblue"; x: 50 }
}
//! [sequential animations]
transitions: Transition {
+ to: "brighter"
+ reversible: true
SequentialAnimation {
PropertyAnimation { property: "x"; duration: 1000 }
ColorAnimation { duration: 1000 }
diff --git a/src/quick/doc/src/concepts/effects/particles.qdoc b/src/quick/doc/src/concepts/effects/particles.qdoc
index 59f9c0db83..0b87eb4529 100644
--- a/src/quick/doc/src/concepts/effects/particles.qdoc
+++ b/src/quick/doc/src/concepts/effects/particles.qdoc
@@ -26,15 +26,16 @@
****************************************************************************/
/*!
- \qmlmodule QtQuick.Particles 2.11
+ \qmlmodule QtQuick.Particles 2.\QtMinorVersion
\title Qt Quick Particles QML Types
\ingroup qmlmodules
\brief Provides QML types for particle effects
This QML module contains a particle system for Qt Quick. To use these types, import the module with the following line:
- \code
- import QtQuick.Particles 2.11
- \endcode
+
+ \qml \QtMinorVersion
+ import QtQuick.Particles 2.\1
+ \endqml
For a simple overview of how the system can be used, see \l{Using the Qt Quick Particle System}.
@@ -48,10 +49,11 @@
Documentation for all Particle System types can be found on the \l QtQuick.Particles module page.
- Note that to use types from the particles module, you will need to import the types with the following line:
- \code
- import QtQuick.Particles 2.11
- \endcode
+ To use the types from the particles module, import the module with the following line:
+
+ \qml \QtMinorVersion
+ import QtQuick.Particles 2.\1
+ \endqml
\section1 The ParticleSystem
This particle system contains four main types of QML types: ParticleSystem, Painters, Emitters and Affectors.
diff --git a/src/quick/doc/src/concepts/input/mouse.qdoc b/src/quick/doc/src/concepts/input/mouse.qdoc
index 422c326898..cb506cb99a 100644
--- a/src/quick/doc/src/concepts/input/mouse.qdoc
+++ b/src/quick/doc/src/concepts/input/mouse.qdoc
@@ -33,6 +33,13 @@
\tableofcontents
+A more modern way of handling events from all pointing devices, including
+mouse and touchscreen, is via \l {Qt Quick Input Handlers}{Input Handlers}.
+This page describes the original Qt Quick \l MouseArea type, which was
+initially designed to handle mouse input, and later began handling single-touch
+events (in the form of synthetic mouse events) in simple touch-oriented user
+interfaces.
+
\section1 Mouse Types
\list
@@ -44,8 +51,8 @@
QML uses \l{qtqml-syntax-signals.html}{signals and handlers} to
deliver mouse interactions. Specifically, Qt Quick provides the \l MouseArea
-and \l MouseEvent types which allow developers to define signal handlers which
-accept mouse events within a defined area.
+and \l MouseEvent types that allow developers to define JavaScript callbacks
+(also called signal handlers), which accept mouse events within a defined area.
\section1 Defining a Mouse Area
@@ -59,8 +66,8 @@ definable.
\section1 Receiving Events
-The MouseArea type provides
-\l{qtqml-syntax-signals.html}{signals and handlers} to detect different
+The MouseArea type emits
+\l{qtqml-syntax-signals.html}{signals} in response to different
mouse events. The \l MouseArea type documentation describes these
gestures in greater detail:
@@ -76,8 +83,8 @@ gestures in greater detail:
\li released
\endlist
-These signals have signal handlers that are invoked when the signals are emitted.
-\snippet qml/mousearea/mousearea-snippet.qml mouse handlers
+These signals can have callbacks that are invoked when the signals are emitted.
+\snippet qml/mousearea/mousearea-snippet.qml signal handlers
\section1 Enabling Gestures
Some mouse gestures and button clicks need to be enabled before they send or
@@ -101,9 +108,9 @@ Additionally, to disable the whole mouse area, set the MouseArea
\section1 MouseEvent Object
-Signals and their handlers receive a \l MouseEvent object as a parameter. The
-\c mouse object contain information about the mouse event. For example, the
-mouse button that started the event is queried through the
+Signals and their callbacks receive a \l MouseEvent object as a parameter.
+The \c mouse object contains information about the mouse event. For example,
+the mouse button that started the event is queried through the
\l {MouseEvent::button}{mouse.button} property.
The \c MouseEvent object can also ignore a mouse event using its \c accepted
diff --git a/src/quick/doc/src/concepts/input/topic.qdoc b/src/quick/doc/src/concepts/input/topic.qdoc
index c23654cadb..95f4732f46 100644
--- a/src/quick/doc/src/concepts/input/topic.qdoc
+++ b/src/quick/doc/src/concepts/input/topic.qdoc
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -35,30 +35,20 @@ design. Depending on the use-case that an application solves, and the
form-factor of the device that the application runs on, the best way
to receive user-input may be different.
-\section1 Touch
+\section1 Input from Pointing Devices
Allowing users to physically touch a screen to interact with an application is
a popular user-interface paradigm on portable devices like smartphones and
-tablets.
+tablets. In desktop applications, detecting and reacting to clicks and presses
+according to the mouse cursor position is a fundamental concept in
+user-interface design.
-Qt Quick was designed specifically with touch-driven user-interfaces in mind,
-and thus touch events are supported in various visual object types, from
-\l{Flickable} lists to the generic \l{MultiPointTouchArea} type, as well as
-in the \l{MouseArea} type (which will be documented thoroughly in a proceeding
-section).
+Touch-driven and mouse-driven user interfaces are supported by various
+\l{Qt Quick Input Handlers}{input handler} types, and visual object types
+such as \l{Flickable} and \l{MouseArea}.
-
-\section1 Mouse
-
-Mouse input is another important user input for user interfaces. Detecting
-and reacting to clicks and presses according to the mouse cursor position is a fundamental
-concept in user-interface design.
-
-Qt Quick provides the MouseArea visual object type which automatically receives
-mouse events (including clicks and wheel events) which allows developers to
-create custom user-interface objects to handle mouse input. Please see the
-documentation about \l{qtquick-input-mouseevents.html}
-{mouse events in Qt Quick} for more information on the topic.
+See also the documentation about
+\l{qtquick-input-mouseevents.html} {mouse events in Qt Quick}.
\section1 Keyboard Input and Keyboard Focus
diff --git a/src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers-index.qdoc b/src/quick/doc/src/concepts/inputhandlers/qtquickhandlers-index.qdoc
index fc1fd5fbc1..2ac9860e6f 100644
--- a/src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers-index.qdoc
+++ b/src/quick/doc/src/concepts/inputhandlers/qtquickhandlers-index.qdoc
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -27,35 +27,34 @@
/*!
\page qtquickhandlers-index.html
- \title Qt Quick Pointer Handlers
- \brief A module with a set of QML elements that handle events from pointing devices in a user interface.
+ \title Qt Quick Input Handlers
+ \brief A module with a set of QML elements that handle events from input devices in a user interface.
- Qt Quick Pointer Handlers are a set of QML types used to handle events from
- touch, mouse, and stylus devices in a UI. In contrast to event-handling
- Items, such as \l MouseArea, Pointer Handlers require less memory and are
- intended to be used in greater numbers: one handler per type of
- interaction. Each Pointer Handler handles events on behalf of its \c parent
- Item. One Item can have multiple Pointer Handlers.
+ Qt Quick Input Handlers are a set of QML types used to handle events from
+ keyboard, touch, mouse, and stylus devices in a UI. In contrast to event-handling
+ items, such as \l MouseArea and \l Flickable, input handlers are explicitly non-visual,
+ require less memory and are intended to be used in greater numbers: one
+ handler instance per aspect of interaction. Each input handler instance
+ handles certain events on behalf of its \c parent Item. Thus the visual and
+ behavioral concerns are better separated, and the behavior is built up by
+ finer-grained composition.
- The module is introduced in Qt 5.10.
+ In Qt 5.10, these handlers were introduced in a separate Qt.labs.handlers module.
+ Now they are included with Qt Quick since 5.12. The pre-existing
+ \l Keys attached property is similar in concept, so we refer to the
+ pointing-device-oriented handlers plus \c Keys together as the set of Input Handlers.
+ We expect to offer more attached-property use cases in future versions of Qt.
- \section1 Pointer Handlers
+ \section1 Input Handlers
- \annotatedlist pointerhandlers
-
- \section1 Getting Started
-
- The QML types can be imported into your application using the following import statement in your \c {.qml} file.
-
- \code
- import Qt.labs.handlers 1.0
- \endcode
+ \annotatedlist qtquick-input-handlers
\section1 Key Features
Some of the key features are:
\list
+ \li Handle keystrokes within the focused Item
\li Handle gestures such as tapping or dragging regardless which device it comes from
\li Handle gestures from different classes of devices in different ways
\li Each Item can have unlimited Handlers
@@ -67,7 +66,5 @@
\list
\li \l{Qt Quick}
- \li \l{Qt Quick Pointer Handlers}
- \li \l{Qt Quick Pointer Handlers QML Types}{Qt Quick Pointer Handlers QML Types}
\endlist
*/
diff --git a/src/quick/doc/src/concepts/layouts/qtquicklayouts.qdoc b/src/quick/doc/src/concepts/layouts/qtquicklayouts.qdoc
index d82e35fb93..c33fc0cfa3 100644
--- a/src/quick/doc/src/concepts/layouts/qtquicklayouts.qdoc
+++ b/src/quick/doc/src/concepts/layouts/qtquicklayouts.qdoc
@@ -26,7 +26,7 @@
****************************************************************************/
/*!
- \qmlmodule QtQuick.Layouts 1.11
+ \qmlmodule QtQuick.Layouts 1.\QtMinorVersion
\title Qt Quick Layouts QML Types
\ingroup qmlmodules
\brief Provides QML types for arranging QML items in a user interface.
@@ -39,8 +39,8 @@
The QML types can be imported into your application using the
following import statement in your .qml file.
- \code
- import QtQuick.Layouts 1.11
- \endcode
+ \qml \QtMinorVersion
+ import QtQuick.Layouts 1.\1
+ \endqml
*/
diff --git a/src/quick/doc/src/concepts/modelviewsdata/cppmodels.qdoc b/src/quick/doc/src/concepts/modelviewsdata/cppmodels.qdoc
index 2705ca5e34..a849a30b4e 100644
--- a/src/quick/doc/src/concepts/modelviewsdata/cppmodels.qdoc
+++ b/src/quick/doc/src/concepts/modelviewsdata/cppmodels.qdoc
@@ -41,9 +41,10 @@ QObjectList or a \l QAbstractItemModel. The first three are useful for exposing
simpler datasets, while QAbstractItemModel provides a more flexible solution for
more complex models.
-For a video tutorial that takes you through the whole process of exposing a C++
-model to QML, see the
-\l {https://youtu.be/9BcAYDlpuT8}{Using C++ Models in QML Tutorial}.
+Here is a video tutorial that takes you through the whole process of exposing a C++
+model to QML:
+
+\youtube 9BcAYDlpuT8
\section2 QStringList-based Model
@@ -232,34 +233,10 @@ contact details from an SQLite database.
\section3 Editable Data Model
-Besides the \c roleNames() and \c data(), the editable models must reimplement
-the \l{QSqlTableModel::}{setData} method to save changes to existing SQL data.
-The following version of the method checks if the given model index is valid
-and the \c role is equal to \l Qt::EditRole, before calling the parent class
-version:
-
-\code
-bool SqlEditableModel::setData(const QModelIndex &item, const QVariant &value, int role)
-{
- if (item.isValid() && role == Qt::EditRole) {
- QSqlTableModel::setData(item, value,role);
- emit dataChanged(item, item);
- return true;
- }
- return false;
+QSqlTableModel implements setData() as described \l{#changing-model-data}{below}.
-}
-\endcode
-
-\note It is important to emit the \l{QAbstractItemModel::}{dataChanged}()
-signal after saving the changes.
-
-Unlike the C++ item views such as QListView or QTableView, the \c setData()
-method must be explicitly invoked from QML whenever appropriate. For example,
-on the \l[QML]{TextField::}{editingFinished}() or \l[QML]{TextField::}{accepted}()
-signal of \l[QtQuickControls]{TextField}. Depending on the
-\l{QSqlTableModel::}{EditStrategy} used by the model, the changes are either
-queued for submission later or submitted immediately.
+Depending on the \l{QSqlTableModel::}{EditStrategy} used by the model, the
+changes are either queued for submission later or submitted immediately.
You can also insert new data into the model by calling
\l {QSqlTableModel::insertRecord}(). In the following example snippet,
@@ -326,5 +303,51 @@ ListView {
See \l {Writing QML Extensions with C++} for details on writing QML C++
plugins.
+\section2 Changing Model Data
+
+Besides the \c roleNames() and \c data(), editable models must reimplement
+the \l{QAbstractItemModel::}{setData} method to save changes to existing model data.
+The following version of the method checks if the given model index is valid
+and the \c role is equal to \l Qt::EditRole:
+
+\code
+bool EditableModel::setData(const QModelIndex &index, const QVariant &value, int role)
+{
+ if (index.isValid() && role == Qt::EditRole) {
+ // Set data in model here. It can also be a good idea to check whether
+ // the new value actually differs from the current value
+ if (m_entries[index.row()] != value.toString()) {
+ m_entries[index.row()] = value.toString();
+ emit dataChanged(index, index, { Qt::EditRole, Qt::DisplayRole });
+ return true;
+ }
+ }
+ return false;
+}
+\endcode
+
+\note It is important to emit the \l{QAbstractItemModel::}{dataChanged}()
+signal after saving the changes.
+
+Unlike the C++ item views such as QListView or QTableView, the \c setData()
+method must be explicitly invoked from QML delegates whenever appropriate. This is done
+by simply assigning a new value to the corresponding model property. For example,
+on the \l[QML]{TextField::}{editingFinished}() or \l[QML]{TextField::}{accepted}()
+signal of \l[QtQuickControls]{TextField}.
+
+\qml
+ListView {
+ anchors.fill: parent
+ model: EditableModel {}
+ delegate: TextField {
+ width: ListView.view.width
+ text: model.edit
+ onAccepted: model.edit = text
+ }
+}
+\endqml
+
+\note The \c edit role is equal to \l Qt::EditRole. See \l{QAbstractItemModel::}{roleNames}()
+for the built-in role names. However, real life models would usually register custom roles.
*/
diff --git a/src/quick/doc/src/concepts/modelviewsdata/modelview.qdoc b/src/quick/doc/src/concepts/modelviewsdata/modelview.qdoc
index 86beb38e6a..0c6aaecf42 100644
--- a/src/quick/doc/src/concepts/modelviewsdata/modelview.qdoc
+++ b/src/quick/doc/src/concepts/modelviewsdata/modelview.qdoc
@@ -46,7 +46,8 @@ types for creating models.
display the data in a list or a grid.
\li \b Delegate - dictates how the data should appear in the view.
The delegate takes each data in the model and encapsulates it. The data is
-accessible through the delegate.
+accessible through the delegate. The delegate can also write data
+back into editable models (e.g. in a TextField's onAccepted Handler).
\endlist
To visualize data, bind the view's \c model property to a model and the
@@ -278,11 +279,6 @@ To visualize data, bind the view's \c model property to a model and the
}
\endcode
- \note VisualItemModel can also be used, but it is only provided for compatibility
- reasons. VisualItemModel allows a QML item to be provided as a model. This model
- contains both the data and delegate; the child items of a VisualItemModel
- provide the contents of the delegate. The model does not provide any roles.
-
\section2 Integers as Models
An integer can be used as a model that contains a certain number
@@ -307,6 +303,7 @@ To visualize data, bind the view's \c model property to a model and the
}
\endqml
+ \note The limit on the number of items in an integer model is 100,000,000.
\section2 Object Instances as Models
@@ -394,6 +391,35 @@ If the model is a string list, the delegate is also exposed to a read-only
It is also possible to use a delegate as the template for the items created
by a Repeater. This is specified using the \l{Repeater::}{delegate} property.
+\section1 Changing Model Data
+
+To change model data, you can assign updated values to the \c model properties.
+The QML ListModel is editable by default whereas C++ models must implement
+setData() to become editable. Integer and JavaScript array models are read-only.
+
+Supposed a \l{QAbstractItemModel} based C++ model that implements the
+\l{QAbstractItemModel::}{setData} method is registered as a QML type named
+\c EditableModel. Data could then be written to the model like this:
+
+\qml
+ListView {
+ anchors.fill: parent
+ model: EditableModel {}
+ delegate: TextEdit {
+ width: ListView.view.width
+ height: 30
+ text: model.edit
+ Keys.onReturnPressed: model.edit = text
+ }
+}
+\endqml
+
+\note The \c edit role is equal to \l Qt::EditRole. See \l{QAbstractItemModel::}{roleNames}()
+for the built-in role names. However, real life models would usually register custom roles.
+
+For more information, visit the \l{qtquick-modelviewsdata-cppmodels.html#changing-model-data}{Using C++ Models with Qt Quick Views}
+article.
+
\section1 Using Transitions
Transitions can be used to animate items that are added to, moved within,
diff --git a/src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers.qdoc b/src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers.qdoc
deleted file mode 100644
index cf87c75e8c..0000000000
--- a/src/quick/doc/src/concepts/pointerhandlers/qtquickhandlers.qdoc
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** 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 Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: https://www.gnu.org/licenses/fdl-1.3.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
- \qmlmodule Qt.labs.handlers 1.0
- \title Qt Quick Pointer Handlers QML Types
- \ingroup qmlmodules
- \brief Provides QML types for handling events from pointing devices in a user interface.
-
- The \l{Qt Quick Pointer Handlers} module provides QML types for handling
- events from pointing devices in a UI. These QML types work in conjunction
- with \l{Qt Quick}.
-
- The QML types can be imported into your application using the
- following import statement in your .qml file.
-
- \code
- import Qt.labs.handlers 1.0
- \endcode
-*/
diff --git a/src/quick/doc/src/concepts/positioning/righttoleft.qdoc b/src/quick/doc/src/concepts/positioning/righttoleft.qdoc
index 4e1eca7ac3..7c8cd735b3 100644
--- a/src/quick/doc/src/concepts/positioning/righttoleft.qdoc
+++ b/src/quick/doc/src/concepts/positioning/righttoleft.qdoc
@@ -73,7 +73,7 @@ the effective alignment of the text element that takes the mirroring into accoun
(This applies to the \l Row, \l Grid, \l Flow, \l ListView and \l GridView types.)
-From Qt Quick 1.1 onwards, types used for horizontal positioning and model views have gained a \c layoutDirection
+Types used for horizontal positioning and model views have the \c layoutDirection
property for controlling the horizontal direction of the layouts. Setting \c layoutDirection to
\c Qt.RightToLeft causes items to be laid out from the right to left. By default Qt Quick follows
the left-to-right layout direction.
@@ -132,7 +132,7 @@ aligned and just make sure that text is translated and aligned properly.
(This applies to \l Image, \l BorderImage and \l AnimatedImage types.)
Most images do not need to be mirrored, but some directional icons, such as arrows, may need to be mirrored.
-The painting of these icons can be mirrored with a dedicated \c mirror property introduced in Qt Quick 1.1:
+The painting of these icons can be mirrored with a dedicated \c mirror property:
\snippet qml/righttoleft.qml 5
diff --git a/src/quick/doc/src/concepts/visualcanvas/scenegraph.qdoc b/src/quick/doc/src/concepts/visualcanvas/scenegraph.qdoc
index 99175ab94e..4c94259139 100644
--- a/src/quick/doc/src/concepts/visualcanvas/scenegraph.qdoc
+++ b/src/quick/doc/src/concepts/visualcanvas/scenegraph.qdoc
@@ -796,6 +796,14 @@ with multiple windows.
\li Mipmapped Image items are not placed in the global atlas and will
not be batched.
+ \li A bug in the OpenGL driver related to framebuffer object (FBO) readbacks
+ may corrupt rendered glyphs. If you set the \c QML_USE_GLYPHCACHE_WORKAROUND
+ environment variable, Qt keeps an additional copy of the glyph in RAM. This
+ means that performance is slightly lower when drawing glyphs that have not
+ been drawn before, as Qt accesses the extra copy via the CPU. It also means
+ that the glyph cache will use twice as much memory. The quality is not
+ affected by this.
+
\endlist
If an application performs poorly, make sure that rendering is
diff --git a/src/quick/doc/src/guidelines/qtquick-bestpractices.qdoc b/src/quick/doc/src/guidelines/qtquick-bestpractices.qdoc
index c8bdfa28cd..dd7f21e81a 100644
--- a/src/quick/doc/src/guidelines/qtquick-bestpractices.qdoc
+++ b/src/quick/doc/src/guidelines/qtquick-bestpractices.qdoc
@@ -28,7 +28,7 @@
/*!
\page qtquick-bestpractices.html
\title Best Practices for QML and Qt Quick
-\brief Lists best practices for working with QML and Qt Quick
+\brief Lists best practices for working with QML and Qt Quick.
\ingroup best-practices
Despite all of the benefits that QML and Qt Quick offer, they can be
@@ -121,7 +121,7 @@ of resources. However, whenever a new file is added to \c RESOURCES using this
approach, it causes \e all of the other files in \c RESOURCES to be recompiled
as well. This can be inefficient, especially for large sets of files.
In this case, a better approach is to separate each type of resource into its
-own \l {Resource Collection Files (.qrc)}{.qrc} file. For example, the snippet
+own \l [Qt Core] {Resource Collection Files}{.qrc} file. For example, the snippet
above could be changed to the following:
\badcode
@@ -197,9 +197,9 @@ so. To explain why, let's take a look at a simplified example.
Suppose we were writing the UI for a settings page:
-\qml
- import QtQuick 2.11
- import QtQuick.Controls 2.4
+\qml \QtMinorVersion
+ import QtQuick 2.\1
+ import QtQuick.Controls 2.\1
Page {
Button {
@@ -296,9 +296,9 @@ into QML:
The QML then calls the C++ slot directly:
-\qml
- import QtQuick 2.11
- import QtQuick.Controls 2.4
+\qml \QtMinorVersion
+ import QtQuick 2.\1
+ import QtQuick.Controls 2.\1
Page {
Button {
diff --git a/src/quick/doc/src/qmltypereference.qdoc b/src/quick/doc/src/qmltypereference.qdoc
index e787ed31ef..ddf90f88d9 100644
--- a/src/quick/doc/src/qmltypereference.qdoc
+++ b/src/quick/doc/src/qmltypereference.qdoc
@@ -26,7 +26,7 @@
****************************************************************************/
/*!
-\qmlmodule QtQuick 2.11
+\qmlmodule QtQuick 2.\QtMinorVersion
\title Qt Quick QML Types
\ingroup qmlmodules
\brief Provides graphical QML types.
@@ -34,11 +34,11 @@
The \l{Qt Quick} module provides graphical primitive types. These types are only
available in a QML document if that document imports the \c QtQuick namespace.
-The current version of the \c QtQuick module is version 2.11, and thus it may be
-imported via the following statement:
+The current version of the \c QtQuick module is version \QtMinorVersion, and
+thus it may be imported via the following statement:
-\qml
-import QtQuick 2.11
+\qml \QtMinorVersion
+import QtQuick 2.\1
\endqml
Visit the \l {Qt Quick} module documentation for more
@@ -78,7 +78,7 @@ In addition, the \c QtQuick import provides the following basic types:
\section1 Object Types
-All object types provided by the \c QtQuick import are based on the \l{Item}
+Most object types provided by the \c QtQuick import are based on the \l{Item}
type, which itself derives from \l{QtQml::QtObject}{QtObject}. \l{Qt QML QML
Types#Object Types} {QML object types} provided by the Qt QML module (such as
\l{QtQml::QtObject}{QtObject} and \l{QtQml::Component}{Component}) are also
@@ -889,15 +889,16 @@ console.log(c + " " + d); // false true
*/
/*!
-\qmlmodule QtTest 1.11
+\qmlmodule QtTest 1.\QtMinorVersion
\title Qt Quick Test QML Types
\brief This module provides QML types to unit test your QML application
\ingroup qmlmodules
You can import this module using the following statement:
-\code
-import QtTest 1.11
-\endcode
+
+\qml \QtMinorVersion
+import QtTest 1.\1
+\endqml
For more information about how to use these types, see
\l{Qt Quick Test}.
diff --git a/src/quick/handlers/handlers.pri b/src/quick/handlers/handlers.pri
index 8bd74d95da..1258822f40 100644
--- a/src/quick/handlers/handlers.pri
+++ b/src/quick/handlers/handlers.pri
@@ -1,17 +1,22 @@
HEADERS += \
$$PWD/qquickdraghandler_p.h \
- $$PWD/qquickhandlersmodule_p.h \
+ $$PWD/qquickhandlerpoint_p.h \
+ $$PWD/qquickhoverhandler_p.h \
$$PWD/qquickmultipointhandler_p.h \
$$PWD/qquickpinchhandler_p.h \
$$PWD/qquickpointerdevicehandler_p.h \
+ $$PWD/qquickpointerdevicehandler_p_p.h \
$$PWD/qquickpointerhandler_p.h \
+ $$PWD/qquickpointerhandler_p_p.h \
$$PWD/qquickpointhandler_p.h \
$$PWD/qquicksinglepointhandler_p.h \
$$PWD/qquicktaphandler_p.h \
+ $$PWD/qquickdragaxis_p.h
SOURCES += \
$$PWD/qquickdraghandler.cpp \
- $$PWD/qquickhandlersmodule.cpp \
+ $$PWD/qquickhandlerpoint.cpp \
+ $$PWD/qquickhoverhandler.cpp \
$$PWD/qquickmultipointhandler.cpp \
$$PWD/qquickpinchhandler.cpp \
$$PWD/qquickpointerdevicehandler.cpp \
@@ -19,4 +24,4 @@ SOURCES += \
$$PWD/qquickpointhandler.cpp \
$$PWD/qquicksinglepointhandler.cpp \
$$PWD/qquicktaphandler.cpp \
-
+ $$PWD/qquickdragaxis.cpp
diff --git a/src/quick/scenegraph/compressedtexture/qsgpkmhandler_p.h b/src/quick/handlers/qquickdragaxis.cpp
index 6154c51b84..5efe19b2fe 100644
--- a/src/quick/scenegraph/compressedtexture/qsgpkmhandler_p.h
+++ b/src/quick/handlers/qquickdragaxis.cpp
@@ -36,35 +36,40 @@
** $QT_END_LICENSE$
**
****************************************************************************/
+#include "qquickdragaxis_p.h"
+#include <limits>
-#ifndef QSGPKMHANDLER_H
-#define QSGPKMHANDLER_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.
-//
+QQuickDragAxis::QQuickDragAxis()
+ : m_minimum(-std::numeric_limits<qreal>::max())
+ , m_maximum(std::numeric_limits<qreal>::max())
+ , m_enabled(true)
+{
+}
-#include "qsgtexturefilehandler_p.h"
+void QQuickDragAxis::setMinimum(qreal minimum)
+{
+ if (m_minimum == minimum)
+ return;
-QT_BEGIN_NAMESPACE
+ m_minimum = minimum;
+ emit minimumChanged();
+}
-class QSGPkmHandler : public QSGTextureFileHandler
+void QQuickDragAxis::setMaximum(qreal maximum)
{
-public:
- using QSGTextureFileHandler::QSGTextureFileHandler;
+ if (m_maximum == maximum)
+ return;
- static bool canRead(const QByteArray &suffix, const QByteArray &block);
+ m_maximum = maximum;
+ emit maximumChanged();
+}
- QQuickTextureFactory *read() override;
-};
+void QQuickDragAxis::setEnabled(bool enabled)
+{
+ if (m_enabled == enabled)
+ return;
-QT_END_NAMESPACE
+ m_enabled = enabled;
+ emit enabledChanged();
+}
-#endif // QSGPKMHANDLER_H
diff --git a/src/quick/scenegraph/compressedtexture/qsgtexturefilehandler_p.h b/src/quick/handlers/qquickdragaxis_p.h
index 8b831aebb9..2c2e0a426d 100644
--- a/src/quick/scenegraph/compressedtexture/qsgtexturefilehandler_p.h
+++ b/src/quick/handlers/qquickdragaxis_p.h
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QSGTEXTUREFILEHANDLER_P_H
-#define QSGTEXTUREFILEHANDLER_P_H
+#ifndef QQUICKDRAGAXIS_P_H
+#define QQUICKDRAGAXIS_P_H
//
// W A R N I N G
@@ -51,33 +51,37 @@
// We mean it.
//
-#include <QLoggingCategory>
+#include <QtCore/qobject.h>
+#include <QtCore/qglobal.h>
-QT_BEGIN_NAMESPACE
+class Q_AUTOTEST_EXPORT QQuickDragAxis : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(qreal minimum READ minimum WRITE setMinimum NOTIFY minimumChanged)
+ Q_PROPERTY(qreal maximum READ maximum WRITE setMaximum NOTIFY maximumChanged)
+ Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
-Q_DECLARE_LOGGING_CATEGORY(QSG_LOG_TEXTUREIO)
+public:
+ QQuickDragAxis();
-class QQuickTextureFactory;
+ qreal minimum() const { return m_minimum; }
+ void setMinimum(qreal minimum);
-class QSGTextureFileHandler
-{
-public:
- QSGTextureFileHandler(QIODevice *device, const QByteArray &logName = QByteArray())
- : m_device(device)
- {
- m_logName = !logName.isEmpty() ? logName : QByteArrayLiteral("(unknown)");
- }
- virtual ~QSGTextureFileHandler() {}
+ qreal maximum() const { return m_maximum; }
+ void setMaximum(qreal maximum);
+
+ bool enabled() const { return m_enabled; }
+ void setEnabled(bool enabled);
- virtual QQuickTextureFactory *read() = 0;
- QIODevice *device() const { return m_device; }
- QByteArray logName() const { return m_logName; }
+signals:
+ void minimumChanged();
+ void maximumChanged();
+ void enabledChanged();
private:
- QIODevice *m_device = nullptr;
- QByteArray m_logName;
+ qreal m_minimum;
+ qreal m_maximum;
+ bool m_enabled;
};
-QT_END_NAMESPACE
-
-#endif // QSGTEXTUREFILEHANDLER_P_H
+#endif // QQUICKDRAGAXIS_P_H
diff --git a/src/quick/handlers/qquickdraghandler.cpp b/src/quick/handlers/qquickdraghandler.cpp
index 5e540b3615..aa66c16007 100644
--- a/src/quick/handlers/qquickdraghandler.cpp
+++ b/src/quick/handlers/qquickdraghandler.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
@@ -43,16 +43,20 @@
QT_BEGIN_NAMESPACE
+static const qreal DragAngleToleranceDegrees = 10;
+
+Q_LOGGING_CATEGORY(lcDragHandler, "qt.quick.handler.drag")
+
/*!
\qmltype DragHandler
\instantiates QQuickDragHandler
- \inherits SinglePointHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inherits MultiPointHandler
+ \inqmlmodule QtQuick
+ \ingroup qtquick-input-handlers
\brief Handler for dragging.
DragHandler is a handler that is used to interactively move an Item.
- Like other Pointer Handlers, by default it is fully functional, and
+ Like other Input Handlers, by default it is fully functional, and
manipulates its \l {PointerHandler::target} {target}.
\snippet pointerHandlers/dragHandler.qml 0
@@ -71,119 +75,173 @@ QT_BEGIN_NAMESPACE
\snippet pointerHandlers/dragHandlerNullTarget.qml 0
+ If minimumPointCount and maximumPointCount are set to values larger than 1,
+ the user will need to drag that many fingers in the same direction to start
+ dragging. A multi-finger drag gesture can be detected independently of both
+ a (default) single-finger DragHandler and a PinchHandler on the same Item,
+ and thus can be used to adjust some other feature independently of the
+ usual pinch behavior: for example adjust a tilt transformation, or adjust
+ some other numeric value, if the \c target is set to null. But if the
+ \l target is an Item, \l centroid is the point at which the drag begins and
+ to which the \c target will be moved (subject to constraints).
+
At this time, drag-and-drop is not yet supported.
\sa Drag, MouseArea
*/
-QQuickDragHandler::QQuickDragHandler(QObject *parent)
- : QQuickSinglePointHandler(parent)
-{
-}
-
-QQuickDragHandler::~QQuickDragHandler()
-{
-}
-
-bool QQuickDragHandler::wantsEventPoint(QQuickEventPoint *point)
+QQuickDragHandler::QQuickDragHandler(QQuickItem *parent)
+ : QQuickMultiPointHandler(parent, 1, 1)
{
- // If we've already been interested in a point, stay interested, even if it has strayed outside bounds.
- return ((point->state() != QQuickEventPoint::Pressed && this->point().id() == point->pointId())
- || QQuickSinglePointHandler::wantsEventPoint(point));
}
-bool QQuickDragHandler::targetContains(QQuickEventPoint *point)
+bool QQuickDragHandler::targetContainsCentroid()
{
Q_ASSERT(parentItem() && target());
- return target()->contains(localTargetPosition(point));
+ return target()->contains(targetCentroidPosition());
}
-QPointF QQuickDragHandler::localTargetPosition(QQuickEventPoint *point)
+QPointF QQuickDragHandler::targetCentroidPosition()
{
- QPointF pos = point->position();
+ QPointF pos = m_centroid.position();
if (target() != parentItem())
pos = parentItem()->mapToItem(target(), pos);
return pos;
}
-void QQuickDragHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point)
+void QQuickDragHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point)
{
- if (grabber == this && stateChange == QQuickEventPoint::GrabExclusive) {
+ QQuickMultiPointHandler::onGrabChanged(grabber, transition, point);
+ if (grabber == this && transition == QQuickEventPoint::GrabExclusive) {
// In case the grab got handed over from another grabber, we might not get the Press.
if (!m_pressedInsideTarget) {
if (target())
m_pressTargetPos = QPointF(target()->width(), target()->height()) / 2;
- m_pressScenePos = point->scenePosition();
} else if (m_pressTargetPos.isNull()) {
if (target())
- m_pressTargetPos = localTargetPosition(point);
- m_pressScenePos = point->scenePosition();
+ m_pressTargetPos = targetCentroidPosition();
}
}
- QQuickSinglePointHandler::onGrabChanged(grabber, stateChange, point);
}
void QQuickDragHandler::onActiveChanged()
{
- if (!active()) {
+ QQuickMultiPointHandler::onActiveChanged();
+ if (active()) {
+ if (auto parent = parentItem()) {
+ if (currentEvent()->asPointerTouchEvent())
+ parent->setKeepTouchGrab(true);
+ // tablet and mouse are treated the same by Item's legacy event handling, and
+ // touch becomes synth-mouse for Flickable, so we need to prevent stealing
+ // mouse grab too, whenever dragging occurs in an enabled direction
+ parent->setKeepMouseGrab(true);
+ }
+ } else {
m_pressTargetPos = QPointF();
- m_pressScenePos = m_pressTargetPos;
m_pressedInsideTarget = false;
+ if (auto parent = parentItem()) {
+ parent->setKeepTouchGrab(false);
+ parent->setKeepMouseGrab(false);
+ }
}
}
-void QQuickDragHandler::handleEventPoint(QQuickEventPoint *point)
+void QQuickDragHandler::handlePointerEventImpl(QQuickPointerEvent *event)
{
- point->setAccepted();
- switch (point->state()) {
- case QQuickEventPoint::Pressed:
- if (target()) {
- m_pressedInsideTarget = targetContains(point);
- m_pressTargetPos = localTargetPosition(point);
- }
- m_pressScenePos = point->scenePosition();
- setPassiveGrab(point);
- break;
- case QQuickEventPoint::Updated: {
- QVector2D accumulatedDragDelta = QVector2D(point->scenePosition() - m_pressScenePos);
- if (active()) {
- // update translation property. Make sure axis is respected for it.
- if (!m_xAxis.enabled())
+ QQuickMultiPointHandler::handlePointerEventImpl(event);
+ event->setAccepted(true);
+
+ if (active()) {
+ // Calculate drag delta, taking into account the axis enabled constraint
+ // i.e. if xAxis is not enabled, then ignore the horizontal component of the actual movement
+ QVector2D accumulatedDragDelta = QVector2D(m_centroid.scenePosition() - m_centroid.scenePressPosition());
+ if (!m_xAxis.enabled())
+ accumulatedDragDelta.setX(0);
+ if (!m_yAxis.enabled())
+ accumulatedDragDelta.setY(0);
+ setTranslation(accumulatedDragDelta);
+ } else {
+ // Check that all points have been dragged past the drag threshold,
+ // to the extent that the constraints allow,
+ // and in approximately the same direction
+ qreal minAngle = 361;
+ qreal maxAngle = -361;
+ bool allOverThreshold = !event->isReleaseEvent();
+ QVector <QQuickEventPoint *> chosenPoints;
+
+ if (event->isPressEvent())
+ m_pressedInsideTarget = target() && m_currentPoints.count() > 0;
+
+ for (const QQuickHandlerPoint &p : m_currentPoints) {
+ if (!allOverThreshold)
+ break;
+ QQuickEventPoint *point = event->pointById(p.id());
+ chosenPoints << point;
+ setPassiveGrab(point);
+ // Calculate drag delta, taking into account the axis enabled constraint
+ // i.e. if xAxis is not enabled, then ignore the horizontal component of the actual movement
+ QVector2D accumulatedDragDelta = QVector2D(point->scenePosition() - point->scenePressPosition());
+ if (!m_xAxis.enabled()) {
+ // If horizontal dragging is disallowed, but the user is dragging
+ // mostly horizontally, then don't activate.
+ if (qAbs(accumulatedDragDelta.x()) > qAbs(accumulatedDragDelta.y()))
+ accumulatedDragDelta.setY(0);
accumulatedDragDelta.setX(0);
- if (!m_yAxis.enabled())
+ }
+ if (!m_yAxis.enabled()) {
+ // If vertical dragging is disallowed, but the user is dragging
+ // mostly vertically, then don't activate.
+ if (qAbs(accumulatedDragDelta.y()) > qAbs(accumulatedDragDelta.x()))
+ accumulatedDragDelta.setX(0);
accumulatedDragDelta.setY(0);
- setTranslation(accumulatedDragDelta);
-
- if (target() && target()->parentItem()) {
- const QPointF newTargetTopLeft = localTargetPosition(point) - m_pressTargetPos;
- const QPointF xformOrigin = target()->transformOriginPoint();
- const QPointF targetXformOrigin = newTargetTopLeft + xformOrigin;
- QPointF pos = target()->parentItem()->mapFromItem(target(), targetXformOrigin);
- pos -= xformOrigin;
- QPointF targetItemPos = target()->position();
- if (!m_xAxis.enabled())
- pos.setX(targetItemPos.x());
- if (!m_yAxis.enabled())
- pos.setY(targetItemPos.y());
- enforceAxisConstraints(&pos);
- moveTarget(pos, point);
}
- } else if (!point->exclusiveGrabber() &&
- ((m_xAxis.enabled() && QQuickWindowPrivate::dragOverThreshold(accumulatedDragDelta.x(), Qt::XAxis, point)) ||
- (m_yAxis.enabled() && QQuickWindowPrivate::dragOverThreshold(accumulatedDragDelta.y(), Qt::YAxis, point)))) {
- setExclusiveGrab(point);
- if (auto parent = parentItem()) {
- if (point->pointerEvent()->asPointerTouchEvent())
- parent->setKeepTouchGrab(true);
- // tablet and mouse are treated the same by Item's legacy event handling, and
- // touch becomes synth-mouse for Flickable, so we need to prevent stealing
- // mouse grab too, whenever dragging occurs in an enabled direction
- parent->setKeepMouseGrab(true);
+ qreal angle = std::atan2(accumulatedDragDelta.y(), accumulatedDragDelta.x()) * 180 / M_PI;
+ bool overThreshold = QQuickWindowPrivate::dragOverThreshold(accumulatedDragDelta);
+ qCDebug(lcDragHandler) << "movement" << accumulatedDragDelta << "angle" << angle << "of point" << point
+ << "pressed @" << point->scenePressPosition() << "over threshold?" << overThreshold;
+ minAngle = qMin(angle, minAngle);
+ maxAngle = qMax(angle, maxAngle);
+ if (allOverThreshold && !overThreshold)
+ allOverThreshold = false;
+
+ if (event->isPressEvent()) {
+ // m_pressedInsideTarget should stay true iff ALL points in which DragHandler is interested
+ // have been pressed inside the target() Item. (E.g. in a Slider the parent might be the
+ // whole control while the target is just the knob.)
+ if (target()) {
+ const QPointF localPressPos = target()->mapFromScene(point->scenePressPosition());
+ m_pressedInsideTarget &= target()->contains(localPressPos);
+ m_pressTargetPos = targetCentroidPosition();
+ }
+ // QQuickWindowPrivate::deliverToPassiveGrabbers() skips subsequent delivery if the event is filtered.
+ // (That affects behavior for mouse but not for touch, because Flickable only handles mouse.)
+ // So we have to compensate by accepting the event here to avoid any parent Flickable from
+ // getting the event via direct delivery and grabbing too soon.
+ point->setAccepted(event->asPointerMouseEvent()); // stop propagation iff it's a mouse event
}
}
- } break;
- default:
- break;
+ if (allOverThreshold) {
+ qreal angleDiff = maxAngle - minAngle;
+ if (angleDiff > 180)
+ angleDiff = 360 - angleDiff;
+ qCDebug(lcDragHandler) << "angle min" << minAngle << "max" << maxAngle << "range" << angleDiff;
+ if (angleDiff < DragAngleToleranceDegrees && grabPoints(chosenPoints))
+ setActive(true);
+ }
+ }
+ if (active() && target() && target()->parentItem()) {
+ const QPointF newTargetTopLeft = targetCentroidPosition() - m_pressTargetPos;
+ const QPointF xformOrigin = target()->transformOriginPoint();
+ const QPointF targetXformOrigin = newTargetTopLeft + xformOrigin;
+ QPointF pos = target()->parentItem()->mapFromItem(target(), targetXformOrigin);
+ pos -= xformOrigin;
+ QPointF targetItemPos = target()->position();
+ if (!m_xAxis.enabled())
+ pos.setX(targetItemPos.x());
+ if (!m_yAxis.enabled())
+ pos.setY(targetItemPos.y());
+ enforceAxisConstraints(&pos);
+ moveTarget(pos);
}
}
@@ -243,39 +301,6 @@ void QQuickDragHandler::setTranslation(const QVector2D &trans)
applied to the \l {PointerHandler::target} {target}.
If \c enabled is true, vertical dragging is allowed.
*/
-QQuickDragAxis::QQuickDragAxis()
- : m_minimum(-DBL_MAX)
- , m_maximum(DBL_MAX)
- , m_enabled(true)
-{
-}
-
-void QQuickDragAxis::setMinimum(qreal minimum)
-{
- if (m_minimum == minimum)
- return;
-
- m_minimum = minimum;
- emit minimumChanged();
-}
-
-void QQuickDragAxis::setMaximum(qreal maximum)
-{
- if (m_maximum == maximum)
- return;
-
- m_maximum = maximum;
- emit maximumChanged();
-}
-
-void QQuickDragAxis::setEnabled(bool enabled)
-{
- if (m_enabled == enabled)
- return;
-
- m_enabled = enabled;
- emit enabledChanged();
-}
/*!
\readonly
diff --git a/src/quick/handlers/qquickdraghandler_p.h b/src/quick/handlers/qquickdraghandler_p.h
index 363df31a64..387a81eb43 100644
--- a/src/quick/handlers/qquickdraghandler_p.h
+++ b/src/quick/handlers/qquickdraghandler_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
@@ -51,41 +51,12 @@
// We mean it.
//
-#include "qquicksinglepointhandler_p.h"
+#include "qquickmultipointhandler_p.h"
+#include "qquickdragaxis_p.h"
QT_BEGIN_NAMESPACE
-class Q_AUTOTEST_EXPORT QQuickDragAxis : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(qreal minimum READ minimum WRITE setMinimum NOTIFY minimumChanged)
- Q_PROPERTY(qreal maximum READ maximum WRITE setMaximum NOTIFY maximumChanged)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
-
-public:
- QQuickDragAxis();
-
- qreal minimum() const { return m_minimum; }
- void setMinimum(qreal minimum);
-
- qreal maximum() const { return m_maximum; }
- void setMaximum(qreal maximum);
-
- bool enabled() const { return m_enabled; }
- void setEnabled(bool enabled);
-
-signals:
- void minimumChanged();
- void maximumChanged();
- void enabledChanged();
-
-private:
- qreal m_minimum;
- qreal m_maximum;
- bool m_enabled;
-};
-
-class Q_AUTOTEST_EXPORT QQuickDragHandler : public QQuickSinglePointHandler
+class Q_AUTOTEST_EXPORT QQuickDragHandler : public QQuickMultiPointHandler
{
Q_OBJECT
Q_PROPERTY(QQuickDragAxis * xAxis READ xAxis CONSTANT)
@@ -93,10 +64,9 @@ class Q_AUTOTEST_EXPORT QQuickDragHandler : public QQuickSinglePointHandler
Q_PROPERTY(QVector2D translation READ translation NOTIFY translationChanged)
public:
- explicit QQuickDragHandler(QObject *parent = nullptr);
- ~QQuickDragHandler();
+ explicit QQuickDragHandler(QQuickItem *parent = nullptr);
- void handleEventPoint(QQuickEventPoint *point) override;
+ void handlePointerEventImpl(QQuickPointerEvent *event) override;
QQuickDragAxis *xAxis() { return &m_xAxis; }
QQuickDragAxis *yAxis() { return &m_yAxis; }
@@ -104,25 +74,22 @@ public:
QVector2D translation() const { return m_translation; }
void setTranslation(const QVector2D &trans);
- Q_INVOKABLE void enforceConstraints();
+ void enforceConstraints();
Q_SIGNALS:
-// void gestureStarted(QQuickGestureEvent *gesture);
void translationChanged();
protected:
- bool wantsEventPoint(QQuickEventPoint *point) override;
void onActiveChanged() override;
- void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point) override;
+ void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point) override;
private:
void ungrab();
void enforceAxisConstraints(QPointF *localPos);
- bool targetContains(QQuickEventPoint *point);
- QPointF localTargetPosition(QQuickEventPoint *point);
+ bool targetContainsCentroid();
+ QPointF targetCentroidPosition();
private:
- QPointF m_pressScenePos;
QPointF m_pressTargetPos; // We must also store the local targetPos, because we cannot deduce
// the press target pos from the scene pos in case there was e.g a
// flick in one of the ancestors during the drag.
diff --git a/src/quick/handlers/qquickhandlerpoint.cpp b/src/quick/handlers/qquickhandlerpoint.cpp
new file mode 100644
index 0000000000..6a106b5464
--- /dev/null
+++ b/src/quick/handlers/qquickhandlerpoint.cpp
@@ -0,0 +1,352 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 "qquickhandlerpoint_p.h"
+#include "private/qquickevents_p_p.h"
+
+QT_BEGIN_NAMESPACE
+Q_DECLARE_LOGGING_CATEGORY(DBG_TOUCH_TARGET)
+
+/*!
+ \qmltype HandlerPoint
+ \instantiates QQuickHandlerPoint
+ \inqmlmodule QtQuick
+ \brief An event point.
+
+ A QML representation of a QQuickEventPoint.
+
+ It's possible to make bindings to properties of a \l SinglePointHandler's
+ current point. For example:
+
+ \snippet pointerHandlers/dragHandlerNullTarget.qml 0
+
+ The point is kept up-to-date when the DragHandler is actively responding to
+ an EventPoint; but when the point is released, or the current point is
+ being handled by a different handler, \c position.x and \c position.y are 0.
+
+ \note This is practically identical to QtQuick::EventPoint; however an
+ EventPoint is a long-lived QObject which is invalidated between gestures
+ and reused for subsequent event deliveries. Continuous bindings to its
+ properties are not possible, and an individual handler cannot rely on it
+ outside the period when that point is part of an active gesture which that
+ handler is handling. HandlerPoint is a Q_GADGET that the handler owns.
+ This allows you to make lifetime bindings to its properties.
+
+ \sa SinglePointHandler::point
+*/
+
+QQuickHandlerPoint::QQuickHandlerPoint()
+{}
+
+void QQuickHandlerPoint::localize(QQuickItem *item)
+{
+ m_pressPosition = item->mapFromScene(m_scenePressPosition);
+}
+
+void QQuickHandlerPoint::reset()
+{
+ m_id = 0;
+ m_uniqueId = QPointingDeviceUniqueId();
+ m_position = QPointF();
+ m_scenePosition = QPointF();
+ m_pressPosition = QPointF();
+ m_scenePressPosition = QPointF();
+ m_sceneGrabPosition = QPointF();
+ m_velocity = QVector2D();
+ m_rotation = 0;
+ m_pressure = 0;
+ m_ellipseDiameters = QSizeF();
+ m_pressedButtons = Qt::NoButton;
+ m_pressedModifiers = Qt::NoModifier;
+}
+
+void QQuickHandlerPoint::reset(const QQuickEventPoint *point)
+{
+ m_id = point->pointId();
+ const QQuickPointerEvent *event = point->pointerEvent();
+ switch (point->state()) {
+ case QQuickEventPoint::Pressed:
+ m_pressPosition = point->position();
+ m_scenePressPosition = point->scenePosition();
+ m_pressedButtons = event->buttons();
+ break;
+ case QQuickEventPoint::Released:
+ if (event->buttons() == Qt::NoButton) {
+ reset();
+ return;
+ }
+ break;
+ default:
+ break;
+ }
+ m_scenePressPosition = point->scenePressPosition();
+ m_pressedButtons = event->buttons();
+ m_pressedModifiers = event->modifiers();
+ if (event->asPointerTouchEvent()) {
+ const QQuickEventTouchPoint *tp = static_cast<const QQuickEventTouchPoint *>(point);
+ m_uniqueId = tp->uniqueId();
+ m_rotation = tp->rotation();
+ m_pressure = tp->pressure();
+ m_ellipseDiameters = tp->ellipseDiameters();
+ } else if (event->asPointerTabletEvent()) {
+ // TODO
+ } else {
+ m_uniqueId = event->device()->uniqueId();
+ m_rotation = 0;
+ m_pressure = event->buttons() ? 1 : 0;
+ m_ellipseDiameters = QSizeF();
+ }
+ m_position = point->position();
+ m_scenePosition = point->scenePosition();
+ if (point->state() == QQuickEventPoint::Updated)
+ m_velocity = point->velocity();
+}
+
+void QQuickHandlerPoint::reset(const QVector<QQuickHandlerPoint> &points)
+{
+ if (points.isEmpty()) {
+ qWarning("reset: no points");
+ return;
+ }
+ if (points.count() == 1) {
+ *this = points.first(); // copy all values
+ return;
+ }
+ // all points are required to be from the same event
+ QPointF posSum;
+ QPointF scenePosSum;
+ QPointF pressPosSum;
+ QPointF scenePressPosSum;
+ QVector2D velocitySum;
+ qreal pressureSum = 0;
+ QSizeF ellipseDiameterSum;
+ for (const QQuickHandlerPoint &point : points) {
+ posSum += point.position();
+ scenePosSum += point.scenePosition();
+ pressPosSum += point.pressPosition();
+ scenePressPosSum += point.scenePressPosition();
+ velocitySum += point.velocity();
+ pressureSum += point.pressure();
+ ellipseDiameterSum += point.ellipseDiameters();
+ }
+ m_id = 0;
+ m_uniqueId = QPointingDeviceUniqueId();
+ // all points are required to be from the same event, so pressed buttons and modifiers should be the same
+ m_pressedButtons = points.first().pressedButtons();
+ m_pressedModifiers = points.first().modifiers();
+ m_position = posSum / points.size();
+ m_scenePosition = scenePosSum / points.size();
+ m_pressPosition = pressPosSum / points.size();
+ m_scenePressPosition = scenePressPosSum / points.size();
+ m_velocity = velocitySum / points.size();
+ m_rotation = 0; // averaging the rotations of all the points isn't very sensible
+ m_pressure = pressureSum / points.size();
+ m_ellipseDiameters = ellipseDiameterSum / points.size();
+}
+
+/*!
+ \readonly
+ \qmlproperty int QtQuick::HandlerPoint::id
+ \brief The ID number of the point
+
+ During a touch gesture, from the time that the first finger is pressed
+ until the last finger is released, each touchpoint will have a unique ID
+ number. Likewise, if input from multiple devices occurs (for example
+ simultaneous mouse and touch presses), all the current event points from
+ all the devices will have unique IDs.
+
+ \note Do not assume that id numbers start at zero or that they are
+ sequential. Such an assumption is often false due to the way the underlying
+ drivers work.
+
+ \sa QTouchEvent::TouchPoint::id
+*/
+
+/*!
+ \readonly
+ \qmlproperty PointingDeviceUniqueId QtQuick::HandlerPoint::uniqueId
+ \brief The unique ID of the point, if any
+
+ This is normally empty, because touchscreens cannot uniquely identify fingers.
+
+ On some types of touchscreens, especially those using TUIO drivers,
+ it's possible to use recognizable physical tokens (fiducial objects)
+ in addition to fingers. So if this point is a touch point, and
+ uniqueId is set, it is the identifier for such an object.
+
+ On a graphics tablet, each type of stylus or other tool often has a unique
+ ID or serial number, which can be useful to respond in different ways to
+ different tools.
+
+ Interpreting the contents of this ID requires knowledge of the hardware and
+ drivers in use.
+
+ \sa QTabletEvent::uniqueId, QtQuick::TouchPoint::uniqueId, QtQuick::EventTouchPoint::uniqueId
+*/
+
+/*!
+ \readonly
+ \qmlproperty QPointF QtQuick::HandlerPoint::position
+ \brief The position within the \c parent Item
+
+ This is the position of the event point relative to the bounds of
+ the \l {PointerHandler::parent} {parent}.
+*/
+
+/*!
+ \readonly
+ \qmlproperty QPointF QtQuick::HandlerPoint::scenePosition
+ \brief The position within the scene
+
+ This is the position of the event point relative to the bounds of the Qt
+ Quick scene (typically the whole window).
+*/
+
+/*!
+ \readonly
+ \qmlproperty QPointF QtQuick::HandlerPoint::pressPosition
+ \brief The pressed position within the \c parent Item
+
+ This is the position at which this point was pressed, relative to the
+ bounds of the \l {PointerHandler::parent} {parent}.
+*/
+
+/*!
+ \readonly
+ \qmlproperty QPointF QtQuick::HandlerPoint::scenePressPosition
+ \brief The pressed position within the scene
+
+ This is the position at which this point was pressed, in the coordinate
+ system of the \l {Qt Quick Scene Graph}{scene graph}.
+*/
+
+/*!
+ \readonly
+ \qmlproperty QPointF QtQuick::HandlerPoint::sceneGrabPosition
+ \brief The grabbed position within the scene
+
+ If this point has been grabbed by a Pointer Handler or an Item, it means
+ that object has taken sole responsibility for handling the movement and the
+ release if this point. In that case, this is the position at which the grab
+ occurred, in the coordinate system of the \l {Qt Quick Scene Graph}{scene graph}.
+*/
+
+/*!
+ \readonly
+ \qmlproperty enumeration QtQuick::HandlerPoint::pressedButtons
+ \brief Which mouse or stylus buttons are currently pressed
+
+ \sa MouseArea::pressedButtons
+*/
+
+/*!
+ \readonly
+ \qmlproperty enumeration QtQuick::HandlerPoint::modifiers
+ \brief Which modifier keys are currently pressed
+
+ This property holds the keyboard modifiers that were pressed at the time
+ the event occurred.
+
+ \sa MouseArea::modifiers
+*/
+
+/*!
+ \readonly
+ \qmlproperty QVector2D QtQuick::HandlerPoint::velocity
+ \brief A vector representing the average speed and direction of movement
+
+ This is a velocity vector pointing in the direction of movement, in logical
+ pixels per second. It has x and y components, at least one of which will be
+ nonzero when this point is in motion. It holds the average recent velocity:
+ how fast and in which direction the event point has been moving recently.
+
+ \sa QtQuick::EventPoint::velocity, QtQuick::TouchPoint::velocity, QTouchEvent::TouchPoint::velocity
+*/
+
+/*!
+ \readonly
+ \qmlproperty qreal QtQuick::HandlerPoint::rotation
+
+ This property holds the rotation angle of the stylus on a graphics tablet
+ or the contact patch of a touchpoint on a touchscreen.
+
+ It is valid only with certain tablet stylus devices and touchscreens that
+ can measure the rotation angle. Otherwise, it will be zero.
+*/
+
+/*!
+ \readonly
+ \qmlproperty qreal QtQuick::HandlerPoint::pressure
+
+ This property tells how hard the user is pressing the stylus on a graphics
+ tablet or the finger against a touchscreen, in the range from \c 0 (no
+ measurable pressure) to \c 1.0 (maximum pressure which the device can
+ measure).
+
+ It is valid only with certain tablets and touchscreens that can measure
+ pressure. Otherwise, it will be zero.
+*/
+
+/*!
+ \readonly
+ \qmlproperty size QtQuick::HandlerPoint::ellipseDiameters
+
+ This property holds the diameters of the contact patch, if the event
+ comes from a touchpoint and the device provides this information.
+
+ A touchpoint is modeled as an elliptical area where the finger is pressed
+ against the touchscreen. (In fact, it could also be modeled as a bitmap;
+ but in that case we expect an elliptical bounding estimate to be fitted to
+ the contact patch before the event is sent.) The harder the user presses,
+ the larger the contact patch; so, these diameters provide an alternate way
+ of detecting pressure, in case the device does not include a separate
+ pressure sensor. The ellipse is centered on \l scenePosition (\l position
+ in the PointerHandler's Item's local coordinates). The \l rotation property
+ provides the rotation of the ellipse, if known. It is expected that if the
+ \l rotation is zero, the \l {QSize::height}{height} is the larger dimension
+ (the major axis), because of the usual hand position, reaching upward or
+ outward across the surface.
+
+ If the contact patch is unknown, or the device is not a touchscreen,
+ these values will be zero.
+
+ \sa QtQuick::EventTouchPoint::ellipseDiameters, QtQuick::TouchPoint::ellipseDiameters, QTouchEvent::TouchPoint::ellipseDiameters
+*/
+
+QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickhandlerpoint_p.h b/src/quick/handlers/qquickhandlerpoint_p.h
new file mode 100644
index 0000000000..44fd830af2
--- /dev/null
+++ b/src/quick/handlers/qquickhandlerpoint_p.h
@@ -0,0 +1,121 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKHANDLERPOINT_H
+#define QQUICKHANDLERPOINT_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 "qquickpointerdevicehandler_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class QQuickMultiPointHandler;
+class QQuickSinglePointHandler;
+
+class Q_QUICK_PRIVATE_EXPORT QQuickHandlerPoint {
+ Q_GADGET
+ Q_PROPERTY(int id READ id)
+ Q_PROPERTY(QPointingDeviceUniqueId uniqueId READ uniqueId)
+ Q_PROPERTY(QPointF position READ position)
+ Q_PROPERTY(QPointF scenePosition READ scenePosition)
+ Q_PROPERTY(QPointF pressPosition READ pressPosition)
+ Q_PROPERTY(QPointF scenePressPosition READ scenePressPosition)
+ Q_PROPERTY(QPointF sceneGrabPosition READ sceneGrabPosition)
+ Q_PROPERTY(Qt::MouseButtons pressedButtons READ pressedButtons)
+ Q_PROPERTY(Qt::KeyboardModifiers modifiers READ modifiers)
+ Q_PROPERTY(QVector2D velocity READ velocity)
+ Q_PROPERTY(qreal rotation READ rotation)
+ Q_PROPERTY(qreal pressure READ pressure)
+ Q_PROPERTY(QSizeF ellipseDiameters READ ellipseDiameters)
+
+public:
+ QQuickHandlerPoint();
+
+ int id() const { return m_id; }
+ Qt::MouseButtons pressedButtons() const { return m_pressedButtons; }
+ Qt::KeyboardModifiers modifiers() const { return m_pressedModifiers; }
+ QPointF pressPosition() const { return m_pressPosition; }
+ QPointF scenePressPosition() const { return m_scenePressPosition; }
+ QPointF sceneGrabPosition() const { return m_sceneGrabPosition; }
+ QPointF position() const { return m_position; }
+ QPointF scenePosition() const { return m_scenePosition; }
+ QVector2D velocity() const { return m_velocity; }
+ qreal rotation() const { return m_rotation; }
+ qreal pressure() const { return m_pressure; }
+ QSizeF ellipseDiameters() const { return m_ellipseDiameters; }
+ QPointingDeviceUniqueId uniqueId() const { return m_uniqueId; }
+ void localize(QQuickItem *item);
+
+ void reset();
+ void reset(const QQuickEventPoint *point);
+ void reset(const QVector<QQuickHandlerPoint> &points);
+
+private:
+ int m_id = 0;
+ QPointingDeviceUniqueId m_uniqueId;
+ Qt::MouseButtons m_pressedButtons = Qt::NoButton;
+ Qt::KeyboardModifiers m_pressedModifiers = Qt::NoModifier;
+ QPointF m_position;
+ QPointF m_scenePosition;
+ QPointF m_pressPosition;
+ QPointF m_scenePressPosition;
+ QPointF m_sceneGrabPosition;
+ QVector2D m_velocity;
+ qreal m_rotation = 0;
+ qreal m_pressure = 0;
+ QSizeF m_ellipseDiameters;
+ friend class QQuickMultiPointHandler;
+ friend class QQuickSinglePointHandler;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QQuickHandlerPoint)
+
+#endif // QQUICKHANDLERPOINT_H
diff --git a/src/quick/handlers/qquickhandlersmodule.cpp b/src/quick/handlers/qquickhandlersmodule.cpp
deleted file mode 100644
index c9e08fe4f2..0000000000
--- a/src/quick/handlers/qquickhandlersmodule.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtQuick 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 "qquickhandlersmodule_p.h"
-#include "qquickpointerhandler_p.h"
-#include "qquickdraghandler_p.h"
-#include "qquickpinchhandler_p.h"
-#include "qquickpointhandler_p.h"
-#include "qquicktaphandler_p.h"
-
-static void initResources()
-{
-#ifdef QT_STATIC
- Q_INIT_RESOURCE(qmake_Qt_labs_handlers);
-#endif
-}
-
-QT_BEGIN_NAMESPACE
-
-static QQmlPrivate::AutoParentResult handler_autoParent(QObject *obj, QObject *parent)
-{
- if (qmlobject_cast<QQuickItem *>(parent)) {
- QQuickPointerHandler *handler = qmlobject_cast<QQuickPointerHandler *>(obj);
- if (handler) {
- handler->setParent(parent);
- return QQmlPrivate::Parented;
- }
- }
- return QQmlPrivate::IncompatibleObject;
-}
-
-static void qt_quickhandlers_defineModule(const char *uri, int major, int minor)
-{
- QQmlPrivate::RegisterAutoParent autoparent = { 0, &handler_autoParent };
- QQmlPrivate::qmlregister(QQmlPrivate::AutoParentRegistration, &autoparent);
- qmlRegisterUncreatableType<QQuickPointerEvent>(uri, major, minor, "PointerEvent",
- QQuickPointerHandler::tr("PointerEvent is only available as a parameter of several signals in PointerHandler"));
- qmlRegisterUncreatableType<QQuickEventPoint>(uri, major, minor, "EventPoint",
- QQuickPointerHandler::tr("EventPoint is only available as a member of PointerEvent"));
- qmlRegisterUncreatableType<QQuickEventTouchPoint>(uri, major, minor, "EventTouchPoint",
- QQuickPointerHandler::tr("EventTouchPoint is only available as a member of PointerEvent"));
- qmlRegisterUncreatableType<QQuickPointerDevice>(uri, major, minor, "PointerDevice",
- QQuickPointerHandler::tr("PointerDevice is only available as a property of PointerEvent"));
- qRegisterMetaType<QPointingDeviceUniqueId>("QPointingDeviceUniqueId");
- qmlRegisterUncreatableType<QPointingDeviceUniqueId>(uri, major, minor, "PointingDeviceUniqueId",
- QQuickPointerHandler::tr("PointingDeviceUniqueId is only available as a property of PointerEvent"));
-
- qmlRegisterUncreatableType<QQuickPointerHandler>(uri,major,minor,"PointerHandler",
- QQuickPointerHandler::tr("PointerHandler is an abstract base class"));
- qmlRegisterType<QQuickPointHandler>(uri,major,minor,"PointHandler");
- qmlRegisterType<QQuickDragHandler>(uri,major,minor,"DragHandler");
- qmlRegisterUncreatableType<QQuickDragAxis>(uri, major, minor, "DragAxis",
- QQuickDragHandler::tr("DragAxis is only available as a grouped property of DragHandler"));
- qmlRegisterType<QQuickPinchHandler>(uri,major,minor,"PinchHandler");
- qmlRegisterType<QQuickTapHandler>(uri,major,minor,"TapHandler");
- qRegisterMetaType<QQuickHandlerPoint>();
-}
-
-void QQuickHandlersModule::defineModule()
-{
- initResources();
-
- const char uri[] = "Qt.labs.handlers";
- int majorVersion = 1;
- int minorVersion = 0;
-
- qt_quickhandlers_defineModule(uri, majorVersion, minorVersion);
-}
-
-QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickhoverhandler.cpp b/src/quick/handlers/qquickhoverhandler.cpp
new file mode 100644
index 0000000000..61955cad03
--- /dev/null
+++ b/src/quick/handlers/qquickhoverhandler.cpp
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 "qquickhoverhandler_p.h"
+
+QT_BEGIN_NAMESPACE
+
+Q_LOGGING_CATEGORY(lcHoverHandler, "qt.quick.handler.hover")
+
+/*!
+ \qmltype HoverHandler
+ \instantiates QQuickHoverHandler
+ \inqmlmodule QtQuick
+ \ingroup qtquick-input-handlers
+ \brief Handler for mouse and tablet hover.
+
+ HoverHandler detects a hovering cursor. Since touchscreens don't generally
+ offer hover events, in practice it detects a hovering mouse or tablet stylus.
+
+ \sa MouseArea
+*/
+
+QQuickHoverHandler::QQuickHoverHandler(QQuickItem *parent)
+ : QQuickSinglePointHandler(parent)
+{
+ // Rule out the touchscreen for now (can be overridden in QML in case a hover-detecting touchscreen exists)
+ setAcceptedDevices(static_cast<QQuickPointerDevice::DeviceType>(
+ static_cast<int>(QQuickPointerDevice::AllDevices) ^ static_cast<int>(QQuickPointerDevice::TouchScreen)));
+}
+
+QQuickHoverHandler::~QQuickHoverHandler()
+{
+ if (auto parent = parentItem())
+ QQuickItemPrivate::get(parent)->setHasHoverInChild(false);
+}
+
+void QQuickHoverHandler::componentComplete()
+{
+ parentItem()->setAcceptHoverEvents(true);
+ QQuickItemPrivate::get(parentItem())->setHasHoverInChild(true);
+}
+
+bool QQuickHoverHandler::wantsPointerEvent(QQuickPointerEvent *event)
+{
+ QQuickEventPoint *point = event->point(0);
+ if (QQuickPointerDeviceHandler::wantsPointerEvent(event) && wantsEventPoint(point) && parentContains(point)) {
+ // assume this is a mouse event, so there's only one point
+ setPointId(point->pointId());
+ return true;
+ }
+ setHovered(false);
+ return false;
+}
+
+void QQuickHoverHandler::handleEventPoint(QQuickEventPoint *point)
+{
+ setHovered(true);
+ setPassiveGrab(point);
+}
+
+void QQuickHoverHandler::setHovered(bool hovered)
+{
+ if (m_hovered != hovered) {
+ qCDebug(lcHoverHandler) << objectName() << "hovered" << m_hovered << "->" << hovered;
+ m_hovered = hovered;
+ emit hoveredChanged();
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/compressedtexture/qsgktxhandler_p.h b/src/quick/handlers/qquickhoverhandler_p.h
index 22f4db65b2..1ee2aeb7e6 100644
--- a/src/quick/scenegraph/compressedtexture/qsgktxhandler_p.h
+++ b/src/quick/handlers/qquickhoverhandler_p.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QSGKTXHANDLER_H
-#define QSGKTXHANDLER_H
+#ifndef QQUICKHOVERHANDLER_H
+#define QQUICKHOVERHANDLER_H
//
// W A R N I N G
@@ -51,28 +51,41 @@
// We mean it.
//
-#include "qsgtexturefilehandler_p.h"
+#include "qquickitem.h"
+#include "qevent.h"
+#include "qquicksinglepointhandler_p.h"
+#include <QtCore/qbasictimer.h>
QT_BEGIN_NAMESPACE
-struct KTXHeader;
-
-class QSGKtxHandler : public QSGTextureFileHandler
+class Q_AUTOTEST_EXPORT QQuickHoverHandler : public QQuickSinglePointHandler
{
+ Q_OBJECT
+ Q_PROPERTY(bool hovered READ isHovered NOTIFY hoveredChanged)
+
public:
- using QSGTextureFileHandler::QSGTextureFileHandler;
+ explicit QQuickHoverHandler(QQuickItem *parent = nullptr);
+ ~QQuickHoverHandler();
+
+ bool isHovered() const { return m_hovered; }
- static bool canRead(const QByteArray &suffix, const QByteArray &block);
+Q_SIGNALS:
+ void hoveredChanged();
- QQuickTextureFactory *read() override;
+protected:
+ void componentComplete() override;
+ bool wantsPointerEvent(QQuickPointerEvent *event) override;
+ void handleEventPoint(QQuickEventPoint *point) override;
private:
- bool checkHeader(const KTXHeader &header);
- quint32 decode(quint32 val);
+ void setHovered(bool hovered);
- bool inverseEndian = false;
+private:
+ bool m_hovered = false;
};
QT_END_NAMESPACE
-#endif // QSGKTXHANDLER_H
+QML_DECLARE_TYPE(QQuickHoverHandler)
+
+#endif // QQUICKHOVERHANDLER_H
diff --git a/src/quick/handlers/qquickmultipointhandler.cpp b/src/quick/handlers/qquickmultipointhandler.cpp
index d595b4c9b4..2f4e9d45e9 100644
--- a/src/quick/handlers/qquickmultipointhandler.cpp
+++ b/src/quick/handlers/qquickmultipointhandler.cpp
@@ -51,23 +51,17 @@ QT_BEGIN_NAMESPACE
\preliminary
\instantiates QQuickMultiPointHandler
\inherits PointerDeviceHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
\brief Abstract handler for multi-point Pointer Events.
An intermediate class (not registered as a QML type)
for any type of handler which requires and acts upon a specific number
of multiple touchpoints.
*/
-QQuickMultiPointHandler::QQuickMultiPointHandler(QObject *parent, int minimumPointCount)
+QQuickMultiPointHandler::QQuickMultiPointHandler(QQuickItem *parent, int minimumPointCount, int maximumPointCount)
: QQuickPointerDeviceHandler(parent)
, m_minimumPointCount(minimumPointCount)
- , m_maximumPointCount(-1)
- , m_pointDistanceThreshold(0)
-{
-}
-
-QQuickMultiPointHandler::~QQuickMultiPointHandler()
+ , m_maximumPointCount(maximumPointCount)
{
}
@@ -81,34 +75,99 @@ bool QQuickMultiPointHandler::wantsPointerEvent(QQuickPointerEvent *event)
return true;
#endif
- if (sameAsCurrentPoints(event))
- return true;
+ if (event->asPointerScrollEvent())
+ return false;
+ // If points were pressed or released within parentItem, reset stored state
+ // and check eligible points again. This class of handlers is intended to
+ // handle a specific number of points, so a differing number of points will
+ // usually result in different behavior. But otherwise if the currentPoints
+ // are all still there in the event, we're good to go (do not reset
+ // m_currentPoints, because we don't want to lose the pressPosition, and do
+ // not want to reshuffle the order either).
const QVector<QQuickEventPoint *> candidatePoints = eligiblePoints(event);
+ if (candidatePoints.count() != m_currentPoints.count()) {
+ m_currentPoints.clear();
+ if (active()) {
+ setActive(false);
+ m_centroid.reset();
+ emit centroidChanged();
+ }
+ } else if (hasCurrentPoints(event)) {
+ return true;
+ }
+
const bool ret = (candidatePoints.size() >= minimumPointCount() && candidatePoints.size() <= maximumPointCount());
- if (ret)
- m_currentPoints = candidatePoints;
+ if (ret) {
+ const int c = candidatePoints.count();
+ m_currentPoints.resize(c);
+ for (int i = 0; i < c; ++i) {
+ m_currentPoints[i].reset(candidatePoints[i]);
+ m_currentPoints[i].localize(parentItem());
+ }
+ } else {
+ m_currentPoints.clear();
+ }
return ret;
}
+void QQuickMultiPointHandler::handlePointerEventImpl(QQuickPointerEvent *event)
+{
+ QQuickPointerHandler::handlePointerEventImpl(event);
+ // event's points can be reordered since the previous event, which is why m_currentPoints
+ // is _not_ a shallow copy of the QQuickPointerTouchEvent::m_touchPoints vector.
+ // So we have to update our m_currentPoints instances based on the given event.
+ for (QQuickHandlerPoint &p : m_currentPoints) {
+ const QQuickEventPoint *ep = event->pointById(p.id());
+ if (ep)
+ p.reset(ep);
+ }
+ QPointF sceneGrabPos = m_centroid.sceneGrabPosition();
+ m_centroid.reset(m_currentPoints);
+ m_centroid.m_sceneGrabPosition = sceneGrabPos; // preserve as it was
+ emit centroidChanged();
+}
+
+void QQuickMultiPointHandler::onActiveChanged()
+{
+ if (active()) {
+ m_centroid.m_sceneGrabPosition = m_centroid.m_scenePosition;
+ } else {
+ // Don't call m_centroid.reset() here, because in a QML onActiveChanged
+ // callback, we'd like to see what the position _was_, what the velocity _was_, etc.
+ // (having them undefined is not useful)
+ // But pressedButtons and pressedModifiers are meant to be more real-time than those
+ // (which seems a bit inconsistent, from one side).
+ m_centroid.m_pressedButtons = Qt::NoButton;
+ m_centroid.m_pressedModifiers = Qt::NoModifier;
+ }
+}
+
+void QQuickMultiPointHandler::onGrabChanged(QQuickPointerHandler *, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *)
+{
+ // If another handler or item takes over this set of points, assume it has
+ // decided that it's the better fit for them. Don't immediately re-grab
+ // at the next opportunity. This should help to avoid grab cycles
+ // (e.g. between DragHandler and PinchHandler).
+ if (transition == QQuickEventPoint::UngrabExclusive || transition == QQuickEventPoint::CancelGrabExclusive)
+ m_currentPoints.clear();
+}
+
QVector<QQuickEventPoint *> QQuickMultiPointHandler::eligiblePoints(QQuickPointerEvent *event)
{
QVector<QQuickEventPoint *> ret;
int c = event->pointCount();
- QRectF parentBounds = parentItem()->mapRectToScene(parentItem()->boundingRect())
- .marginsAdded(QMarginsF(m_pointDistanceThreshold, m_pointDistanceThreshold, m_pointDistanceThreshold, m_pointDistanceThreshold));
// If one or more points are newly pressed or released, all non-released points are candidates for this handler.
- // In other cases however, do not steal the grab: that is, if a point has a grabber,
- // it's not a candidate for this handler.
+ // In other cases however, check whether it would be OK to steal the grab if the handler chooses to do that.
bool stealingAllowed = event->isPressEvent() || event->isReleaseEvent();
for (int i = 0; i < c; ++i) {
QQuickEventPoint *p = event->point(i);
if (!stealingAllowed) {
QObject *exclusiveGrabber = p->exclusiveGrabber();
- if (exclusiveGrabber && exclusiveGrabber != this)
+ if (exclusiveGrabber && exclusiveGrabber != this && !canGrab(p))
continue;
}
- if (p->state() != QQuickEventPoint::Released && parentBounds.contains(p->scenePosition()))
+ if (p->state() != QQuickEventPoint::Released && wantsEventPoint(p))
ret << p;
}
return ret;
@@ -122,7 +181,7 @@ QVector<QQuickEventPoint *> QQuickMultiPointHandler::eligiblePoints(QQuickPointe
If a smaller number of touchpoints are in contact with the
\l {PointerHandler::parent}{parent}, they will be ignored.
- Any ignored points are eligible to activate other Pointer Handlers that
+ Any ignored points are eligible to activate other Input Handlers that
have different constraints, on the same Item or on other Items.
The default value is 2.
@@ -148,7 +207,7 @@ void QQuickMultiPointHandler::setMinimumPointCount(int c)
chosen in the order that they are pressed, and the remaining points will
be ignored.
- Any ignored points are eligible to activate other Pointer Handlers that
+ Any ignored points are eligible to activate other Input Handlers that
have different constraints, on the same Item or on other Items.
The default value is the same as \l minimumPointCount.
@@ -162,70 +221,20 @@ void QQuickMultiPointHandler::setMaximumPointCount(int maximumPointCount)
emit maximumPointCountChanged();
}
-/*!
- \qmlproperty real MultiPointHandler::pointDistanceThreshold
-
- The margin beyond the bounds of the \l {PointerHandler::parent}{parent}
- item within which a touch point can activate this handler. For example, on
- a PinchHandler where the \l {PointerHandler::target}{target} is also the
- \c parent, it's useful to set this to a distance at least half the width
- of a typical user's finger, so that if the \c parent has been scaled down
- to a very small size, the pinch gesture is still possible.
-
- The default value is 0.
-
- \image pointDistanceThreshold.png
-*/
-void QQuickMultiPointHandler::setPointDistanceThreshold(qreal pointDistanceThreshold)
-{
- if (m_pointDistanceThreshold == pointDistanceThreshold)
- return;
-
- m_pointDistanceThreshold = pointDistanceThreshold;
- emit pointDistanceThresholdChanged();
-}
-
-bool QQuickMultiPointHandler::sameAsCurrentPoints(QQuickPointerEvent *event)
+bool QQuickMultiPointHandler::hasCurrentPoints(QQuickPointerEvent *event)
{
- bool ret = true;
- int c = event->pointCount();
- if (c != m_currentPoints.size())
+ if (event->pointCount() < m_currentPoints.size() || m_currentPoints.size() == 0)
return false;
// TODO optimize: either ensure the points are sorted,
// or use std::equal with a predicate
- for (int i = 0; ret && i < c; ++i) {
- if (event->point(i)->state() == QQuickEventPoint::Released)
+ for (const QQuickHandlerPoint &p : qAsConst(m_currentPoints)) {
+ const QQuickEventPoint *ep = event->pointById(p.id());
+ if (!ep)
+ return false;
+ if (ep->state() == QQuickEventPoint::Released)
return false;
- bool found = false;
- int pointId = event->point(i)->pointId();
- for (QQuickEventPoint *o : qAsConst(m_currentPoints))
- if (o && pointId == o->pointId())
- found = true;
- if (!found)
- ret = false;
}
- return ret;
-}
-
-// TODO make templates for these functions somehow?
-QPointF QQuickMultiPointHandler::touchPointCentroid()
-{
- QPointF ret;
- if (Q_UNLIKELY(m_currentPoints.size() == 0))
- return ret;
- for (QQuickEventPoint *point : qAsConst(m_currentPoints))
- ret += point->scenePosition();
- return ret / m_currentPoints.size();
-}
-
-QVector2D QQuickMultiPointHandler::touchPointCentroidVelocity()
-{
- QVector2D ret;
- if (Q_UNLIKELY(m_currentPoints.size() == 0))
- return ret;
- for (QQuickEventPoint *point : qAsConst(m_currentPoints))
- ret += point->velocity();
- return ret / m_currentPoints.size();
+ return true;
}
qreal QQuickMultiPointHandler::averageTouchPointDistance(const QPointF &ref)
@@ -233,8 +242,8 @@ qreal QQuickMultiPointHandler::averageTouchPointDistance(const QPointF &ref)
qreal ret = 0;
if (Q_UNLIKELY(m_currentPoints.size() == 0))
return ret;
- for (QQuickEventPoint *point : qAsConst(m_currentPoints))
- ret += QVector2D(point->scenePosition() - ref).length();
+ for (const QQuickHandlerPoint &p : m_currentPoints)
+ ret += QVector2D(p.scenePosition() - ref).length();
return ret / m_currentPoints.size();
}
@@ -244,8 +253,8 @@ qreal QQuickMultiPointHandler::averageStartingDistance(const QPointF &ref)
qreal ret = 0;
if (Q_UNLIKELY(m_currentPoints.size() == 0))
return ret;
- for (QQuickEventPoint *point : qAsConst(m_currentPoints))
- ret += QVector2D(point->sceneGrabPosition() - ref).length();
+ for (const QQuickHandlerPoint &p : m_currentPoints)
+ ret += QVector2D(p.sceneGrabPosition() - ref).length();
return ret / m_currentPoints.size();
}
@@ -253,9 +262,9 @@ QVector<QQuickMultiPointHandler::PointData> QQuickMultiPointHandler::angles(cons
{
QVector<PointData> angles;
angles.reserve(m_currentPoints.count());
- for (QQuickEventPoint *point : qAsConst(m_currentPoints)) {
- qreal angle = QLineF(ref, point->scenePosition()).angle();
- angles.append(PointData(point->pointId(), -angle)); // convert to clockwise, to be consistent with QQuickItem::rotation
+ for (const QQuickHandlerPoint &p : m_currentPoints) {
+ qreal angle = QLineF(ref, p.scenePosition()).angle();
+ angles.append(PointData(p.id(), -angle)); // convert to clockwise, to be consistent with QQuickItem::rotation
}
return angles;
}
@@ -302,7 +311,7 @@ bool QQuickMultiPointHandler::grabPoints(QVector<QQuickEventPoint *> points)
{
bool allowed = true;
for (QQuickEventPoint* point : points) {
- if (!canGrab(point)) {
+ if (point->exclusiveGrabber() != this && !canGrab(point)) {
allowed = false;
break;
}
@@ -314,4 +323,19 @@ bool QQuickMultiPointHandler::grabPoints(QVector<QQuickEventPoint *> points)
return allowed;
}
+void QQuickMultiPointHandler::moveTarget(QPointF pos)
+{
+ target()->setPosition(pos);
+ m_centroid.m_position = target()->mapFromScene(m_centroid.m_scenePosition);
+}
+
+/*!
+ \readonly
+ \qmlproperty QtQuick::HandlerPoint QtQuick::MultiPointHandler::centroid
+
+ A point exactly in the middle of the currently-pressed touch points.
+ If only one point is pressed, it's the same as that point.
+ A handler that has a \l target will normally transform it relative to this point.
+*/
+
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickmultipointhandler_p.h b/src/quick/handlers/qquickmultipointhandler_p.h
index 67e550d387..94142013cc 100644
--- a/src/quick/handlers/qquickmultipointhandler_p.h
+++ b/src/quick/handlers/qquickmultipointhandler_p.h
@@ -53,6 +53,7 @@
#include "qquickitem.h"
#include "qevent.h"
+#include "qquickhandlerpoint_p.h"
#include "qquickpointerdevicehandler_p.h"
QT_BEGIN_NAMESPACE
@@ -62,11 +63,10 @@ class Q_AUTOTEST_EXPORT QQuickMultiPointHandler : public QQuickPointerDeviceHand
Q_OBJECT
Q_PROPERTY(int minimumPointCount READ minimumPointCount WRITE setMinimumPointCount NOTIFY minimumPointCountChanged)
Q_PROPERTY(int maximumPointCount READ maximumPointCount WRITE setMaximumPointCount NOTIFY maximumPointCountChanged)
- Q_PROPERTY(qreal pointDistanceThreshold READ pointDistanceThreshold WRITE setPointDistanceThreshold NOTIFY pointDistanceThresholdChanged)
+ Q_PROPERTY(QQuickHandlerPoint centroid READ centroid NOTIFY centroidChanged)
public:
- explicit QQuickMultiPointHandler(QObject *parent = nullptr, int minimumPointCount = 2);
- ~QQuickMultiPointHandler();
+ explicit QQuickMultiPointHandler(QQuickItem *parent = nullptr, int minimumPointCount = 2, int maximumPointCount = -1);
int minimumPointCount() const { return m_minimumPointCount; }
void setMinimumPointCount(int c);
@@ -74,13 +74,13 @@ public:
int maximumPointCount() const { return m_maximumPointCount >= 0 ? m_maximumPointCount : m_minimumPointCount; }
void setMaximumPointCount(int maximumPointCount);
- qreal pointDistanceThreshold() const { return m_pointDistanceThreshold; }
- void setPointDistanceThreshold(qreal pointDistanceThreshold);
+ QQuickHandlerPoint centroid() const { return m_centroid; }
signals:
void minimumPointCountChanged();
void maximumPointCountChanged();
- void pointDistanceThresholdChanged();
+ void marginChanged();
+ void centroidChanged();
protected:
struct PointData {
@@ -91,10 +91,11 @@ protected:
};
bool wantsPointerEvent(QQuickPointerEvent *event) override;
- bool sameAsCurrentPoints(QQuickPointerEvent *event);
+ void handlePointerEventImpl(QQuickPointerEvent *event) override;
+ void onActiveChanged() override;
+ void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point) override;
+ bool hasCurrentPoints(QQuickPointerEvent *event);
QVector<QQuickEventPoint *> eligiblePoints(QQuickPointerEvent *event);
- QPointF touchPointCentroid();
- QVector2D touchPointCentroidVelocity();
qreal averageTouchPointDistance(const QPointF &ref);
qreal averageStartingDistance(const QPointF &ref);
qreal averageTouchPointAngle(const QPointF &ref);
@@ -103,12 +104,13 @@ protected:
static qreal averageAngleDelta(const QVector<PointData> &old, const QVector<PointData> &newAngles);
void acceptPoints(const QVector<QQuickEventPoint *> &points);
bool grabPoints(QVector<QQuickEventPoint *> points);
+ void moveTarget(QPointF pos);
protected:
- QVector<QQuickEventPoint *> m_currentPoints;
+ QVector<QQuickHandlerPoint> m_currentPoints;
+ QQuickHandlerPoint m_centroid;
int m_minimumPointCount;
int m_maximumPointCount;
- qreal m_pointDistanceThreshold;
};
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickpinchhandler.cpp b/src/quick/handlers/qquickpinchhandler.cpp
index 57d851ed59..e6442e7258 100644
--- a/src/quick/handlers/qquickpinchhandler.cpp
+++ b/src/quick/handlers/qquickpinchhandler.cpp
@@ -47,6 +47,7 @@
#include <QMouseEvent>
#include <QDebug>
#include <qpa/qplatformnativeinterface.h>
+#include <math.h>
QT_BEGIN_NAMESPACE
@@ -56,12 +57,12 @@ Q_LOGGING_CATEGORY(lcPinchHandler, "qt.quick.handler.pinch")
\qmltype PinchHandler
\instantiates QQuickPinchHandler
\inherits MultiPointHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
+ \ingroup qtquick-input-handlers
\brief Handler for pinch gestures.
PinchHandler is a handler that interprets a multi-finger gesture to
- interactively rotate, zoom, and drag an Item. Like other Pointer Handlers,
+ interactively rotate, zoom, and drag an Item. Like other Input Handlers,
by default it is fully functional, and manipulates its \l target,
which is the Item within which it is declared.
@@ -85,26 +86,8 @@ Q_LOGGING_CATEGORY(lcPinchHandler, "qt.quick.handler.pinch")
\sa PinchArea
*/
-QQuickPinchHandler::QQuickPinchHandler(QObject *parent)
+QQuickPinchHandler::QQuickPinchHandler(QQuickItem *parent)
: QQuickMultiPointHandler(parent, 2)
- , m_activeScale(1)
- , m_activeRotation(0)
- , m_activeTranslation(0,0)
- , m_minimumScale(-qInf())
- , m_maximumScale(qInf())
- , m_minimumRotation(-qInf())
- , m_maximumRotation(qInf())
- , m_minimumX(-qInf())
- , m_maximumX(qInf())
- , m_minimumY(-qInf())
- , m_maximumY(qInf())
- , m_pinchOrigin(PinchCenter)
- , m_startScale(1)
- , m_startRotation(0)
-{
-}
-
-QQuickPinchHandler::~QQuickPinchHandler()
{
}
@@ -169,29 +152,6 @@ void QQuickPinchHandler::setMaximumRotation(qreal maximumRotation)
}
/*!
- \qmlproperty real QtQuick::PinchHandler::pinchOrigin
-
- The point to be held in place, around which the \l target is scaled and
- rotated.
-
- \value FirstPoint
- the first touch point, wherever the first finger is pressed
- \value PinchCenter
- the centroid between all the touch points at the time when the
- PinchHandler becomes \l active
- \value TargetCenter
- the center of the \l target
-*/
-void QQuickPinchHandler::setPinchOrigin(QQuickPinchHandler::PinchOrigin pinchOrigin)
-{
- if (m_pinchOrigin == pinchOrigin)
- return;
-
- m_pinchOrigin = pinchOrigin;
- emit pinchOriginChanged();
-}
-
-/*!
\qmlproperty real QtQuick::PinchHandler::minimumX
The minimum acceptable x coordinate of the centroid
@@ -287,11 +247,11 @@ bool QQuickPinchHandler::wantsPointerEvent(QQuickPointerEvent *event)
void QQuickPinchHandler::onActiveChanged()
{
+ QQuickMultiPointHandler::onActiveChanged();
if (active()) {
m_startMatrix = QMatrix4x4();
- m_startCentroid = touchPointCentroid();
- m_startAngles = angles(m_startCentroid);
- m_startDistance = averageTouchPointDistance(m_startCentroid);
+ m_startAngles = angles(m_centroid.sceneGrabPosition());
+ m_startDistance = averageTouchPointDistance(m_centroid.sceneGrabPosition());
m_activeRotation = 0;
m_activeTranslation = QVector2D();
if (const QQuickItem *t = target()) {
@@ -304,7 +264,7 @@ void QQuickPinchHandler::onActiveChanged()
m_startMatrix.rotate(m_startRotation, 0, 0, -1);
m_startMatrix.translate(-xformOrigin);
} else {
- m_startScale = 1;
+ m_startScale = m_accumulatedScale;
m_startRotation = 0;
}
qCInfo(lcPinchHandler) << "activated with starting scale" << m_startScale << "rotation" << m_startRotation;
@@ -316,20 +276,21 @@ void QQuickPinchHandler::onActiveChanged()
void QQuickPinchHandler::handlePointerEventImpl(QQuickPointerEvent *event)
{
if (Q_UNLIKELY(lcPinchHandler().isDebugEnabled())) {
- for (QQuickEventPoint *point : qAsConst(m_currentPoints))
- qCDebug(lcPinchHandler) << point->state() << point->sceneGrabPosition() << "->" << point->scenePosition();
+ for (const QQuickHandlerPoint &p : m_currentPoints)
+ qCDebug(lcPinchHandler) << hex << p.id() << p.sceneGrabPosition() << "->" << p.scenePosition();
}
+ QQuickMultiPointHandler::handlePointerEventImpl(event);
qreal dist = 0;
#if QT_CONFIG(gestures)
if (const auto gesture = event->asPointerNativeGestureEvent()) {
+ m_centroid.reset(event->point(0));
switch (gesture->type()) {
case Qt::EndNativeGesture:
m_activeScale = 1;
m_activeRotation = 0;
m_activeTranslation = QVector2D();
- m_centroid = QPointF();
- m_centroidVelocity = QVector2D();
+ m_centroid.reset();
setActive(false);
emit updated();
return;
@@ -344,24 +305,81 @@ void QQuickPinchHandler::handlePointerEventImpl(QQuickPointerEvent *event)
return;
}
if (!active()) {
- m_centroid = gesture->point(0)->scenePosition();
setActive(true);
- m_startCentroid = m_centroid;
// Native gestures for 2-finger pinch do not allow dragging, so
// the centroid won't move during the gesture, and translation stays at zero
- m_centroidVelocity = QVector2D();
m_activeTranslation = QVector2D();
}
} else
#endif // QT_CONFIG(gestures)
{
- bool containsReleasedPoints = event->isReleaseEvent();
+ const bool containsReleasedPoints = event->isReleaseEvent();
+ QVector<QQuickEventPoint *> chosenPoints;
+ for (const QQuickHandlerPoint &p : m_currentPoints) {
+ QQuickEventPoint *ep = event->pointById(p.id());
+ chosenPoints << ep;
+ }
if (!active()) {
// Verify that at least one of the points has moved beyond threshold needed to activate the handler
- for (QQuickEventPoint *point : qAsConst(m_currentPoints)) {
- if (!containsReleasedPoints && QQuickWindowPrivate::dragOverThreshold(point) && grabPoints(m_currentPoints)) {
- setActive(true);
- break;
+ int numberOfPointsDraggedOverThreshold = 0;
+ QVector2D accumulatedDrag;
+ const QVector2D currentCentroid(m_centroid.scenePosition());
+ const QVector2D pressCentroid(m_centroid.scenePressPosition());
+
+ QStyleHints *styleHints = QGuiApplication::styleHints();
+ const int dragThreshold = styleHints->startDragDistance();
+ const int dragThresholdSquared = dragThreshold * dragThreshold;
+
+ double accumulatedCentroidDistance = 0; // Used to detect scale
+ if (event->isPressEvent())
+ m_accumulatedStartCentroidDistance = 0; // Used to detect scale
+
+ float accumulatedMovementMagnitude = 0;
+
+ for (QQuickEventPoint *point : qAsConst(chosenPoints)) {
+ if (!containsReleasedPoints) {
+ accumulatedDrag += QVector2D(point->scenePressPosition() - point->scenePosition());
+ /*
+ In order to detect a drag, we want to check if all points have moved more or
+ less in the same direction.
+
+ We then take each point, and convert the point to a local coordinate system where
+ the centroid is the origin. This is done both for the press positions and the
+ current positions. We will then have two positions:
+
+ - pressCentroidRelativePosition
+ is the start point relative to the press centroid
+ - currentCentroidRelativePosition
+ is the current point relative to the current centroid
+
+ If those two points are far enough apart, it might not be considered as a drag
+ anymore. (Note that the threshold will matched to the average of the relative
+ movement of all the points). Therefore, a big relative movement will make a big
+ contribution to the average relative movement.
+
+ The algorithm then can be described as:
+ For each point:
+ - Calculate vector pressCentroidRelativePosition (from the press centroid to the press position)
+ - Calculate vector currentCentroidRelativePosition (from the current centroid to the current position)
+ - Calculate the relative movement vector:
+
+ centroidRelativeMovement = currentCentroidRelativePosition - pressCentroidRelativePosition
+
+ and measure its magnitude. Add the magnitude to the accumulatedMovementMagnitude.
+
+ Finally, if the accumulatedMovementMagnitude is below some threshold, it means
+ that the points were stationary or they were moved in parallel (e.g. the hand
+ was moved, but the relative position between each finger remained very much
+ the same). This is then used to rule out if there is a rotation or scale.
+ */
+ QVector2D pressCentroidRelativePosition = QVector2D(point->scenePosition()) - currentCentroid;
+ QVector2D currentCentroidRelativePosition = QVector2D(point->scenePressPosition()) - pressCentroid;
+ QVector2D centroidRelativeMovement = currentCentroidRelativePosition - pressCentroidRelativePosition;
+ accumulatedMovementMagnitude += centroidRelativeMovement.length();
+
+ accumulatedCentroidDistance += pressCentroidRelativePosition.length();
+ if (event->isPressEvent())
+ m_accumulatedStartCentroidDistance += (QVector2D(point->scenePressPosition()) - pressCentroid).length();
} else {
setPassiveGrab(point);
}
@@ -369,47 +387,74 @@ void QQuickPinchHandler::handlePointerEventImpl(QQuickPointerEvent *event)
point->setAccepted(false); // don't stop propagation
setPassiveGrab(point);
}
+ if (QQuickWindowPrivate::dragOverThreshold(point))
+ ++numberOfPointsDraggedOverThreshold;
+ }
+
+ const bool requiredNumberOfPointsDraggedOverThreshold = numberOfPointsDraggedOverThreshold >= minimumPointCount() && numberOfPointsDraggedOverThreshold <= maximumPointCount();
+ accumulatedMovementMagnitude /= m_currentPoints.count();
+
+ QVector2D avgDrag = accumulatedDrag / m_currentPoints.count();
+ if (!xAxis()->enabled())
+ avgDrag.setX(0);
+ if (!yAxis()->enabled())
+ avgDrag.setY(0);
+
+ const qreal centroidMovementDelta = (currentCentroid - pressCentroid).length();
+
+ qreal distanceToCentroidDelta = qAbs(accumulatedCentroidDistance - m_accumulatedStartCentroidDistance); // Used to detect scale
+ if (numberOfPointsDraggedOverThreshold >= 1) {
+ if (requiredNumberOfPointsDraggedOverThreshold && avgDrag.lengthSquared() >= dragThresholdSquared && accumulatedMovementMagnitude < dragThreshold) {
+ // Drag
+ if (grabPoints(chosenPoints))
+ setActive(true);
+ } else if (distanceToCentroidDelta > dragThreshold) { // all points should in accumulation have been moved beyond threshold (?)
+ // Scale
+ if (grabPoints(chosenPoints))
+ setActive(true);
+ } else if (distanceToCentroidDelta < dragThreshold && (centroidMovementDelta < dragThreshold)) {
+ // Rotate
+ // Since it wasn't a scale and if we exceeded the dragthreshold, and the
+ // centroid didn't moved much, the points must have been moved around the centroid.
+ if (grabPoints(chosenPoints))
+ setActive(true);
+ }
}
if (!active())
return;
}
- // TODO check m_pinchOrigin: right now it acts like it's set to PinchCenter
- m_centroid = touchPointCentroid();
- m_centroidVelocity = touchPointCentroidVelocity();
+
// avoid mapping the minima and maxima, as they might have unmappable values
// such as -inf/+inf. Because of this we perform the bounding to min/max in local coords.
// 1. scale
- dist = averageTouchPointDistance(m_centroid);
+ dist = averageTouchPointDistance(m_centroid.scenePosition());
m_activeScale = dist / m_startDistance;
m_activeScale = qBound(m_minimumScale/m_startScale, m_activeScale, m_maximumScale/m_startScale);
// 2. rotate
- QVector<PointData> newAngles = angles(m_centroid);
+ QVector<PointData> newAngles = angles(m_centroid.scenePosition());
const qreal angleDelta = averageAngleDelta(m_startAngles, newAngles);
m_activeRotation += angleDelta;
m_startAngles = std::move(newAngles);
if (!containsReleasedPoints)
- acceptPoints(m_currentPoints);
+ acceptPoints(chosenPoints);
}
- QPointF centroidParentPos;
- QRectF bounds(m_minimumX, m_minimumY, m_maximumX - m_minimumX, m_maximumY - m_minimumY);
- if (target() && target()->parentItem()) {
- centroidParentPos = target()->parentItem()->mapFromScene(m_centroid);
- centroidParentPos = QPointF(qBound(bounds.left(), centroidParentPos.x(), bounds.right()),
- qBound(bounds.top(), centroidParentPos.y(), bounds.bottom()));
- }
const qreal totalRotation = m_startRotation + m_activeRotation;
const qreal rotation = qBound(m_minimumRotation, totalRotation, m_maximumRotation);
m_activeRotation += (rotation - totalRotation); //adjust for the potential bounding above
- const qreal scale = m_startScale * m_activeScale;
+ m_accumulatedScale = m_startScale * m_activeScale;
if (target() && target()->parentItem()) {
+ const QPointF centroidParentPos = target()->parentItem()->mapFromScene(m_centroid.scenePosition());
// 3. Drag/translate
- const QPointF centroidStartParentPos = target()->parentItem()->mapFromScene(m_startCentroid);
+ const QPointF centroidStartParentPos = target()->parentItem()->mapFromScene(m_centroid.sceneGrabPosition());
m_activeTranslation = QVector2D(centroidParentPos - centroidStartParentPos);
-
+ if (!xAxis()->enabled())
+ m_activeTranslation.setX(0);
+ if (!yAxis()->enabled())
+ m_activeTranslation.setY(0);
// apply rotation + scaling around the centroid - then apply translation.
QMatrix4x4 mat;
@@ -426,18 +471,23 @@ void QQuickPinchHandler::handlePointerEventImpl(QQuickPointerEvent *event)
QPointF pos = mat * xformOriginPoint;
pos -= xformOriginPoint;
+ if (xAxis()->enabled())
+ pos.setX(qBound(xAxis()->minimum(), pos.x(), xAxis()->maximum()));
+ if (yAxis()->enabled())
+ pos.setY(qBound(yAxis()->minimum(), pos.y(), yAxis()->maximum()));
+
target()->setPosition(pos);
target()->setRotation(rotation);
- target()->setScale(scale);
+ target()->setScale(m_accumulatedScale);
// TODO some translation inadvertently happens; try to hold the chosen pinch origin in place
} else {
- m_activeTranslation = QVector2D(m_centroid - m_startCentroid);
+ m_activeTranslation = QVector2D(m_centroid.scenePosition() - m_centroid.scenePressPosition());
}
- qCDebug(lcPinchHandler) << "centroid" << m_startCentroid << "->" << m_centroid
+ qCDebug(lcPinchHandler) << "centroid" << m_centroid.scenePressPosition() << "->" << m_centroid.scenePosition()
<< ", distance" << m_startDistance << "->" << dist
- << ", startScale" << m_startScale << "->" << scale
+ << ", startScale" << m_startScale << "->" << m_accumulatedScale
<< ", activeRotation" << m_activeRotation
<< ", rotation" << rotation
<< " from " << event->device()->type();
@@ -447,31 +497,33 @@ void QQuickPinchHandler::handlePointerEventImpl(QQuickPointerEvent *event)
/*!
\readonly
- \qmlproperty QPointF QtQuick::PinchHandler::centroid
+ \qmlproperty QtQuick::HandlerPoint QtQuick::PinchHandler::centroid
A point exactly in the middle of the currently-pressed touch points.
- If \l pinchOrigin is set to \c PinchCenter, the \l target will be rotated
- around this point.
+ The \l target will be rotated around this point.
*/
/*!
\readonly
- \qmlproperty QVector2D QtQuick::PinchHandler::centroidVelocity
+ \qmlproperty real QtQuick::PinchHandler::scale
- The average velocity of the \l centroid: a vector representing the speed
- and direction of movement of the whole group of touchpoints, in logical
- pixels per second.
+ The scale factor that will automatically be set on the \l target if it is not null.
+ Otherwise, bindings can be used to do arbitrary things with this value.
+ While the pinch gesture is being performed, it is continuously multiplied by
+ \l activeScale; after the gesture ends, it stays the same; and when the next
+ pinch gesture begins, it begins to be multiplied by activeScale again.
*/
/*!
\readonly
- \qmlproperty real QtQuick::PinchHandler::scale
-
- The scale factor. It is 1.0 when the gesture begins, increases as the
- touchpoints are spread apart, and decreases as the touchpoints are brought
- together. If \l target is not null, this will be automatically applied to its
- \l {Item::scale}{scale}. Otherwise, bindings can be used to do arbitrary
- things with this value.
+ \qmlproperty real QtQuick::PinchHandler::activeScale
+
+ The scale factor while the pinch gesture is being performed.
+ It is 1.0 when the gesture begins, increases as the touchpoints are spread
+ apart, and decreases as the touchpoints are brought together.
+ If \l target is not null, its \l {Item::scale}{scale} will be automatically
+ multiplied by this value.
+ Otherwise, bindings can be used to do arbitrary things with this value.
*/
/*!
diff --git a/src/quick/handlers/qquickpinchhandler_p.h b/src/quick/handlers/qquickpinchhandler_p.h
index 9a17971416..8f24d18166 100644
--- a/src/quick/handlers/qquickpinchhandler_p.h
+++ b/src/quick/handlers/qquickpinchhandler_p.h
@@ -55,6 +55,7 @@
#include "qevent.h"
#include "qquickmultipointhandler_p.h"
#include <private/qquicktranslate_p.h>
+#include "qquickdragaxis_p.h"
QT_BEGIN_NAMESPACE
@@ -65,25 +66,19 @@ class Q_AUTOTEST_EXPORT QQuickPinchHandler : public QQuickMultiPointHandler
Q_PROPERTY(qreal maximumScale READ maximumScale WRITE setMaximumScale NOTIFY maximumScaleChanged)
Q_PROPERTY(qreal minimumRotation READ minimumRotation WRITE setMinimumRotation NOTIFY minimumRotationChanged)
Q_PROPERTY(qreal maximumRotation READ maximumRotation WRITE setMaximumRotation NOTIFY maximumRotationChanged)
- Q_PROPERTY(PinchOrigin pinchOrigin READ pinchOrigin WRITE setPinchOrigin NOTIFY pinchOriginChanged)
- Q_PROPERTY(QPointF centroid READ centroid NOTIFY updated)
- Q_PROPERTY(QVector2D centroidVelocity READ centroidVelocity NOTIFY updated)
Q_PROPERTY(qreal scale READ scale NOTIFY updated)
+ Q_PROPERTY(qreal activeScale READ activeScale NOTIFY updated)
Q_PROPERTY(qreal rotation READ rotation NOTIFY updated)
Q_PROPERTY(QVector2D translation READ translation NOTIFY updated)
Q_PROPERTY(qreal minimumX READ minimumX WRITE setMinimumX NOTIFY minimumXChanged)
Q_PROPERTY(qreal maximumX READ maximumX WRITE setMaximumX NOTIFY maximumXChanged)
Q_PROPERTY(qreal minimumY READ minimumY WRITE setMinimumY NOTIFY minimumYChanged)
Q_PROPERTY(qreal maximumY READ maximumY WRITE setMaximumY NOTIFY maximumYChanged)
+ Q_PROPERTY(QQuickDragAxis * xAxis READ xAxis CONSTANT)
+ Q_PROPERTY(QQuickDragAxis * yAxis READ yAxis CONSTANT)
public:
- enum PinchOrigin {
- FirstPoint, PinchCenter, TargetCenter
- };
- Q_ENUM(PinchOrigin)
-
- explicit QQuickPinchHandler(QObject *parent = nullptr);
- ~QQuickPinchHandler();
+ explicit QQuickPinchHandler(QQuickItem *parent = nullptr);
qreal minimumScale() const { return m_minimumScale; }
void setMinimumScale(qreal minimumScale);
@@ -97,15 +92,10 @@ public:
qreal maximumRotation() const { return m_maximumRotation; }
void setMaximumRotation(qreal maximumRotation);
- PinchOrigin pinchOrigin() const { return m_pinchOrigin; }
- void setPinchOrigin(PinchOrigin pinchOrigin);
-
QVector2D translation() const { return m_activeTranslation; }
- qreal scale() const { return m_activeScale; }
+ qreal scale() const { return m_accumulatedScale; }
+ qreal activeScale() const { return m_activeScale; }
qreal rotation() const { return m_activeRotation; }
- QPointF centroid() const { return m_centroid; }
- QVector2D centroidVelocity() const { return m_centroidVelocity; }
-
qreal minimumX() const { return m_minimumX; }
void setMinimumX(qreal minX);
qreal maximumX() const { return m_maximumX; }
@@ -115,6 +105,9 @@ public:
qreal maximumY() const { return m_maximumY; }
void setMaximumY(qreal maxY);
+ QQuickDragAxis *xAxis() { return &m_xAxis; }
+ QQuickDragAxis *yAxis() { return &m_yAxis; }
+
signals:
void minimumScaleChanged();
void maximumScaleChanged();
@@ -124,7 +117,6 @@ signals:
void maximumXChanged();
void minimumYChanged();
void maximumYChanged();
- void pinchOriginChanged();
void updated();
protected:
@@ -134,36 +126,34 @@ protected:
private:
// properties
- qreal m_activeScale;
- qreal m_activeRotation;
- QVector2D m_activeTranslation;
- QPointF m_centroid;
- QVector2D m_centroidVelocity;
-
- qreal m_minimumScale;
- qreal m_maximumScale;
+ qreal m_activeScale = 1;
+ qreal m_accumulatedScale = 1;
+ qreal m_activeRotation = 0;
+ QVector2D m_activeTranslation = QVector2D(0, 0);
- qreal m_minimumRotation;
- qreal m_maximumRotation;
+ qreal m_minimumScale = -qInf();
+ qreal m_maximumScale = qInf();
- qreal m_minimumX;
- qreal m_maximumX;
- qreal m_minimumY;
- qreal m_maximumY;
+ qreal m_minimumRotation = -qInf();
+ qreal m_maximumRotation = qInf();
- PinchOrigin m_pinchOrigin;
+ qreal m_minimumX = -qInf();
+ qreal m_maximumX = qInf();
+ qreal m_minimumY = -qInf();
+ qreal m_maximumY = qInf();
+ QQuickDragAxis m_xAxis;
+ QQuickDragAxis m_yAxis;
// internal
- qreal m_startScale;
- qreal m_startRotation;
- QPointF m_startCentroid;
- qreal m_startDistance;
+ qreal m_startScale = 1;
+ qreal m_startRotation = 0;
+ qreal m_startDistance = 0;
QPointF m_startPos;
+ qreal m_accumulatedStartCentroidDistance = 0;
QVector<PointData> m_startAngles;
QMatrix4x4 m_startMatrix;
QQuickMatrix4x4 m_transform;
-
};
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickpointerdevicehandler.cpp b/src/quick/handlers/qquickpointerdevicehandler.cpp
index 06831613b6..096fad2071 100644
--- a/src/quick/handlers/qquickpointerdevicehandler.cpp
+++ b/src/quick/handlers/qquickpointerdevicehandler.cpp
@@ -37,7 +37,7 @@
**
****************************************************************************/
-#include "qquickpointerdevicehandler_p.h"
+#include "qquickpointerdevicehandler_p_p.h"
#include <private/qquickitem_p.h>
#include <QMouseEvent>
#include <QDebug>
@@ -51,27 +51,87 @@ QT_BEGIN_NAMESPACE
\preliminary
\instantiates QQuickPointerDeviceHandler
\inherits PointerHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
\brief Abstract handler for pointer events with device-specific constraints.
An intermediate class (not registered as a QML type) for handlers which
allow filtering based on device type, pointer type, or keyboard modifiers.
*/
-QQuickPointerDeviceHandler::QQuickPointerDeviceHandler(QObject *parent)
- : QQuickPointerHandler(parent)
- , m_acceptedDevices(QQuickPointerDevice::AllDevices)
- , m_acceptedPointerTypes(QQuickPointerDevice::AllPointerTypes)
- , m_acceptedModifiers(Qt::KeyboardModifierMask)
+QQuickPointerDeviceHandler::QQuickPointerDeviceHandler(QQuickItem *parent)
+ : QQuickPointerHandler(*(new QQuickPointerDeviceHandlerPrivate), parent)
{
}
-QQuickPointerDeviceHandler::~QQuickPointerDeviceHandler()
+QQuickPointerDeviceHandler::QQuickPointerDeviceHandler(QQuickPointerDeviceHandlerPrivate &dd, QQuickItem *parent)
+ : QQuickPointerHandler(dd, parent)
{
}
+QQuickPointerDevice::DeviceTypes QQuickPointerDeviceHandler::acceptedDevices() const
+{
+ Q_D(const QQuickPointerDeviceHandler);
+ return d->acceptedDevices;
+}
+
+QQuickPointerDevice::PointerTypes QQuickPointerDeviceHandler::acceptedPointerTypes() const
+{
+ Q_D(const QQuickPointerDeviceHandler);
+ return d->acceptedPointerTypes;
+}
+
+/*!
+ \qmlproperty flags QtQuick::PointerDeviceHandler::acceptedButtons
+
+ The mouse buttons which can activate this Pointer Handler.
+
+ By default, this property is set to \l {QtQuick::MouseEvent::button} {Qt.LeftButton}.
+ It can be set to an OR combination of mouse buttons, and will ignore events
+ from other buttons.
+
+ For example, a control could be made to respond to left and right clicks
+ in different ways, with two handlers:
+
+ \qml
+ Item {
+ TapHandler {
+ onTapped: console.log("left clicked")
+ }
+ TapHandler {
+ acceptedButtons: Qt.RightButton
+ onTapped: console.log("right clicked")
+ }
+ }
+ \endqml
+
+ \note Tapping on a touchscreen or tapping the stylus on a graphics tablet
+ emulates clicking the left mouse button. This behavior can be altered via
+ \l {PointerDeviceHandler::acceptedDevices}{acceptedDevices} or
+ \l {PointerDeviceHandler::acceptedPointerTypes}{acceptedPointerTypes}.
+*/
+Qt::MouseButtons QQuickPointerDeviceHandler::acceptedButtons() const
+{
+ Q_D(const QQuickPointerDeviceHandler);
+ return d->acceptedButtons;
+}
+
+void QQuickPointerDeviceHandler::setAcceptedButtons(Qt::MouseButtons buttons)
+{
+ Q_D(QQuickPointerDeviceHandler);
+ if (d->acceptedButtons == buttons)
+ return;
+
+ d->acceptedButtons = buttons;
+ emit acceptedButtonsChanged();
+}
+
+Qt::KeyboardModifiers QQuickPointerDeviceHandler::acceptedModifiers() const
+{
+ Q_D(const QQuickPointerDeviceHandler);
+ return d->acceptedModifiers;
+}
+
/*!
- \qmlproperty int PointerDeviceHandler::acceptedDevices
+ \qmlproperty flags PointerDeviceHandler::acceptedDevices
The types of pointing devices that can activate this Pointer Handler.
@@ -98,15 +158,16 @@ QQuickPointerDeviceHandler::~QQuickPointerDeviceHandler()
*/
void QQuickPointerDeviceHandler::setAcceptedDevices(QQuickPointerDevice::DeviceTypes acceptedDevices)
{
- if (m_acceptedDevices == acceptedDevices)
+ Q_D(QQuickPointerDeviceHandler);
+ if (d->acceptedDevices == acceptedDevices)
return;
- m_acceptedDevices = acceptedDevices;
+ d->acceptedDevices = acceptedDevices;
emit acceptedDevicesChanged();
}
/*!
- \qmlproperty int PointerDeviceHandler::acceptedPointerTypes
+ \qmlproperty flags PointerDeviceHandler::acceptedPointerTypes
The types of pointing instruments (finger, stylus, eraser, etc.)
that can activate this Pointer Handler.
@@ -136,15 +197,16 @@ void QQuickPointerDeviceHandler::setAcceptedDevices(QQuickPointerDevice::DeviceT
*/
void QQuickPointerDeviceHandler::setAcceptedPointerTypes(QQuickPointerDevice::PointerTypes acceptedPointerTypes)
{
- if (m_acceptedPointerTypes == acceptedPointerTypes)
+ Q_D(QQuickPointerDeviceHandler);
+ if (d->acceptedPointerTypes == acceptedPointerTypes)
return;
- m_acceptedPointerTypes = acceptedPointerTypes;
+ d->acceptedPointerTypes = acceptedPointerTypes;
emit acceptedPointerTypesChanged();
}
/*!
- \qmlproperty int PointerDeviceHandler::acceptedModifiers
+ \qmlproperty flags PointerDeviceHandler::acceptedModifiers
If this property is set, it will require the given keyboard modifiers to
be pressed in order to react to pointer events, and otherwise ignore them.
@@ -171,26 +233,28 @@ void QQuickPointerDeviceHandler::setAcceptedPointerTypes(QQuickPointerDevice::Po
*/
void QQuickPointerDeviceHandler::setAcceptedModifiers(Qt::KeyboardModifiers acceptedModifiers)
{
- if (m_acceptedModifiers == acceptedModifiers)
+ Q_D(QQuickPointerDeviceHandler);
+ if (d->acceptedModifiers == acceptedModifiers)
return;
- m_acceptedModifiers = acceptedModifiers;
+ d->acceptedModifiers = acceptedModifiers;
emit acceptedModifiersChanged();
}
bool QQuickPointerDeviceHandler::wantsPointerEvent(QQuickPointerEvent *event)
{
+ Q_D(QQuickPointerDeviceHandler);
if (!QQuickPointerHandler::wantsPointerEvent(event))
return false;
qCDebug(lcPointerHandlerDispatch) << objectName()
- << "checking device type" << m_acceptedDevices
- << "pointer type" << m_acceptedPointerTypes
- << "modifiers" << m_acceptedModifiers;
- if ((event->device()->type() & m_acceptedDevices) == 0)
+ << "checking device type" << d->acceptedDevices
+ << "pointer type" << d->acceptedPointerTypes
+ << "modifiers" << d->acceptedModifiers;
+ if ((event->device()->type() & d->acceptedDevices) == 0)
return false;
- if ((event->device()->pointerType() & m_acceptedPointerTypes) == 0)
+ if ((event->device()->pointerType() & d->acceptedPointerTypes) == 0)
return false;
- if (m_acceptedModifiers != Qt::KeyboardModifierMask && event->modifiers() != m_acceptedModifiers)
+ if (d->acceptedModifiers != Qt::KeyboardModifierMask && event->modifiers() != d->acceptedModifiers)
return false;
return true;
}
diff --git a/src/quick/handlers/qquickpointerdevicehandler_p.h b/src/quick/handlers/qquickpointerdevicehandler_p.h
index 1638604ea7..82b24369d3 100644
--- a/src/quick/handlers/qquickpointerdevicehandler_p.h
+++ b/src/quick/handlers/qquickpointerdevicehandler_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 QtQuick module of the Qt Toolkit.
@@ -36,6 +36,7 @@
** $QT_END_LICENSE$
**
****************************************************************************/
+#include "qquickpointerhandler_p.h"
#ifndef QQUICKPOINTERDEVICEHANDLER_H
#define QQUICKPOINTERDEVICEHANDLER_H
@@ -51,42 +52,44 @@
// We mean it.
//
-#include "qquickpointerhandler_p.h"
-
QT_BEGIN_NAMESPACE
+class QQuickPointerDeviceHandlerPrivate;
+
class Q_AUTOTEST_EXPORT QQuickPointerDeviceHandler : public QQuickPointerHandler
{
Q_OBJECT
Q_PROPERTY(QQuickPointerDevice::DeviceTypes acceptedDevices READ acceptedDevices WRITE setAcceptedDevices NOTIFY acceptedDevicesChanged)
Q_PROPERTY(QQuickPointerDevice::PointerTypes acceptedPointerTypes READ acceptedPointerTypes WRITE setAcceptedPointerTypes NOTIFY acceptedPointerTypesChanged)
+ Q_PROPERTY(Qt::MouseButtons acceptedButtons READ acceptedButtons WRITE setAcceptedButtons NOTIFY acceptedButtonsChanged)
Q_PROPERTY(Qt::KeyboardModifiers acceptedModifiers READ acceptedModifiers WRITE setAcceptedModifiers NOTIFY acceptedModifiersChanged)
public:
- explicit QQuickPointerDeviceHandler(QObject *parent = nullptr);
- ~QQuickPointerDeviceHandler();
+ explicit QQuickPointerDeviceHandler(QQuickItem *parent = nullptr);
- QQuickPointerDevice::DeviceTypes acceptedDevices() const { return m_acceptedDevices; }
- QQuickPointerDevice::PointerTypes acceptedPointerTypes() const { return m_acceptedPointerTypes; }
- Qt::KeyboardModifiers acceptedModifiers() const { return m_acceptedModifiers; }
+ QQuickPointerDevice::DeviceTypes acceptedDevices() const;
+ QQuickPointerDevice::PointerTypes acceptedPointerTypes() const;
+ Qt::MouseButtons acceptedButtons() const;
+ Qt::KeyboardModifiers acceptedModifiers() const;
-public slots:
+public Q_SLOTS:
void setAcceptedDevices(QQuickPointerDevice::DeviceTypes acceptedDevices);
void setAcceptedPointerTypes(QQuickPointerDevice::PointerTypes acceptedPointerTypes);
+ void setAcceptedButtons(Qt::MouseButtons buttons);
void setAcceptedModifiers(Qt::KeyboardModifiers acceptedModifiers);
Q_SIGNALS:
void acceptedDevicesChanged();
void acceptedPointerTypesChanged();
+ void acceptedButtonsChanged();
void acceptedModifiersChanged();
protected:
+ QQuickPointerDeviceHandler(QQuickPointerDeviceHandlerPrivate &dd, QQuickItem *parent = nullptr);
+
bool wantsPointerEvent(QQuickPointerEvent *event) override;
-protected:
- QQuickPointerDevice::DeviceTypes m_acceptedDevices;
- QQuickPointerDevice::PointerTypes m_acceptedPointerTypes;
- Qt::KeyboardModifiers m_acceptedModifiers;
+ Q_DECLARE_PRIVATE(QQuickPointerDeviceHandler)
};
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickpointerdevicehandler_p_p.h b/src/quick/handlers/qquickpointerdevicehandler_p_p.h
new file mode 100644
index 0000000000..6a950590f3
--- /dev/null
+++ b/src/quick/handlers/qquickpointerdevicehandler_p_p.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKPOINTERDEVICEHANDLER_P_H
+#define QQUICKPOINTERDEVICEHANDLER_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 "qquickpointerdevicehandler_p.h"
+#include "qquickpointerhandler_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+class Q_AUTOTEST_EXPORT QQuickPointerDeviceHandlerPrivate : public QQuickPointerHandlerPrivate
+{
+ Q_DECLARE_PUBLIC(QQuickPointerDeviceHandler)
+
+public:
+ static QQuickPointerDeviceHandlerPrivate* get(QQuickPointerDeviceHandler *q) { return q->d_func(); }
+ static const QQuickPointerDeviceHandlerPrivate* get(const QQuickPointerDeviceHandler *q) { return q->d_func(); }
+
+ QQuickPointerDevice::DeviceTypes acceptedDevices = QQuickPointerDevice::AllDevices;
+ QQuickPointerDevice::PointerTypes acceptedPointerTypes = QQuickPointerDevice::AllPointerTypes;
+ Qt::MouseButtons acceptedButtons = Qt::LeftButton;
+ Qt::KeyboardModifiers acceptedModifiers = Qt::KeyboardModifierMask;
+};
+
+QT_END_NAMESPACE
+
+#endif // QQUICKPOINTERDEVICEHANDLER_P_H
diff --git a/src/quick/handlers/qquickpointerhandler.cpp b/src/quick/handlers/qquickpointerhandler.cpp
index e5b1dc8985..12c06aa179 100644
--- a/src/quick/handlers/qquickpointerhandler.cpp
+++ b/src/quick/handlers/qquickpointerhandler.cpp
@@ -38,6 +38,8 @@
****************************************************************************/
#include "qquickpointerhandler_p.h"
+#include "qquickpointerhandler_p_p.h"
+#include <QtQuick/private/qquickitem_p.h>
QT_BEGIN_NAMESPACE
@@ -51,24 +53,20 @@ Q_LOGGING_CATEGORY(lcPointerHandlerActive, "qt.quick.handler.active")
\since 5.10
\preliminary
\instantiates QQuickPointerHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
\brief Abstract handler for pointer events.
- PointerHandler is the base class handler (not registered as a QML type) for
- pointer events without regard to source (touch, mouse or graphics tablet).
+ PointerHandler is the base class Input Handler (not registered as a QML type) for
+ events from any kind of pointing device (touch, mouse or graphics tablet).
*/
-QQuickPointerHandler::QQuickPointerHandler(QObject *parent)
- : QObject(parent)
- , m_currentEvent(nullptr)
- , m_target(nullptr)
- , m_enabled(true)
- , m_active(false)
- , m_targetExplicitlySet(false)
- , m_hadKeepMouseGrab(false)
- , m_hadKeepTouchGrab(false)
- , m_grabPermissions(CanTakeOverFromItems | CanTakeOverFromHandlersOfDifferentType | ApprovesTakeOverByAnything)
+QQuickPointerHandler::QQuickPointerHandler(QQuickItem *parent)
+ : QObject(*(new QQuickPointerHandlerPrivate), parent)
+{
+}
+
+QQuickPointerHandler::QQuickPointerHandler(QQuickPointerHandlerPrivate &dd, QQuickItem *parent)
+ : QObject(dd, parent)
{
}
@@ -82,25 +80,58 @@ QQuickPointerHandler::~QQuickPointerHandler()
}
/*!
+ \qmlproperty real PointerHandler::margin
+
+ The margin beyond the bounds of the \l {PointerHandler::parent}{parent}
+ item within which an event point can activate this handler. For example, on
+ a PinchHandler where the \l {PointerHandler::target}{target} is also the
+ \c parent, it's useful to set this to a distance at least half the width
+ of a typical user's finger, so that if the \c parent has been scaled down
+ to a very small size, the pinch gesture is still possible. Or, if a
+ TapHandler-based button is placed near the screen edge, it can be used
+ to comply with Fitts's Law: react to mouse clicks at the screen edge
+ even though the button is visually spaced away from the edge by a few pixels.
+
+ The default value is 0.
+
+ \image pointerHandlerMargin.png
+*/
+qreal QQuickPointerHandler::margin() const
+{
+ Q_D(const QQuickPointerHandler);
+ return d->m_margin;
+}
+
+void QQuickPointerHandler::setMargin(qreal pointDistanceThreshold)
+{
+ Q_D(QQuickPointerHandler);
+ if (d->m_margin == pointDistanceThreshold)
+ return;
+
+ d->m_margin = pointDistanceThreshold;
+ emit marginChanged();
+}
+
+/*!
Notification that the grab has changed in some way which is relevant to this handler.
- The \a grabber (subject) will be the PointerHandler whose state is changing,
+ The \a grabber (subject) will be the Input Handler whose state is changing,
or null if the state change regards an Item.
- The \a stateChange (verb) tells what happened.
+ The \a transition (verb) tells what happened.
The \a point (object) is the point that was grabbed or ungrabbed.
EventPoint has the sole responsibility to call this function.
- The PointerHandler must react in whatever way is appropriate, and must
+ The Input Handler must react in whatever way is appropriate, and must
emit the relevant signals (for the benefit of QML code).
A subclass is allowed to override this virtual function, but must always
call its parent class's implementation in addition to (usually after)
whatever custom behavior it implements.
*/
-void QQuickPointerHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point)
+void QQuickPointerHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point)
{
- qCDebug(lcPointerHandlerGrab) << point << stateChange << grabber;
+ qCDebug(lcPointerHandlerGrab) << point << transition << grabber;
Q_ASSERT(point);
if (grabber == this) {
bool wasCanceled = false;
- switch (stateChange) {
+ switch (transition) {
case QQuickEventPoint::GrabPassive:
case QQuickEventPoint::GrabExclusive:
break;
@@ -113,8 +144,9 @@ void QQuickPointerHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEv
setActive(false);
point->setAccepted(false);
if (auto par = parentItem()) {
- par->setKeepMouseGrab(m_hadKeepMouseGrab);
- par->setKeepTouchGrab(m_hadKeepTouchGrab);
+ Q_D(const QQuickPointerHandler);
+ par->setKeepMouseGrab(d->hadKeepMouseGrab);
+ par->setKeepTouchGrab(d->hadKeepTouchGrab);
}
break;
case QQuickEventPoint::OverrideGrabPassive:
@@ -124,19 +156,17 @@ void QQuickPointerHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEv
}
if (wasCanceled)
emit canceled(point);
- else
- emit grabChanged(point);
+ emit grabChanged(transition, point);
}
}
/*!
- \internal
Acquire or give up a passive grab of the given \a point, according to the \a grab state.
- Unlike the exclusive grab, multiple PointerHandlers can have passive grabs
+ Unlike the exclusive grab, multiple Input Handlers can have passive grabs
simultaneously. This means that each of them will receive further events
- when the \a point moves, and when it is finally released. Typically a
- PointerHandler should acquire a passive grab as soon as a point is pressed,
+ when the \a point moves, and when it is finally released. Typically an
+ Input Handler should acquire a passive grab as soon as a point is pressed,
if the handler's constraints do not clearly rule out any interest in that
point. For example, DragHandler needs a passive grab in order to watch the
movement of a point to see whether it will be dragged past the drag
@@ -181,19 +211,20 @@ bool QQuickPointerHandler::canGrab(QQuickEventPoint *point)
*/
bool QQuickPointerHandler::approveGrabTransition(QQuickEventPoint *point, QObject *proposedGrabber)
{
+ Q_D(const QQuickPointerHandler);
bool allowed = false;
if (proposedGrabber == this) {
QObject* existingGrabber = point->exclusiveGrabber();
- allowed = (existingGrabber == nullptr) || ((m_grabPermissions & CanTakeOverFromAnything) == CanTakeOverFromAnything);
+ allowed = (existingGrabber == nullptr) || ((d->grabPermissions & CanTakeOverFromAnything) == CanTakeOverFromAnything);
if (existingGrabber) {
if (QQuickPointerHandler *existingPhGrabber = point->grabberPointerHandler()) {
- if (!allowed && (m_grabPermissions & CanTakeOverFromHandlersOfDifferentType) &&
+ if (!allowed && (d->grabPermissions & CanTakeOverFromHandlersOfDifferentType) &&
existingPhGrabber->metaObject()->className() != metaObject()->className())
allowed = true;
- if (!allowed && (m_grabPermissions & CanTakeOverFromHandlersOfSameType) &&
+ if (!allowed && (d->grabPermissions & CanTakeOverFromHandlersOfSameType) &&
existingPhGrabber->metaObject()->className() == metaObject()->className())
allowed = true;
- } else if ((m_grabPermissions & CanTakeOverFromItems)) {
+ } else if ((d->grabPermissions & CanTakeOverFromItems)) {
QQuickItem * existingItemGrabber = point->grabberItem();
if (existingItemGrabber && !((existingItemGrabber->keepMouseGrab() && point->pointerEvent()->asPointerMouseEvent()) ||
(existingItemGrabber->keepTouchGrab() && point->pointerEvent()->asPointerTouchEvent())))
@@ -203,18 +234,18 @@ bool QQuickPointerHandler::approveGrabTransition(QQuickEventPoint *point, QObjec
} else {
// proposedGrabber is different: that means this instance will lose its grab
if (proposedGrabber) {
- if ((m_grabPermissions & ApprovesTakeOverByAnything) == ApprovesTakeOverByAnything)
+ if ((d->grabPermissions & ApprovesTakeOverByAnything) == ApprovesTakeOverByAnything)
allowed = true;
- if (!allowed && (m_grabPermissions & ApprovesTakeOverByHandlersOfDifferentType) &&
+ if (!allowed && (d->grabPermissions & ApprovesTakeOverByHandlersOfDifferentType) &&
proposedGrabber->metaObject()->className() != metaObject()->className())
allowed = true;
- if (!allowed && (m_grabPermissions & ApprovesTakeOverByHandlersOfSameType) &&
+ if (!allowed && (d->grabPermissions & ApprovesTakeOverByHandlersOfSameType) &&
proposedGrabber->metaObject()->className() == metaObject()->className())
allowed = true;
- if (!allowed && (m_grabPermissions & ApprovesTakeOverByItems) && proposedGrabber->inherits("QQuickItem"))
+ if (!allowed && (d->grabPermissions & ApprovesTakeOverByItems) && proposedGrabber->inherits("QQuickItem"))
allowed = true;
} else {
- if (!allowed && (m_grabPermissions & ApprovesCancellation))
+ if (!allowed && (d->grabPermissions & ApprovesCancellation))
allowed = true;
}
}
@@ -225,23 +256,49 @@ bool QQuickPointerHandler::approveGrabTransition(QQuickEventPoint *point, QObjec
}
/*!
- \qmlproperty bool QtQuick::PointerHandler::grabPermission
+ \qmlproperty flags QtQuick::PointerHandler::grabPermissions
This property specifies the permissions when this handler's logic decides
to take over the exclusive grab, or when it is asked to approve grab
takeover or cancellation by another handler.
+ \value PointerHandler.TakeOverForbidden
+ This handler neither takes from nor gives grab permission to any type of Item or Handler.
+ \value PointerHandler.CanTakeOverFromHandlersOfSameType
+ This handler can take the exclusive grab from another handler of the same class.
+ \value PointerHandler.CanTakeOverFromHandlersOfDifferentType
+ This handler can take the exclusive grab from any kind of handler.
+ \value PointerHandler.CanTakeOverFromAnything
+ This handler can take the exclusive grab from any type of Item or Handler.
+ \value PointerHandler.ApprovesTakeOverByHandlersOfSameType
+ This handler gives permission for another handler of the same class to take the grab.
+ \value PointerHandler.ApprovesTakeOverByHandlersOfDifferentType
+ This handler gives permission for any kind of handler to take the grab.
+ \value PointerHandler.ApprovesTakeOverByItems
+ This handler gives permission for any kind of Item to take the grab.
+ \value PointerHandler.ApprovesCancellation
+ This handler will allow its grab to be set to null.
+ \value PointerHandler.ApprovesTakeOverByAnything
+ This handler gives permission for any any type of Item or Handler to take the grab.
+
The default is
- \c {CanTakeOverFromItems | CanTakeOverFromHandlersOfDifferentType | ApprovesTakeOverByAnything}
+ \c {PointerHandler.CanTakeOverFromItems | PointerHandler.CanTakeOverFromHandlersOfDifferentType | PointerHandler.ApprovesTakeOverByAnything}
which allows most takeover scenarios but avoids e.g. two PinchHandlers fighting
over the same touchpoints.
*/
+QQuickPointerHandler::GrabPermissions QQuickPointerHandler::grabPermissions() const
+{
+ Q_D(const QQuickPointerHandler);
+ return static_cast<QQuickPointerHandler::GrabPermissions>(d->grabPermissions);
+}
+
void QQuickPointerHandler::setGrabPermissions(GrabPermissions grabPermission)
{
- if (m_grabPermissions == grabPermission)
+ Q_D(QQuickPointerHandler);
+ if (d->grabPermissions == grabPermission)
return;
- m_grabPermissions = grabPermission;
+ d->grabPermissions = grabPermission;
emit grabPermissionChanged();
}
@@ -253,8 +310,13 @@ void QQuickPointerHandler::componentComplete()
{
}
+QQuickPointerEvent *QQuickPointerHandler::currentEvent()
+{
+ Q_D(const QQuickPointerHandler);
+ return d->currentEvent;
+}
+
/*!
- \internal
Acquire or give up the exclusive grab of the given \a point, according to
the \a grab state, and subject to the rules: canGrab(), and the rule not to
relinquish another handler's grab. Returns true if permission is granted,
@@ -284,7 +346,6 @@ bool QQuickPointerHandler::setExclusiveGrab(QQuickEventPoint *point, bool grab)
}
/*!
- \internal
Cancel any existing grab of the given \a point.
*/
void QQuickPointerHandler::cancelAllGrabs(QQuickEventPoint *point)
@@ -300,9 +361,19 @@ QPointF QQuickPointerHandler::eventPos(const QQuickEventPoint *point) const
bool QQuickPointerHandler::parentContains(const QQuickEventPoint *point) const
{
- if (point) {
- if (QQuickItem *par = parentItem())
- return par->contains(par->mapFromScene(point->scenePosition()));
+ if (!point)
+ return false;
+ if (QQuickItem *par = parentItem()) {
+ if (par->window()) {
+ QPoint screenPosition = par->window()->mapToGlobal(point->scenePosition().toPoint());
+ if (!par->window()->geometry().contains(screenPosition))
+ return false;
+ }
+ QPointF p = par->mapFromScene(point->scenePosition());
+ qreal m = margin();
+ if (m > 0)
+ return p.x() >= -m && p.y() >= -m && p.x() <= par->width() + m && p.y() <= par->height() + m;
+ return par->contains(p);
}
return false;
}
@@ -313,15 +384,28 @@ bool QQuickPointerHandler::parentContains(const QQuickEventPoint *point) const
If a PointerHandler is disabled, it will reject all events
and no signals will be emitted.
*/
+bool QQuickPointerHandler::enabled() const
+{
+ Q_D(const QQuickPointerHandler);
+ return d->enabled;
+}
+
void QQuickPointerHandler::setEnabled(bool enabled)
{
- if (m_enabled == enabled)
+ Q_D(QQuickPointerHandler);
+ if (d->enabled == enabled)
return;
- m_enabled = enabled;
+ d->enabled = enabled;
emit enabledChanged();
}
+bool QQuickPointerHandler::active() const
+{
+ Q_D(const QQuickPointerHandler);
+ return d->active;
+}
+
/*!
\qmlproperty Item QtQuick::PointerHandler::target
@@ -335,21 +419,28 @@ void QQuickPointerHandler::setEnabled(bool enabled)
*/
void QQuickPointerHandler::setTarget(QQuickItem *target)
{
- m_targetExplicitlySet = true;
- if (m_target == target)
+ Q_D(QQuickPointerHandler);
+ d->targetExplicitlySet = true;
+ if (d->target == target)
return;
- QQuickItem *oldTarget = m_target;
- m_target = target;
+ QQuickItem *oldTarget = d->target;
+ d->target = target;
onTargetChanged(oldTarget);
emit targetChanged();
}
+QQuickItem *QQuickPointerHandler::parentItem() const
+{
+ return static_cast<QQuickItem *>(QObject::parent());
+}
+
QQuickItem *QQuickPointerHandler::target() const
{
- if (!m_targetExplicitlySet)
+ Q_D(const QQuickPointerHandler);
+ if (!d->targetExplicitlySet)
return parentItem();
- return m_target;
+ return d->target;
}
void QQuickPointerHandler::handlePointerEvent(QQuickPointerEvent *event)
@@ -374,15 +465,24 @@ void QQuickPointerHandler::handlePointerEvent(QQuickPointerEvent *event)
bool QQuickPointerHandler::wantsPointerEvent(QQuickPointerEvent *event)
{
+ Q_D(const QQuickPointerHandler);
Q_UNUSED(event)
- return m_enabled;
+ return d->enabled;
+}
+
+bool QQuickPointerHandler::wantsEventPoint(QQuickEventPoint *point)
+{
+ bool ret = point->exclusiveGrabber() == this || point->passiveGrabbers().contains(this) || parentContains(point);
+ qCDebug(lcPointerHandlerDispatch) << hex << point->pointId() << "@" << point->scenePosition()
+ << metaObject()->className() << objectName() << ret;
+ return ret;
}
/*!
\readonly
\qmlproperty bool QtQuick::PointerHandler::active
- This holds true whenever this PointerHandler has taken sole responsibility
+ This holds true whenever this Input Handler has taken sole responsibility
for handing one or more EventPoints, by successfully taking an exclusive
grab of those points. This means that it is keeping its properties
up-to-date according to the movements of those Event Points and actively
@@ -390,9 +490,10 @@ bool QQuickPointerHandler::wantsPointerEvent(QQuickPointerEvent *event)
*/
void QQuickPointerHandler::setActive(bool active)
{
- if (m_active != active) {
- qCDebug(lcPointerHandlerActive) << this << m_active << "->" << active;
- m_active = active;
+ Q_D(QQuickPointerHandler);
+ if (d->active != active) {
+ qCDebug(lcPointerHandlerActive) << this << d->active << "->" << active;
+ d->active = active;
onActiveChanged();
emit activeChanged();
}
@@ -400,7 +501,8 @@ void QQuickPointerHandler::setActive(bool active)
void QQuickPointerHandler::handlePointerEventImpl(QQuickPointerEvent *event)
{
- m_currentEvent = event;
+ Q_D(QQuickPointerHandler);
+ d->currentEvent = event;
}
/*!
@@ -417,10 +519,13 @@ void QQuickPointerHandler::handlePointerEventImpl(QQuickPointerEvent *event)
*/
/*!
- \qmlsignal QtQuick::PointerHandler::grabChanged(EventPoint point)
+ \qmlsignal QtQuick::PointerHandler::grabChanged(GrabTransition transition, EventPoint point)
- This signal is emitted when this handler has acquired or relinquished a
- passive or exclusive grab of the given \a point.
+ This signal is emitted when the grab has changed in some way which is
+ relevant to this handler.
+
+ The \a transition (verb) tells what happened.
+ The \a point (object) is the point that was grabbed or ungrabbed.
*/
/*!
@@ -430,4 +535,16 @@ void QQuickPointerHandler::handlePointerEventImpl(QQuickPointerEvent *event)
emitted when the grab is stolen by a different Pointer Handler or Item.
*/
+QQuickPointerHandlerPrivate::QQuickPointerHandlerPrivate()
+ : grabPermissions(QQuickPointerHandler::CanTakeOverFromItems |
+ QQuickPointerHandler::CanTakeOverFromHandlersOfDifferentType |
+ QQuickPointerHandler::ApprovesTakeOverByAnything)
+ , enabled(true)
+ , active(false)
+ , targetExplicitlySet(false)
+ , hadKeepMouseGrab(false)
+ , hadKeepTouchGrab(false)
+{
+}
+
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquickpointerhandler_p.h b/src/quick/handlers/qquickpointerhandler_p.h
index e2bcce8fc9..c600e42491 100644
--- a/src/quick/handlers/qquickpointerhandler_p.h
+++ b/src/quick/handlers/qquickpointerhandler_p.h
@@ -51,8 +51,6 @@
// We mean it.
//
-#include "qevent.h"
-
#include <QtQuick/private/qquickevents_p_p.h>
#include <QtQuick/private/qquickitem_p.h>
@@ -60,6 +58,8 @@ QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcPointerHandlerDispatch)
+class QQuickPointerHandlerPrivate;
+
class Q_QUICK_PRIVATE_EXPORT QQuickPointerHandler : public QObject, public QQmlParserStatus
{
Q_OBJECT
@@ -70,10 +70,11 @@ class Q_QUICK_PRIVATE_EXPORT QQuickPointerHandler : public QObject, public QQmlP
Q_PROPERTY(QQuickItem * target READ target WRITE setTarget NOTIFY targetChanged)
Q_PROPERTY(QQuickItem * parent READ parentItem CONSTANT)
Q_PROPERTY(GrabPermissions grabPermissions READ grabPermissions WRITE setGrabPermissions NOTIFY grabPermissionChanged)
+ Q_PROPERTY(qreal margin READ margin WRITE setMargin NOTIFY marginChanged)
public:
- explicit QQuickPointerHandler(QObject *parent = nullptr);
- virtual ~QQuickPointerHandler();
+ explicit QQuickPointerHandler(QQuickItem *parent = nullptr);
+ ~QQuickPointerHandler();
enum GrabPermission {
TakeOverForbidden = 0x0,
@@ -91,40 +92,47 @@ public:
Q_FLAG(GrabPermissions)
public:
- bool enabled() const { return m_enabled; }
+ bool enabled() const;
void setEnabled(bool enabled);
- bool active() const { return m_active; }
+ bool active() const;
QQuickItem *target() const;
void setTarget(QQuickItem *target);
- QQuickItem * parentItem() const { return static_cast<QQuickItem *>(QObject::parent()); }
+ QQuickItem * parentItem() const;
void handlePointerEvent(QQuickPointerEvent *event);
- GrabPermissions grabPermissions() const { return static_cast<GrabPermissions>(m_grabPermissions); }
+ GrabPermissions grabPermissions() const;
void setGrabPermissions(GrabPermissions grabPermissions);
+ qreal margin() const;
+ void setMargin(qreal pointDistanceThreshold);
+
Q_SIGNALS:
void enabledChanged();
void activeChanged();
void targetChanged();
- void grabChanged(QQuickEventPoint *point);
+ void marginChanged();
+ void grabChanged(QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point);
void grabPermissionChanged();
void canceled(QQuickEventPoint *point);
protected:
+ QQuickPointerHandler(QQuickPointerHandlerPrivate &dd, QQuickItem *parent);
+
void classBegin() override;
void componentComplete() override;
- QQuickPointerEvent *currentEvent() { return m_currentEvent; }
+ QQuickPointerEvent *currentEvent();
virtual bool wantsPointerEvent(QQuickPointerEvent *event);
+ virtual bool wantsEventPoint(QQuickEventPoint *point);
virtual void handlePointerEventImpl(QQuickPointerEvent *event);
void setActive(bool active);
virtual void onTargetChanged(QQuickItem *oldTarget) { Q_UNUSED(oldTarget); }
virtual void onActiveChanged() { }
- virtual void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point);
+ virtual void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point);
virtual bool canGrab(QQuickEventPoint *point);
virtual bool approveGrabTransition(QQuickEventPoint *point, QObject *proposedGrabber);
void setPassiveGrab(QQuickEventPoint *point, bool grab = true);
@@ -133,19 +141,11 @@ protected:
QPointF eventPos(const QQuickEventPoint *point) const;
bool parentContains(const QQuickEventPoint *point) const;
-private:
- QQuickPointerEvent *m_currentEvent;
- QQuickItem *m_target;
- bool m_enabled : 1;
- bool m_active : 1;
- bool m_targetExplicitlySet : 1;
- bool m_hadKeepMouseGrab : 1; // some handlers override target()->setKeepMouseGrab(); this remembers previous state
- bool m_hadKeepTouchGrab : 1; // some handlers override target()->setKeepTouchGrab(); this remembers previous state
- uint m_reserved : 19;
- uint8_t m_grabPermissions : 8;
-
friend class QQuickEventPoint;
+ friend class QQuickItemPrivate;
friend class QQuickWindowPrivate;
+
+ Q_DECLARE_PRIVATE(QQuickPointerHandler)
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickPointerHandler::GrabPermissions)
diff --git a/src/quick/handlers/qquickpointerhandler_p_p.h b/src/quick/handlers/qquickpointerhandler_p_p.h
new file mode 100644
index 0000000000..2ea4905643
--- /dev/null
+++ b/src/quick/handlers/qquickpointerhandler_p_p.h
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKPOINTERHANDLER_P_H
+#define QQUICKPOINTERHANDLER_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 "qevent.h"
+
+#include <QtQuick/private/qquickevents_p_p.h>
+#include <QtQuick/private/qquickpointerhandler_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class Q_QUICK_PRIVATE_EXPORT QQuickPointerHandlerPrivate : public QObjectPrivate
+{
+ Q_DECLARE_PUBLIC(QQuickPointerHandler)
+
+public:
+ static QQuickPointerHandlerPrivate* get(QQuickPointerHandler *q) { return q->d_func(); }
+ static const QQuickPointerHandlerPrivate* get(const QQuickPointerHandler *q) { return q->d_func(); }
+
+ QQuickPointerHandlerPrivate();
+
+ QQuickPointerEvent *currentEvent = nullptr;
+ QQuickItem *target = nullptr;
+ qreal m_margin = 0;
+ uint8_t grabPermissions : 8;
+ bool enabled : 1;
+ bool active : 1;
+ bool targetExplicitlySet : 1;
+ bool hadKeepMouseGrab : 1; // some handlers override target()->setKeepMouseGrab(); this remembers previous state
+ bool hadKeepTouchGrab : 1; // some handlers override target()->setKeepTouchGrab(); this remembers previous state
+};
+
+QT_END_NAMESPACE
+
+#endif // QQUICKPOINTERHANDLER_P_H
diff --git a/src/quick/handlers/qquickpointhandler.cpp b/src/quick/handlers/qquickpointhandler.cpp
index 7e2d40452c..3bc1c06a1a 100644
--- a/src/quick/handlers/qquickpointhandler.cpp
+++ b/src/quick/handlers/qquickpointhandler.cpp
@@ -47,8 +47,8 @@ QT_BEGIN_NAMESPACE
\qmltype PointHandler
\instantiates QQuickPointHandler
\inherits SinglePointHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
+ \ingroup qtquick-input-handlers
\brief Handler for reacting to a single touchpoint.
PointHandler can be used to show feedback about a touchpoint or the mouse
@@ -97,7 +97,7 @@ QT_BEGIN_NAMESPACE
\snippet pointerHandlers/pointHandler.qml 0
- Like all pointer handlers, a PointHandler has a \l target property, which
+ Like all input handlers, a PointHandler has a \l target property, which
may be used as a convenient place to put a point-tracking Item; but
PointHandler will not automatically manipulate the \c target item in any way.
You need to use bindings to make it react to the \l point.
@@ -114,16 +114,12 @@ QT_BEGIN_NAMESPACE
\sa MultiPointTouchArea
*/
-QQuickPointHandler::QQuickPointHandler(QObject *parent)
+QQuickPointHandler::QQuickPointHandler(QQuickItem *parent)
: QQuickSinglePointHandler(parent)
{
setIgnoreAdditionalPoints();
}
-QQuickPointHandler::~QQuickPointHandler()
-{
-}
-
bool QQuickPointHandler::wantsEventPoint(QQuickEventPoint *pt)
{
// On press, we want it unless a sibling of the same type also does.
@@ -143,11 +139,16 @@ void QQuickPointHandler::handleEventPoint(QQuickEventPoint *point)
{
switch (point->state()) {
case QQuickEventPoint::Pressed:
- setPassiveGrab(point);
- setActive(true);
+ if (point->pointerEvent()->asPointerTouchEvent() ||
+ (point->pointerEvent()->buttons() & acceptedButtons()) != Qt::NoButton) {
+ setPassiveGrab(point);
+ setActive(true);
+ }
break;
case QQuickEventPoint::Released:
- setActive(false);
+ if (point->pointerEvent()->asPointerTouchEvent() ||
+ (point->pointerEvent()->buttons() & acceptedButtons()) == Qt::NoButton)
+ setActive(false);
break;
default:
break;
diff --git a/src/quick/handlers/qquickpointhandler_p.h b/src/quick/handlers/qquickpointhandler_p.h
index 5babab0c4d..380ce1f90f 100644
--- a/src/quick/handlers/qquickpointhandler_p.h
+++ b/src/quick/handlers/qquickpointhandler_p.h
@@ -61,8 +61,7 @@ class Q_AUTOTEST_EXPORT QQuickPointHandler : public QQuickSinglePointHandler
Q_PROPERTY(QVector2D translation READ translation NOTIFY translationChanged)
public:
- explicit QQuickPointHandler(QObject *parent = 0);
- ~QQuickPointHandler();
+ explicit QQuickPointHandler(QQuickItem *parent = nullptr);
QVector2D translation() const;
diff --git a/src/quick/handlers/qquicksinglepointhandler.cpp b/src/quick/handlers/qquicksinglepointhandler.cpp
index 9df20390e4..82e5b1b05d 100644
--- a/src/quick/handlers/qquicksinglepointhandler.cpp
+++ b/src/quick/handlers/qquicksinglepointhandler.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2017 The Qt Company Ltd.
+** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
@@ -48,8 +48,7 @@ Q_DECLARE_LOGGING_CATEGORY(DBG_TOUCH_TARGET)
\preliminary
\instantiates QQuickSinglePointHandler
\inherits PointerDeviceHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
\brief Abstract handler for single-point Pointer Events.
An intermediate class (not registered as a QML type)
@@ -59,10 +58,8 @@ Q_DECLARE_LOGGING_CATEGORY(DBG_TOUCH_TARGET)
Override handleEventPoint() to implement a single-point handler.
*/
-QQuickSinglePointHandler::QQuickSinglePointHandler(QObject *parent)
+QQuickSinglePointHandler::QQuickSinglePointHandler(QQuickItem *parent)
: QQuickPointerDeviceHandler(parent)
- , m_acceptedButtons(Qt::LeftButton)
- , m_ignoreAdditionalPoints(false)
{
}
@@ -71,7 +68,7 @@ bool QQuickSinglePointHandler::wantsPointerEvent(QQuickPointerEvent *event)
if (!QQuickPointerDeviceHandler::wantsPointerEvent(event))
return false;
if (event->device()->pointerType() != QQuickPointerDevice::Finger &&
- (event->buttons() & m_acceptedButtons) == 0 && (event->button() & m_acceptedButtons) == 0)
+ (event->buttons() & acceptedButtons()) == 0 && (event->button() & acceptedButtons()) == 0)
return false;
if (m_pointInfo.m_id) {
@@ -79,16 +76,23 @@ bool QQuickSinglePointHandler::wantsPointerEvent(QQuickPointerEvent *event)
// It's expected to be an update or a release.
// If we no longer want it, cancel the grab.
int candidatePointCount = 0;
+ bool missing = true;
QQuickEventPoint *point = nullptr;
int c = event->pointCount();
for (int i = 0; i < c; ++i) {
QQuickEventPoint *p = event->point(i);
+ const bool found = (p->pointId() == m_pointInfo.m_id);
+ if (found)
+ missing = false;
if (wantsEventPoint(p)) {
++candidatePointCount;
- if (p->pointId() == m_pointInfo.m_id)
+ if (found)
point = p;
}
}
+ if (missing)
+ qCWarning(DBG_TOUCH_TARGET) << this << "pointId" << hex << m_pointInfo.m_id
+ << "is missing from current event, but was neither canceled nor released";
if (point) {
if (candidatePointCount == 1 || (candidatePointCount > 1 && m_ignoreAdditionalPoints)) {
point->setAccepted();
@@ -97,8 +101,6 @@ bool QQuickSinglePointHandler::wantsPointerEvent(QQuickPointerEvent *event)
point->cancelAllGrabs(this);
}
} else {
- qCWarning(DBG_TOUCH_TARGET) << this << "pointId" << hex << m_pointInfo.m_id
- << "is missing from current event, but was neither canceled nor released";
return false;
}
} else {
@@ -115,7 +117,7 @@ bool QQuickSinglePointHandler::wantsPointerEvent(QQuickPointerEvent *event)
}
}
if (chosen && candidatePointCount == 1) {
- m_pointInfo.m_id = chosen->pointId();
+ setPointId(chosen->pointId());
chosen->setAccepted();
}
}
@@ -127,64 +129,28 @@ void QQuickSinglePointHandler::handlePointerEventImpl(QQuickPointerEvent *event)
QQuickPointerDeviceHandler::handlePointerEventImpl(event);
QQuickEventPoint *currentPoint = event->pointById(m_pointInfo.m_id);
Q_ASSERT(currentPoint);
- if (!m_pointInfo.m_id || !currentPoint->isAccepted()) {
+ m_pointInfo.reset(currentPoint);
+ handleEventPoint(currentPoint);
+ if (currentPoint->state() == QQuickEventPoint::Released && (event->buttons() & acceptedButtons()) == Qt::NoButton) {
+ setExclusiveGrab(currentPoint, false);
reset();
- } else {
- if (event->asPointerTouchEvent()) {
- QQuickEventTouchPoint *tp = static_cast<QQuickEventTouchPoint *>(currentPoint);
- m_pointInfo.m_uniqueId = tp->uniqueId();
- m_pointInfo.m_rotation = tp->rotation();
- m_pointInfo.m_pressure = tp->pressure();
- m_pointInfo.m_ellipseDiameters = tp->ellipseDiameters();
- } else if (event->asPointerTabletEvent()) {
- // TODO
- } else {
- m_pointInfo.m_uniqueId = event->device()->uniqueId();
- m_pointInfo.m_rotation = 0;
- m_pointInfo.m_pressure = event->buttons() ? 1 : 0;
- m_pointInfo.m_ellipseDiameters = QSizeF();
- }
- m_pointInfo.m_position = currentPoint->position();
- m_pointInfo.m_scenePosition = currentPoint->scenePosition();
- if (currentPoint->state() == QQuickEventPoint::Updated)
- m_pointInfo.m_velocity = currentPoint->velocity();
- handleEventPoint(currentPoint);
- switch (currentPoint->state()) {
- case QQuickEventPoint::Pressed:
- m_pointInfo.m_pressPosition = currentPoint->position();
- m_pointInfo.m_scenePressPosition = currentPoint->scenePosition();
- m_pointInfo.m_pressedButtons = event->buttons();
- break;
- case QQuickEventPoint::Released:
- setExclusiveGrab(currentPoint, false);
- reset();
- break;
- default:
- m_pointInfo.m_pressedButtons = event->buttons();
- break;
- }
- emit pointChanged();
}
+ emit pointChanged();
}
-bool QQuickSinglePointHandler::wantsEventPoint(QQuickEventPoint *point)
-{
- return parentContains(point);
-}
-
-void QQuickSinglePointHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point)
+void QQuickSinglePointHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point)
{
if (grabber != this)
return;
- switch (stateChange) {
+ switch (transition) {
case QQuickEventPoint::GrabExclusive:
m_pointInfo.m_sceneGrabPosition = point->sceneGrabPosition();
setActive(true);
- QQuickPointerHandler::onGrabChanged(grabber, stateChange, point);
+ QQuickPointerHandler::onGrabChanged(grabber, transition, point);
break;
case QQuickEventPoint::GrabPassive:
m_pointInfo.m_sceneGrabPosition = point->sceneGrabPosition();
- QQuickPointerHandler::onGrabChanged(grabber, stateChange, point);
+ QQuickPointerHandler::onGrabChanged(grabber, transition, point);
break;
case QQuickEventPoint::OverrideGrabPassive:
return; // don't emit
@@ -193,11 +159,10 @@ void QQuickSinglePointHandler::onGrabChanged(QQuickPointerHandler *grabber, QQui
case QQuickEventPoint::CancelGrabPassive:
case QQuickEventPoint::CancelGrabExclusive:
// the grab is lost or relinquished, so the point is no longer relevant
- QQuickPointerHandler::onGrabChanged(grabber, stateChange, point);
+ QQuickPointerHandler::onGrabChanged(grabber, transition, point);
reset();
break;
}
- emit singlePointGrabChanged();
}
void QQuickSinglePointHandler::setIgnoreAdditionalPoints(bool v)
@@ -212,42 +177,9 @@ void QQuickSinglePointHandler::moveTarget(QPointF pos, QQuickEventPoint *point)
m_pointInfo.m_position = target()->mapFromScene(m_pointInfo.m_scenePosition);
}
-/*!
- \qmlproperty int QtQuick::SinglePointHandler::acceptedButtons
-
- The mouse buttons which can activate this Pointer Handler.
-
- By default, this property is set to \l {QtQuick::MouseEvent::button} {Qt.LeftButton}.
- It can be set to an OR combination of mouse buttons, and will ignore events
- from other buttons.
-
- For example, a control could be made to respond to left and right clicks
- in different ways, with two handlers:
-
- \qml
- Item {
- TapHandler {
- onTapped: console.log("left clicked")
- }
- TapHandler {
- acceptedButtons: Qt.RightButton
- onTapped: console.log("right clicked")
- }
- }
- \endqml
-
- \note Tapping on a touchscreen or tapping the stylus on a graphics tablet
- emulates clicking the left mouse button. This behavior can be altered via
- \l {PointerDeviceHandler::acceptedDevices}{acceptedDevices} or
- \l {PointerDeviceHandler::acceptedPointerTypes}{acceptedPointerTypes}.
-*/
-void QQuickSinglePointHandler::setAcceptedButtons(Qt::MouseButtons buttons)
+void QQuickSinglePointHandler::setPointId(int id)
{
- if (m_acceptedButtons == buttons)
- return;
-
- m_acceptedButtons = buttons;
- emit acceptedButtonsChanged();
+ m_pointInfo.m_id = id;
}
void QQuickSinglePointHandler::reset()
@@ -264,213 +196,4 @@ void QQuickSinglePointHandler::reset()
handled, this object is reset to default values (all coordinates are 0).
*/
-/*!
- \qmltype HandlerPoint
- \instantiates QQuickHandlerPoint
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
- \brief An event point.
-
- A QML representation of a QQuickEventPoint.
-
- It's possible to make bindings to properties of a \l SinglePointHandler's
- current point. For example:
-
- \snippet pointerHandlers/dragHandlerNullTarget.qml 0
-
- The point is kept up-to-date when the DragHandler is actively responding to
- an EventPoint; but when the point is released, or the current point is
- being handled by a different handler, \c position.x and \c position.y are 0.
-
- \note This is practically identical to QtQuick::EventPoint; however an
- EventPoint is a long-lived QObject which is invalidated between gestures
- and reused for subsequent event deliveries. Continuous bindings to its
- properties are not possible, and an individual handler cannot rely on it
- outside the period when that point is part of an active gesture which that
- handler is handling. HandlerPoint is a Q_GADGET that the handler owns.
- This allows you to make lifetime bindings to its properties.
-
- \sa SinglePointHandler::point
-*/
-
-QQuickHandlerPoint::QQuickHandlerPoint()
- : m_id(0)
- , m_rotation(0)
- , m_pressure(0)
-{}
-
-void QQuickHandlerPoint::reset()
-{
- m_id = 0;
- m_uniqueId = QPointingDeviceUniqueId();
- m_position = QPointF();
- m_scenePosition = QPointF();
- m_pressPosition = QPointF();
- m_scenePressPosition = QPointF();
- m_sceneGrabPosition = QPointF();
- m_velocity = QVector2D();
- m_rotation = 0;
- m_pressure = 0;
- m_ellipseDiameters = QSizeF();
- m_pressedButtons = Qt::NoButton;
-}
-
-/*!
- \readonly
- \qmlproperty int QtQuick::HandlerPoint::id
- \brief The ID number of the point
-
- During a touch gesture, from the time that the first finger is pressed
- until the last finger is released, each touchpoint will have a unique ID
- number. Likewise, if input from multiple devices occurs (for example
- simultaneous mouse and touch presses), all the current event points from
- all the devices will have unique IDs.
-
- \note Do not assume that id numbers start at zero or that they are
- sequential. Such an assumption is often false due to the way the underlying
- drivers work.
-
- \sa QTouchEvent::TouchPoint::id
-*/
-
-/*!
- \readonly
- \qmlproperty PointingDeviceUniqueId QtQuick::HandlerPoint::uniqueId
- \brief The unique ID of the point, if any
-
- This is normally empty, because touchscreens cannot uniquely identify fingers.
-
- On some types of touchscreens, especially those using TUIO drivers,
- it's possible to use recognizable physical tokens (fiducial objects)
- in addition to fingers. So if this point is a touch point, and
- uniqueId is set, it is the identifier for such an object.
-
- On a graphics tablet, each type of stylus or other tool often has a unique
- ID or serial number, which can be useful to respond in different ways to
- different tools.
-
- Interpreting the contents of this ID requires knowledge of the hardware and
- drivers in use.
-
- \sa QTabletEvent::uniqueId, QtQuick::TouchPoint::uniqueId, QtQuick::EventTouchPoint::uniqueId
-*/
-
-/*!
- \readonly
- \qmlproperty QPointF QtQuick::HandlerPoint::position
- \brief The position within the \c parent Item
-
- This is the position of the event point relative to the bounds of
- the \l {PointerHandler::parent} {parent}.
-*/
-
-/*!
- \readonly
- \qmlproperty QPointF QtQuick::HandlerPoint::scenePosition
- \brief The position within the scene
-
- This is the position of the event point relative to the bounds of the Qt
- Quick scene (typically the whole window).
-*/
-
-/*!
- \readonly
- \qmlproperty QPointF QtQuick::HandlerPoint::pressPosition
- \brief The pressed position within the \c parent Item
-
- This is the position at which this point was pressed, relative to the
- bounds of the \l {PointerHandler::parent} {parent}.
-*/
-
-/*!
- \readonly
- \qmlproperty QPointF QtQuick::HandlerPoint::scenePressPosition
- \brief The pressed position within the scene
-
- This is the position at which this point was pressed, in the coordinate
- system of the \l {Qt Quick Scene Graph}{scene graph}.
-*/
-
-/*!
- \readonly
- \qmlproperty QPointF QtQuick::HandlerPoint::sceneGrabPosition
- \brief The grabbed position within the scene
-
- If this point has been grabbed by a Pointer Handler or an Item, it means
- that object has taken sole responsibility for handling the movement and the
- release if this point. In that case, this is the position at which the grab
- occurred, in the coordinate system of the \l {Qt Quick Scene Graph}{scene graph}.
-*/
-
-/*!
- \readonly
- \qmlproperty enum QtQuick::HandlerPoint::pressedButtons
- \brief Which mouse or stylus buttons are currently pressed
-
- \sa MouseArea::pressedButtons
-*/
-
-/*!
- \readonly
- \qmlproperty QVector2D QtQuick::HandlerPoint::velocity
- \brief A vector representing the average speed and direction of movement
-
- This is a velocity vector pointing in the direction of movement, in logical
- pixels per second. It has x and y components, at least one of which will be
- nonzero when this point is in motion. It holds the average recent velocity:
- how fast and in which direction the event point has been moving recently.
-
- \sa QtQuick::EventPoint::velocity, QtQuick::TouchPoint::velocity, QTouchEvent::TouchPoint::velocity
-*/
-
-/*!
- \readonly
- \qmlproperty qreal QtQuick::HandlerPoint::rotation
-
- This property holds the rotation angle of the stylus on a graphics tablet
- or the contact patch of a touchpoint on a touchscreen.
-
- It is valid only with certain tablet stylus devices and touchscreens that
- can measure the rotation angle. Otherwise, it will be zero.
-*/
-
-/*!
- \readonly
- \qmlproperty qreal QtQuick::HandlerPoint::pressure
-
- This property tells how hard the user is pressing the stylus on a graphics
- tablet or the finger against a touchscreen, in the range from \c 0 (no
- measurable pressure) to \c 1.0 (maximum pressure which the device can
- measure).
-
- It is valid only with certain tablets and touchscreens that can measure
- pressure. Otherwise, it will be zero.
-*/
-
-/*!
- \readonly
- \qmlproperty size QtQuick::HandlerPoint::ellipseDiameters
-
- This property holds the diameters of the contact patch, if the event
- comes from a touchpoint and the device provides this information.
-
- A touchpoint is modeled as an elliptical area where the finger is pressed
- against the touchscreen. (In fact, it could also be modeled as a bitmap;
- but in that case we expect an elliptical bounding estimate to be fitted to
- the contact patch before the event is sent.) The harder the user presses,
- the larger the contact patch; so, these diameters provide an alternate way
- of detecting pressure, in case the device does not include a separate
- pressure sensor. The ellipse is centered on \l scenePosition (\l position
- in the PointerHandler's Item's local coordinates). The \l rotation property
- provides the rotation of the ellipse, if known. It is expected that if the
- \l rotation is zero, the \l {QSize::height}{height} is the larger dimension
- (the major axis), because of the usual hand position, reaching upward or
- outward across the surface.
-
- If the contact patch is unknown, or the device is not a touchscreen,
- these values will be zero.
-
- \sa QtQuick::EventTouchPoint::ellipseDiameters, QtQuick::TouchPoint::ellipseDiameters, QTouchEvent::TouchPoint::ellipseDiameters
-*/
-
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquicksinglepointhandler_p.h b/src/quick/handlers/qquicksinglepointhandler_p.h
index 7606b4f7ba..b9e5b12224 100644
--- a/src/quick/handlers/qquicksinglepointhandler_p.h
+++ b/src/quick/handlers/qquicksinglepointhandler_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 QtQuick module of the Qt Toolkit.
@@ -51,104 +51,47 @@
// We mean it.
//
+#include "qquickhandlerpoint_p.h"
#include "qquickpointerdevicehandler_p.h"
QT_BEGIN_NAMESPACE
-class QQuickSinglePointHandler;
-
-class Q_QUICK_PRIVATE_EXPORT QQuickHandlerPoint {
- Q_GADGET
- Q_PROPERTY(int id READ id)
- Q_PROPERTY(QPointingDeviceUniqueId uniqueId READ uniqueId)
- Q_PROPERTY(QPointF position READ position)
- Q_PROPERTY(QPointF scenePosition READ scenePosition)
- Q_PROPERTY(QPointF pressPosition READ pressPosition)
- Q_PROPERTY(QPointF scenePressPosition READ scenePressPosition)
- Q_PROPERTY(QPointF sceneGrabPosition READ sceneGrabPosition)
- Q_PROPERTY(Qt::MouseButtons pressedButtons READ pressedButtons)
- Q_PROPERTY(QVector2D velocity READ velocity)
- Q_PROPERTY(qreal rotation READ rotation)
- Q_PROPERTY(qreal pressure READ pressure)
- Q_PROPERTY(QSizeF ellipseDiameters READ ellipseDiameters)
-
-public:
- QQuickHandlerPoint();
-
- int id() const { return m_id; }
- Qt::MouseButtons pressedButtons() const { return m_pressedButtons; }
- QPointF pressPosition() const { return m_pressPosition; }
- QPointF scenePressPosition() const { return m_scenePressPosition; }
- QPointF sceneGrabPosition() const { return m_sceneGrabPosition; }
- QPointF position() const { return m_position; }
- QPointF scenePosition() const { return m_scenePosition; }
- QVector2D velocity() const { return m_velocity; }
- qreal rotation() const { return m_rotation; }
- qreal pressure() const { return m_pressure; }
- QSizeF ellipseDiameters() const { return m_ellipseDiameters; }
- QPointingDeviceUniqueId uniqueId() const { return m_uniqueId; }
-
-private:
- void reset();
- int m_id;
- QPointingDeviceUniqueId m_uniqueId;
- Qt::MouseButtons m_pressedButtons;
- QPointF m_position;
- QPointF m_scenePosition;
- QPointF m_pressPosition;
- QPointF m_scenePressPosition;
- QPointF m_sceneGrabPosition;
- QVector2D m_velocity;
- qreal m_rotation;
- qreal m_pressure;
- QSizeF m_ellipseDiameters;
- friend class QQuickSinglePointHandler;
-};
-
class Q_QUICK_PRIVATE_EXPORT QQuickSinglePointHandler : public QQuickPointerDeviceHandler
{
Q_OBJECT
- Q_PROPERTY(Qt::MouseButtons acceptedButtons READ acceptedButtons WRITE setAcceptedButtons NOTIFY acceptedButtonsChanged)
Q_PROPERTY(QQuickHandlerPoint point READ point NOTIFY pointChanged)
public:
- explicit QQuickSinglePointHandler(QObject *parent = nullptr);
- virtual ~QQuickSinglePointHandler() { }
-
- Qt::MouseButtons acceptedButtons() const { return m_acceptedButtons; }
- void setAcceptedButtons(Qt::MouseButtons buttons);
+ explicit QQuickSinglePointHandler(QQuickItem *parent = nullptr);
QQuickHandlerPoint point() const { return m_pointInfo; }
Q_SIGNALS:
void pointChanged();
- void singlePointGrabChanged(); // QQuickPointerHandler::grabChanged signal can't be a property notifier here
- void acceptedButtonsChanged();
protected:
bool wantsPointerEvent(QQuickPointerEvent *event) override;
- virtual bool wantsEventPoint(QQuickEventPoint *point);
void handlePointerEventImpl(QQuickPointerEvent *event) override;
virtual void handleEventPoint(QQuickEventPoint *point) = 0;
QQuickEventPoint *currentPoint(QQuickPointerEvent *ev) { return ev->pointById(m_pointInfo.m_id); }
- void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point) override;
+ void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point) override;
void setIgnoreAdditionalPoints(bool v = true);
void moveTarget(QPointF pos, QQuickEventPoint *point);
+ void setPointId(int id);
+
private:
void reset();
private:
QQuickHandlerPoint m_pointInfo;
- Qt::MouseButtons m_acceptedButtons;
- bool m_ignoreAdditionalPoints : 1;
+ bool m_ignoreAdditionalPoints = false;
};
QT_END_NAMESPACE
-QML_DECLARE_TYPE(QQuickHandlerPoint)
QML_DECLARE_TYPE(QQuickSinglePointHandler)
#endif // QQUICKPOINTERSINGLEHANDLER_H
diff --git a/src/quick/handlers/qquicktaphandler.cpp b/src/quick/handlers/qquicktaphandler.cpp
index 902ff0df10..e97722d6b7 100644
--- a/src/quick/handlers/qquicktaphandler.cpp
+++ b/src/quick/handlers/qquicktaphandler.cpp
@@ -55,8 +55,8 @@ int QQuickTapHandler::m_touchMultiTapDistanceSquared(-1);
\qmltype TapHandler
\instantiates QQuickTapHandler
\inherits SinglePointHandler
- \inqmlmodule Qt.labs.handlers
- \ingroup qtquick-handlers
+ \inqmlmodule QtQuick
+ \ingroup qtquick-input-handlers
\brief Handler for taps and clicks.
TapHandler is a handler for taps on a touchscreen or clicks on a mouse.
@@ -65,7 +65,7 @@ int QQuickTapHandler::m_touchMultiTapDistanceSquared(-1);
value is DragThreshold, which requires the press and release to be close
together in both space and time. In this case, DragHandler is able to
function using only a passive grab, and therefore does not interfere with
- event delivery to any other Items or Pointer Handlers. So the default
+ event delivery to any other Items or Input Handlers. So the default
gesturePolicy is useful when you want to modify behavior of an existing
control or Item by adding a TapHandler with bindings and/or JavaScript
callbacks.
@@ -84,13 +84,8 @@ int QQuickTapHandler::m_touchMultiTapDistanceSquared(-1);
\sa MouseArea
*/
-QQuickTapHandler::QQuickTapHandler(QObject *parent)
+QQuickTapHandler::QQuickTapHandler(QQuickItem *parent)
: QQuickSinglePointHandler(parent)
- , m_pressed(false)
- , m_gesturePolicy(DragThreshold)
- , m_tapCount(0)
- , m_longPressThreshold(-1)
- , m_lastTapTimestamp(0.0)
{
if (m_mouseMultiClickDistanceSquared < 0) {
m_multiTapInterval = qApp->styleHints()->mouseDoubleClickInterval() / 1000.0;
@@ -103,11 +98,7 @@ QQuickTapHandler::QQuickTapHandler(QObject *parent)
}
}
-QQuickTapHandler::~QQuickTapHandler()
-{
-}
-
-static bool dragOverThreshold(QQuickEventPoint *point)
+static bool dragOverThreshold(const QQuickEventPoint *point)
{
QPointF delta = point->scenePosition() - point->scenePressPosition();
return (QQuickWindowPrivate::dragOverThreshold(delta.x(), Qt::XAxis, point) ||
@@ -121,6 +112,11 @@ bool QQuickTapHandler::wantsEventPoint(QQuickEventPoint *point)
// (e.g. DragHandler) gets a chance to take over.
// Don't forget to emit released in case of a cancel.
bool ret = false;
+ bool overThreshold = dragOverThreshold(point);
+ if (overThreshold) {
+ m_longPressTimer.stop();
+ m_holdTimer.invalidate();
+ }
switch (point->state()) {
case QQuickEventPoint::Pressed:
case QQuickEventPoint::Released:
@@ -129,7 +125,7 @@ bool QQuickTapHandler::wantsEventPoint(QQuickEventPoint *point)
case QQuickEventPoint::Updated:
switch (m_gesturePolicy) {
case DragThreshold:
- ret = !dragOverThreshold(point);
+ ret = !overThreshold;
break;
case WithinBounds:
ret = parentContains(point);
@@ -209,19 +205,6 @@ void QQuickTapHandler::timerEvent(QTimerEvent *event)
}
/*!
- \qmlsignal QtQuick::TapHandler::tapped()
-
- This signal is emitted when the pointer device taps the item.
- */
-
-/*!
- \qmlsignal QtQuick::TapHandler::longPressed()
-
- This signal is emitted when a press occurs that is longer than the
- \l {TapHandler::longPressThreshold} {long press threshold}.
- */
-
-/*!
\qmlproperty enumeration QtQuick::TapHandler::gesturePolicy
The spatial constraint for a tap or long press gesture to be recognized,
@@ -237,12 +220,12 @@ void QQuickTapHandler::timerEvent(QTimerEvent *event)
threshold (QStyleHints::startDragDistance), the tap gesture is
canceled, even if the button or finger is still pressed. This policy
can be useful whenever TapHandler needs to cooperate with other
- pointer handlers (for example \l DragHandler) or event-handling Items
+ input handlers (for example \l DragHandler) or event-handling Items
(for example QtQuick Controls), because in this case TapHandler
will not take the exclusive grab, but merely a passive grab.
\value TapHandler.WithinBounds
- If the event point leaves the bounds of the \l target item, the tap
+ If the event point leaves the bounds of the \l parent Item, the tap
gesture is canceled. The TapHandler will take the exclusive grab on
press, but will release the grab as soon as the boundary constraint
is no longer satisfied.
@@ -250,7 +233,7 @@ void QQuickTapHandler::timerEvent(QTimerEvent *event)
\value TapHandler.ReleaseWithinBounds
At the time of release (the mouse button is released or the finger
is lifted), if the event point is outside the bounds of the
- \l target item, a tap gesture is not recognized. This corresponds to
+ \l parent Item, a tap gesture is not recognized. This corresponds to
typical behavior for button widgets: you can cancel a click by
dragging outside the button, and you can also change your mind by
dragging back inside the button before release. Note that it's
@@ -308,12 +291,12 @@ void QQuickTapHandler::setPressed(bool press, bool cancel, QQuickEventPoint *poi
else
m_tapCount = 1;
qCDebug(lcTapHandler) << objectName() << "tapped" << m_tapCount << "times";
- emit tapped();
+ emit tapped(point);
emit tapCountChanged();
if (m_tapCount == 1)
- emit singleTapped();
+ emit singleTapped(point);
else if (m_tapCount == 2)
- emit doubleTapped();
+ emit doubleTapped(point);
m_lastTapTimestamp = ts;
m_lastTapPos = point->scenePosition();
} else {
@@ -330,10 +313,10 @@ void QQuickTapHandler::setPressed(bool press, bool cancel, QQuickEventPoint *poi
}
}
-void QQuickTapHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point)
+void QQuickTapHandler::onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point)
{
- QQuickSinglePointHandler::onGrabChanged(grabber, stateChange, point);
- bool isCanceled = stateChange == QQuickEventPoint::CancelGrabExclusive || stateChange == QQuickEventPoint::CancelGrabPassive;
+ QQuickSinglePointHandler::onGrabChanged(grabber, transition, point);
+ bool isCanceled = transition == QQuickEventPoint::CancelGrabExclusive || transition == QQuickEventPoint::CancelGrabPassive;
if (grabber == this && (isCanceled || point->state() == QQuickEventPoint::Released))
setPressed(false, isCanceled, point);
}
@@ -387,23 +370,45 @@ void QQuickTapHandler::updateTimeHeld()
*/
/*!
- \qmlsignal TapHandler::singleTapped
+ \qmlsignal QtQuick::TapHandler::tapped
+
+ This signal is emitted each time the \l parent Item is tapped.
+
+ That is, if you press and release a touchpoint or button within a time
+ period less than \l longPressThreshold, while any movement does not exceed
+ the drag threshold, then the \c tapped signal will be emitted at the time
+ of release.
+*/
+
+/*!
+ \qmlsignal QtQuick::TapHandler::singleTapped
\since 5.11
- This signal is emitted when the \l target is tapped once. After an amount
- of time greater than QStyleHints::mouseDoubleClickInterval, it can be
- tapped again; but if the time until the next tap is less, \l tapCount
- will increase.
+ This signal is emitted when the \l parent Item is tapped once.
+ After an amount of time greater than QStyleHints::mouseDoubleClickInterval,
+ it can be tapped again; but if the time until the next tap is less,
+ \l tapCount will increase.
*/
/*!
- \qmlsignal TapHandler::doubleTapped
+ \qmlsignal QtQuick::TapHandler::doubleTapped
\since 5.11
- This signal is emitted when the \l target is tapped twice within a short
- span of time (QStyleHints::mouseDoubleClickInterval) and distance
+ This signal is emitted when the \l parent Item is tapped twice within a
+ short span of time (QStyleHints::mouseDoubleClickInterval) and distance
(QPlatformTheme::MouseDoubleClickDistance or
- QPlatformTheme::TouchDoubleTapDistance). This signal always occurs
- after singleTapped, tapped and tapCountChanged.
+ QPlatformTheme::TouchDoubleTapDistance). This signal always occurs after
+ \l singleTapped, \l tapped, and \l tapCountChanged.
*/
+
+/*!
+ \qmlsignal QtQuick::TapHandler::longPressed
+
+ This signal is emitted when the \l parent Item is pressed and held for a
+ time period greater than \l longPressThreshold. That is, if you press and
+ hold a touchpoint or button, while any movement does not exceed the drag
+ threshold, then the \c longPressed signal will be emitted at the time that
+ \l timeHeld exceeds \l longPressThreshold.
+*/
+
QT_END_NAMESPACE
diff --git a/src/quick/handlers/qquicktaphandler_p.h b/src/quick/handlers/qquicktaphandler_p.h
index b7c1895926..6ec5d55227 100644
--- a/src/quick/handlers/qquicktaphandler_p.h
+++ b/src/quick/handlers/qquicktaphandler_p.h
@@ -75,8 +75,7 @@ public:
};
Q_ENUM(GesturePolicy)
- explicit QQuickTapHandler(QObject *parent = nullptr);
- ~QQuickTapHandler();
+ explicit QQuickTapHandler(QQuickItem *parent = nullptr);
bool isPressed() const { return m_pressed; }
@@ -95,13 +94,13 @@ Q_SIGNALS:
void timeHeldChanged();
void longPressThresholdChanged();
void gesturePolicyChanged();
- void tapped();
- void singleTapped();
- void doubleTapped();
+ void tapped(QQuickEventPoint *eventPoint);
+ void singleTapped(QQuickEventPoint *eventPoint);
+ void doubleTapped(QQuickEventPoint *eventPoint);
void longPressed();
protected:
- void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabState stateChange, QQuickEventPoint *point) override;
+ void onGrabChanged(QQuickPointerHandler *grabber, QQuickEventPoint::GrabTransition transition, QQuickEventPoint *point) override;
void timerEvent(QTimerEvent *event) override;
bool wantsEventPoint(QQuickEventPoint *point) override;
void handleEventPoint(QQuickEventPoint *point) override;
@@ -113,14 +112,14 @@ private:
void updateTimeHeld();
private:
- bool m_pressed;
- GesturePolicy m_gesturePolicy;
- int m_tapCount;
- int m_longPressThreshold;
- QBasicTimer m_longPressTimer;
- QElapsedTimer m_holdTimer;
QPointF m_lastTapPos;
- qreal m_lastTapTimestamp;
+ qreal m_lastTapTimestamp = 0;
+ QElapsedTimer m_holdTimer;
+ QBasicTimer m_longPressTimer;
+ int m_tapCount = 0;
+ int m_longPressThreshold = -1;
+ GesturePolicy m_gesturePolicy = GesturePolicy::DragThreshold;
+ bool m_pressed = false;
static qreal m_multiTapInterval;
static int m_mouseMultiClickDistanceSquared;
diff --git a/src/quick/items/context2d/qquickcanvasitem.cpp b/src/quick/items/context2d/qquickcanvasitem.cpp
index eee64c9663..06dddabb65 100644
--- a/src/quick/items/context2d/qquickcanvasitem.cpp
+++ b/src/quick/items/context2d/qquickcanvasitem.cpp
@@ -735,7 +735,7 @@ void QQuickCanvasItem::updatePolish()
for (auto it = animationCallbacks.cbegin(), end = animationCallbacks.cend(); it != end; ++it) {
function = it.value().value();
- jsCall->args[0] = QV4::Primitive::fromUInt32(QDateTime::currentMSecsSinceEpoch() / 1000);
+ jsCall->args[0] = QV4::Value::fromUInt32(QDateTime::currentMSecsSinceEpoch() / 1000);
function->call(jsCall);
}
}
diff --git a/src/quick/items/context2d/qquickcontext2d.cpp b/src/quick/items/context2d/qquickcontext2d.cpp
index 2c115f4d3c..32336b5baf 100644
--- a/src/quick/items/context2d/qquickcontext2d.cpp
+++ b/src/quick/items/context2d/qquickcontext2d.cpp
@@ -563,6 +563,8 @@ struct QQuickJSContext2D : public QV4::Object
static QV4::ReturnedValue method_set_lineWidth(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_get_miterLimit(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_set_miterLimit(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
+ static QV4::ReturnedValue method_set_lineDashOffset(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
+ static QV4::ReturnedValue method_get_lineDashOffset(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_get_shadowBlur(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_set_shadowBlur(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
@@ -596,7 +598,7 @@ public:
static QV4::Heap::QQuickJSContext2DPrototype *create(QV4::ExecutionEngine *engine)
{
QV4::Scope scope(engine);
- QV4::Scoped<QQuickJSContext2DPrototype> o(scope, engine->memoryManager->allocObject<QQuickJSContext2DPrototype>());
+ QV4::Scoped<QQuickJSContext2DPrototype> o(scope, engine->memoryManager->allocate<QQuickJSContext2DPrototype>());
o->defineDefaultProperty(QStringLiteral("quadraticCurveTo"), method_quadraticCurveTo, 0);
o->defineDefaultProperty(QStringLiteral("restore"), method_restore, 0);
@@ -641,6 +643,8 @@ public:
o->defineDefaultProperty(QStringLiteral("createLinearGradient"), method_createLinearGradient, 0);
o->defineDefaultProperty(QStringLiteral("strokeRect"), method_strokeRect, 0);
o->defineDefaultProperty(QStringLiteral("closePath"), method_closePath, 0);
+ o->defineDefaultProperty(QStringLiteral("setLineDash"), method_setLineDash, 0);
+ o->defineDefaultProperty(QStringLiteral("getLineDash"), method_getLineDash, 0);
o->defineAccessorProperty(QStringLiteral("canvas"), QQuickJSContext2DPrototype::method_get_canvas, nullptr);
return o->d();
@@ -690,6 +694,8 @@ public:
static QV4::ReturnedValue method_createImageData(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_getImageData(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
static QV4::ReturnedValue method_putImageData(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
+ static QV4::ReturnedValue method_setLineDash(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
+ static QV4::ReturnedValue method_getLineDash(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
};
@@ -908,8 +914,8 @@ struct QQuickJSContext2DPixelData : public QV4::Object
V4_OBJECT2(QQuickJSContext2DPixelData, QV4::Object)
V4_NEEDS_DESTROY
- static QV4::ReturnedValue getIndexed(const QV4::Managed *m, uint index, bool *hasProperty);
- static bool putIndexed(QV4::Managed *m, uint index, const QV4::Value &value);
+ static QV4::ReturnedValue virtualGet(const QV4::Managed *m, QV4::PropertyKey id, const QV4::Value *receiver, bool *hasProperty);
+ static bool virtualPut(QV4::Managed *m, QV4::PropertyKey id, const QV4::Value &value, Value *receiver);
static QV4::ReturnedValue proto_get_length(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc);
};
@@ -938,7 +944,7 @@ struct QQuickJSContext2DImageData : public QV4::Object
void QV4::Heap::QQuickJSContext2DImageData::init()
{
Object::init();
- pixelData = QV4::Primitive::undefinedValue();
+ pixelData = QV4::Value::undefinedValue();
QV4::Scope scope(internalClass->engine);
QV4::ScopedObject o(scope, this);
@@ -954,19 +960,19 @@ static QV4::ReturnedValue qt_create_image_data(qreal w, qreal h, QV4::ExecutionE
{
QV4::Scope scope(v4);
QQuickContext2DEngineData *ed = engineData(scope.engine);
- QV4::Scoped<QQuickJSContext2DPixelData> pixelData(scope, scope.engine->memoryManager->allocObject<QQuickJSContext2DPixelData>());
+ QV4::Scoped<QQuickJSContext2DPixelData> pixelData(scope, scope.engine->memoryManager->allocate<QQuickJSContext2DPixelData>());
QV4::ScopedObject p(scope, ed->pixelArrayProto.value());
- pixelData->setPrototype(p);
+ pixelData->setPrototypeOf(p);
if (image.isNull()) {
*pixelData->d()->image = QImage(w, h, QImage::Format_ARGB32);
pixelData->d()->image->fill(0x00000000);
} else {
- Q_ASSERT(image.width()== qRound(w * image.devicePixelRatio()) && image.height() == qRound(h * image.devicePixelRatio()));
+ Q_ASSERT(image.width()== qRound(w * image.devicePixelRatioF()) && image.height() == qRound(h * image.devicePixelRatioF()));
*pixelData->d()->image = image.format() == QImage::Format_ARGB32 ? image : image.convertToFormat(QImage::Format_ARGB32);
}
- QV4::Scoped<QQuickJSContext2DImageData> imageData(scope, scope.engine->memoryManager->allocObject<QQuickJSContext2DImageData>());
+ QV4::Scoped<QQuickJSContext2DImageData> imageData(scope, scope.engine->memoryManager->allocate<QQuickJSContext2DImageData>());
imageData->d()->pixelData = pixelData.asReturnedValue();
return imageData.asReturnedValue();
}
@@ -1406,7 +1412,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_fillStyle(const QV4::FunctionOb
QV4::Scoped<QQuickJSContext2D> r(scope, thisObject->as<QQuickJSContext2D>());
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Primitive::undefinedValue());
+ QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Value::undefinedValue());
if (value->as<Object>()) {
QColor color = scope.engine->toVariant(value, qMetaTypeId<QColor>()).value<QColor>();
@@ -1461,7 +1467,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_fillRule(const QV4::FunctionObj
QV4::Scoped<QQuickJSContext2D> r(scope, thisObject->as<QQuickJSContext2D>());
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Primitive::undefinedValue());
+ QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Value::undefinedValue());
if ((value->isString() && value->toQString() == QLatin1String("WindingFill"))
|| (value->isInt32() && value->integerValue() == Qt::WindingFill)) {
@@ -1515,7 +1521,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_strokeStyle(const QV4::Function
QV4::Scoped<QQuickJSContext2D> r(scope, thisObject->as<QQuickJSContext2D>());
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Primitive::undefinedValue());
+ QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Value::undefinedValue());
if (value->as<Object>()) {
QColor color = scope.engine->toVariant(value, qMetaTypeId<QColor>()).value<QColor>();
@@ -1582,9 +1588,9 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_createLinearGradient(const
}
QQuickContext2DEngineData *ed = engineData(scope.engine);
- QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocObject<QQuickContext2DStyle>());
+ QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocate<QQuickContext2DStyle>());
QV4::ScopedObject p(scope, ed->gradientProto.value());
- gradient->setPrototype(p);
+ gradient->setPrototypeOf(p);
*gradient->d()->brush = QLinearGradient(x0, y0, x1, y1);
RETURN_RESULT(*gradient);
}
@@ -1634,9 +1640,9 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_createRadialGradient(const
QQuickContext2DEngineData *ed = engineData(scope.engine);
- QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocObject<QQuickContext2DStyle>());
+ QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocate<QQuickContext2DStyle>());
QV4::ScopedObject p(scope, ed->gradientProto.value());
- gradient->setPrototype(p);
+ gradient->setPrototypeOf(p);
*gradient->d()->brush = QRadialGradient(QPointF(x1, y1), r1, QPointF(x0, y0), r0);
RETURN_RESULT(*gradient);
}
@@ -1678,9 +1684,9 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_createConicalGradient(cons
QQuickContext2DEngineData *ed = engineData(scope.engine);
- QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocObject<QQuickContext2DStyle>());
+ QV4::Scoped<QQuickContext2DStyle> gradient(scope, scope.engine->memoryManager->allocate<QQuickContext2DStyle>());
QV4::ScopedObject p(scope, ed->gradientProto.value());
- gradient->setPrototype(p);
+ gradient->setPrototypeOf(p);
*gradient->d()->brush = QConicalGradient(x, y, angle);
RETURN_RESULT(*gradient);
}
@@ -1738,7 +1744,7 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_createPattern(const QV4::F
CHECK_CONTEXT(r)
if (argc >= 2) {
- QV4::Scoped<QQuickContext2DStyle> pattern(scope, scope.engine->memoryManager->allocObject<QQuickContext2DStyle>());
+ QV4::Scoped<QQuickContext2DStyle> pattern(scope, scope.engine->memoryManager->allocate<QQuickContext2DStyle>());
QColor color = scope.engine->toVariant(argv[0], qMetaTypeId<QColor>()).value<QColor>();
if (color.isValid()) {
@@ -1963,6 +1969,122 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_miterLimit(const QV4::FunctionO
RETURN_UNDEFINED();
}
+/*!
+ \qmlmethod array QtQuick::Context2D::getLineDash()
+ \since QtQuick 2.11
+ Returns an array of qreals representing the dash pattern of the line.
+
+ \sa setLineDash()
+ */
+QV4::ReturnedValue QQuickJSContext2DPrototype::method_getLineDash(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
+{
+ QV4::Scope scope(b);
+ QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
+ CHECK_CONTEXT(r)
+
+ const QVector<qreal> pattern = r->d()->context->state.lineDash;
+ QV4::ScopedArrayObject array(scope, scope.engine->newArrayObject(pattern.size()));
+ array->arrayReserve(pattern.size());
+ for (int i = 0; i < pattern.size(); i++)
+ array->put(i, QV4::Value::fromDouble(pattern[i]));
+
+ array->setArrayLengthUnchecked(pattern.size());
+
+ RETURN_RESULT(*array);
+}
+
+/*!
+ \qmlmethod QtQuick::Context2D::setLineDash(array pattern)
+ \since QtQuick 2.11
+ Sets the dash pattern to the given pattern
+
+ \a pattern a list of numbers that specifies distances to alternately draw a line and a gap.
+
+ If the number of elements in the array is odd, the elements of the array get copied
+ and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25].
+
+ \table 100%
+ \row
+ \li \inlineimage qml-item-canvas-lineDash.png
+ \li
+ \code
+ var space = 4
+ ctx.setLineDash([1, space, 3, space, 9, space, 27, space, 9, space])
+ ...
+ ctx.stroke();
+ \endcode
+ \endtable
+
+ \sa setLineDash
+ */
+QV4::ReturnedValue QQuickJSContext2DPrototype::method_setLineDash(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
+{
+ QV4::Scope scope(b);
+ QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
+ CHECK_CONTEXT_SETTER(r)
+
+ if (!argc)
+ RETURN_UNDEFINED();
+
+ QV4::ScopedArrayObject array(scope, argv[0]);
+ if (!array)
+ RETURN_UNDEFINED();
+
+ QV4::ScopedValue v(scope);
+ const uint arrayLength = array->getLength();
+ QVector<qreal> dashes;
+ dashes.reserve(arrayLength);
+ for (uint i = 0; i < arrayLength; ++i) {
+ v = array->get(i);
+ const double number = v->toNumber();
+
+ if (!qt_is_finite(number) || (number < 0))
+ RETURN_UNDEFINED();
+
+ dashes.append(v->toNumber());
+ }
+ if (dashes.size() % 2 != 0) {
+ dashes += dashes;
+ }
+
+ r->d()->context->state.lineDash = dashes;
+ r->d()->context->buffer()->setLineDash(dashes);
+
+ RETURN_UNDEFINED();
+}
+
+/*!
+ \qmlproperty real QtQuick::Context2D::lineDashOffset
+ \since QtQuick 2.11
+
+ Holds the current line dash offset
+ The default line dash ofset value is 0
+ */
+QV4::ReturnedValue QQuickJSContext2D::method_get_lineDashOffset(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *, int)
+{
+ QV4::Scope scope(b);
+ QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
+ CHECK_CONTEXT(r)
+
+ RETURN_RESULT(QV4::Encode(r->d()->context->state.lineDashOffset));
+}
+
+QV4::ReturnedValue QQuickJSContext2D::method_set_lineDashOffset(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
+{
+ QV4::Scope scope(b);
+ QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
+ CHECK_CONTEXT_SETTER(r)
+
+ const qreal offset = argc ? argv[0].toNumber() : -1;
+
+ if (qt_is_finite(offset) && offset != r->d()->context->state.lineDashOffset) {
+ r->d()->context->state.lineDashOffset = offset;
+ r->d()->context->buffer()->setLineDashOffset(offset);
+ }
+ RETURN_UNDEFINED();
+}
+
+
// shadows
/*!
\qmlproperty real QtQuick::Context2D::shadowBlur
@@ -2096,7 +2218,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_path(const QV4::FunctionObject
QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Primitive::undefinedValue());
+ QV4::ScopedValue value(scope, argc ? argv[0] : QV4::Value::undefinedValue());
r->d()->context->beginPath();
QV4::Scoped<QV4::QObjectWrapper> qobjectWrapper(scope, value);
if (!!qobjectWrapper) {
@@ -2593,7 +2715,7 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_isPointInPath(const QV4::F
bool pointInPath = false;
if (argc >= 2)
pointInPath = r->d()->context->isPointInPath(argv[0].toNumber(), argv[1].toNumber());
- RETURN_RESULT(QV4::Primitive::fromBoolean(pointInPath).asReturnedValue());
+ RETURN_RESULT(QV4::Value::fromBoolean(pointInPath).asReturnedValue());
}
QV4::ReturnedValue QQuickJSContext2DPrototype::method_drawFocusRing(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *, int)
@@ -2652,7 +2774,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_font(const QV4::FunctionObject
QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedString s(scope, argc ? argv[0] : QV4::Primitive::undefinedValue(), QV4::ScopedString::Convert);
+ QV4::ScopedString s(scope, argc ? argv[0] : QV4::Value::undefinedValue(), QV4::ScopedString::Convert);
if (scope.engine->hasException)
RETURN_UNDEFINED();
QFont font = qt_font_from_string(s->toQString(), r->d()->context->state.font);
@@ -2704,7 +2826,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_textAlign(const QV4::FunctionOb
QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedString s(scope, argc ? argv[0] : QV4::Primitive::undefinedValue(), QV4::ScopedString::Convert);
+ QV4::ScopedString s(scope, argc ? argv[0] : QV4::Value::undefinedValue(), QV4::ScopedString::Convert);
if (scope.engine->hasException)
RETURN_UNDEFINED();
QString textAlign = s->toQString();
@@ -2771,7 +2893,7 @@ QV4::ReturnedValue QQuickJSContext2D::method_set_textBaseline(const QV4::Functio
QV4::Scope scope(b);
QV4::Scoped<QQuickJSContext2D> r(scope, *thisObject);
CHECK_CONTEXT_SETTER(r)
- QV4::ScopedString s(scope, argc ? argv[0] : QV4::Primitive::undefinedValue(), QV4::ScopedString::Convert);
+ QV4::ScopedString s(scope, argc ? argv[0] : QV4::Value::undefinedValue(), QV4::ScopedString::Convert);
if (scope.engine->hasException)
RETURN_UNDEFINED();
QString textBaseline = s->toQString();
@@ -2858,7 +2980,7 @@ QV4::ReturnedValue QQuickJSContext2DPrototype::method_measureText(const QV4::Fun
uint width = fm.width(argv[0].toQStringNoThrow());
QV4::ScopedObject tm(scope, scope.engine->newObject());
tm->put(QV4::ScopedString(scope, scope.engine->newIdentifier(QStringLiteral("width"))).getPointer(),
- QV4::ScopedValue(scope, QV4::Primitive::fromDouble(width)));
+ QV4::ScopedValue(scope, QV4::Value::fromDouble(width)));
RETURN_RESULT(*tm);
}
RETURN_UNDEFINED();
@@ -3130,8 +3252,12 @@ QV4::ReturnedValue QQuickJSContext2DPixelData::proto_get_length(const QV4::Funct
RETURN_RESULT(QV4::Encode(r->d()->image->width() * r->d()->image->height() * 4));
}
-QV4::ReturnedValue QQuickJSContext2DPixelData::getIndexed(const QV4::Managed *m, uint index, bool *hasProperty)
+QV4::ReturnedValue QQuickJSContext2DPixelData::virtualGet(const QV4::Managed *m, QV4::PropertyKey id, const QV4::Value *receiver, bool *hasProperty)
{
+ if (!id.isArrayIndex())
+ return QV4::Object::virtualGet(m, id, receiver, hasProperty);
+
+ uint index = id.asArrayIndex();
Q_ASSERT(m->as<QQuickJSContext2DPixelData>());
QV4::ExecutionEngine *v4 = static_cast<const QQuickJSContext2DPixelData *>(m)->engine();
QV4::Scope scope(v4);
@@ -3156,19 +3282,24 @@ QV4::ReturnedValue QQuickJSContext2DPixelData::getIndexed(const QV4::Managed *m,
return QV4::Encode(qAlpha(*pixel));
}
}
+
if (hasProperty)
*hasProperty = false;
return QV4::Encode::undefined();
}
-bool QQuickJSContext2DPixelData::putIndexed(QV4::Managed *m, uint index, const QV4::Value &value)
+bool QQuickJSContext2DPixelData::virtualPut(QV4::Managed *m, QV4::PropertyKey id, const QV4::Value &value, QV4::Value *receiver)
{
+ if (!id.isArrayIndex())
+ return Object::virtualPut(m, id, value, receiver);
+
Q_ASSERT(m->as<QQuickJSContext2DPixelData>());
QV4::ExecutionEngine *v4 = static_cast<QQuickJSContext2DPixelData *>(m)->engine();
QV4::Scope scope(v4);
if (scope.hasException())
return false;
+ uint index = id.asArrayIndex();
QV4::Scoped<QQuickJSContext2DPixelData> r(scope, static_cast<QQuickJSContext2DPixelData *>(m));
const int v = value.toInt32();
@@ -4303,6 +4434,7 @@ QQuickContext2DEngineData::QQuickContext2DEngineData(QV4::ExecutionEngine *v4)
proto->defineAccessorProperty(QStringLiteral("lineWidth"), QQuickJSContext2D::method_get_lineWidth, QQuickJSContext2D::method_set_lineWidth);
proto->defineAccessorProperty(QStringLiteral("textAlign"), QQuickJSContext2D::method_get_textAlign, QQuickJSContext2D::method_set_textAlign);
proto->defineAccessorProperty(QStringLiteral("shadowBlur"), QQuickJSContext2D::method_get_shadowBlur, QQuickJSContext2D::method_set_shadowBlur);
+ proto->defineAccessorProperty(QStringLiteral("lineDashOffset"), QQuickJSContext2D::method_get_lineDashOffset, QQuickJSContext2D::method_set_lineDashOffset);
contextPrototype = proto;
proto = scope.engine->newObject();
@@ -4366,6 +4498,10 @@ void QQuickContext2D::popState()
if (newState.shadowOffsetY != state.shadowOffsetY)
buffer()->setShadowOffsetY(newState.shadowOffsetY);
+
+ if (newState.lineDash != state.lineDash)
+ buffer()->setLineDash(newState.lineDash);
+
m_path = state.matrix.map(m_path);
state = newState;
m_path = state.matrix.inverted().map(m_path);
@@ -4399,9 +4535,9 @@ void QQuickContext2D::setV4Engine(QV4::ExecutionEngine *engine)
QQuickContext2DEngineData *ed = engineData(engine);
QV4::Scope scope(engine);
- QV4::Scoped<QQuickJSContext2D> wrapper(scope, engine->memoryManager->allocObject<QQuickJSContext2D>());
+ QV4::Scoped<QQuickJSContext2D> wrapper(scope, engine->memoryManager->allocate<QQuickJSContext2D>());
QV4::ScopedObject p(scope, ed->contextPrototype.value());
- wrapper->setPrototype(p);
+ wrapper->setPrototypeOf(p);
wrapper->d()->context = this;
m_v4value = wrapper;
}
diff --git a/src/quick/items/context2d/qquickcontext2d_p.h b/src/quick/items/context2d/qquickcontext2d_p.h
index 4cc07027b1..1ece6796f3 100644
--- a/src/quick/items/context2d/qquickcontext2d_p.h
+++ b/src/quick/items/context2d/qquickcontext2d_p.h
@@ -112,6 +112,8 @@ public:
LineWidth,
LineCap,
LineJoin,
+ LineDash,
+ LineDashOffset,
MiterLimit,
ShadowOffsetX,
ShadowOffsetY,
@@ -142,6 +144,7 @@ public:
, lineWidth(1)
, lineCap(Qt::FlatCap)
, lineJoin(Qt::MiterJoin)
+ , lineDashOffset(0)
, miterLimit(10)
, shadowOffsetX(0)
, shadowOffsetY(0)
@@ -170,6 +173,8 @@ public:
qreal lineWidth;
Qt::PenCapStyle lineCap;
Qt::PenJoinStyle lineJoin;
+ QVector<qreal> lineDash;
+ qreal lineDashOffset;
qreal miterLimit;
qreal shadowOffsetX;
qreal shadowOffsetY;
diff --git a/src/quick/items/context2d/qquickcontext2dcommandbuffer.cpp b/src/quick/items/context2d/qquickcontext2dcommandbuffer.cpp
index 30895d9b0e..55ebbe907c 100644
--- a/src/quick/items/context2d/qquickcontext2dcommandbuffer.cpp
+++ b/src/quick/items/context2d/qquickcontext2dcommandbuffer.cpp
@@ -192,6 +192,10 @@ QPen QQuickContext2DCommandBuffer::makePen(const QQuickContext2D::State& state)
pen.setJoinStyle(state.lineJoin);
pen.setMiterLimit(state.miterLimit);
pen.setBrush(state.strokeStyle);
+ if (!state.lineDash.isEmpty()) {
+ pen.setDashPattern(state.lineDash);
+ }
+ pen.setDashOffset(state.lineDashOffset);
return pen;
}
@@ -361,6 +365,28 @@ void QQuickContext2DCommandBuffer::replay(QPainter* p, QQuickContext2D::State& s
p->setPen(nPen);
break;
}
+ case QQuickContext2D::LineDash:
+ {
+ const qreal count = takeReal();
+ QVector<qreal> pattern;
+ pattern.reserve(count);
+ for (uint i = 0; i < count; i++) {
+ pattern.append(takeReal());
+ }
+ state.lineDash = pattern;
+ QPen nPen = p->pen();
+ nPen.setDashPattern(pattern);
+ p->setPen(nPen);
+ break;
+ }
+ case QQuickContext2D::LineDashOffset:
+ {
+ state.lineDashOffset = takeReal();
+ QPen nPen = p->pen();
+ nPen.setDashOffset(state.lineDashOffset);
+ p->setPen(nPen);
+ break;
+ }
case QQuickContext2D::MiterLimit:
{
state.miterLimit = takeMiterLimit();
diff --git a/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h b/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
index 2a1ac7304e..c3e844c929 100644
--- a/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
+++ b/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
@@ -201,6 +201,20 @@ public:
ints << join;
}
+ inline void setLineDash(const QVector<qreal> &pattern)
+ {
+ commands << QQuickContext2D::LineDash;
+ reals << pattern.length();
+ for (qreal r : pattern)
+ reals << r;
+ }
+
+ inline void setLineDashOffset( qreal offset)
+ {
+ commands << QQuickContext2D::LineDashOffset;
+ reals << offset;
+ }
+
inline void setMiterLimit( qreal limit)
{
commands << QQuickContext2D::MiterLimit;
diff --git a/src/quick/items/items.pri b/src/quick/items/items.pri
index 1acb3b5265..e649b5429d 100644
--- a/src/quick/items/items.pri
+++ b/src/quick/items/items.pri
@@ -122,9 +122,11 @@ qtConfig(quick-gridview) {
qtConfig(quick-itemview) {
HEADERS += \
+ $$PWD/qquickitemviewfxitem_p_p.h \
$$PWD/qquickitemview_p.h \
$$PWD/qquickitemview_p_p.h
SOURCES += \
+ $$PWD/qquickitemviewfxitem.cpp \
$$PWD/qquickitemview.cpp
}
@@ -142,6 +144,14 @@ qtConfig(quick-listview) {
$$PWD/qquicklistview.cpp
}
+qtConfig(quick-tableview) {
+ HEADERS += \
+ $$PWD/qquicktableview_p.h \
+ $$PWD/qquicktableview_p_p.h
+ SOURCES += \
+ $$PWD/qquicktableview.cpp
+}
+
qtConfig(quick-pathview) {
HEADERS += \
$$PWD/qquickpathview_p.h \
diff --git a/src/quick/items/qquickanchors_p.h b/src/quick/items/qquickanchors_p.h
index 931b963534..c7995cb7a8 100644
--- a/src/quick/items/qquickanchors_p.h
+++ b/src/quick/items/qquickanchors_p.h
@@ -108,6 +108,7 @@ public:
Vertical_Mask = TopAnchor | BottomAnchor | VCenterAnchor | BaselineAnchor
};
Q_DECLARE_FLAGS(Anchors, Anchor)
+ Q_FLAG(Anchors)
QQuickAnchorLine left() const;
void setLeft(const QQuickAnchorLine &edge);
diff --git a/src/quick/items/qquickanimatedsprite.cpp b/src/quick/items/qquickanimatedsprite.cpp
index 603d5a3120..18adb4e992 100644
--- a/src/quick/items/qquickanimatedsprite.cpp
+++ b/src/quick/items/qquickanimatedsprite.cpp
@@ -268,6 +268,16 @@ QT_BEGIN_NAMESPACE
Stops, then starts the sprite animation.
*/
+/*!
+ \qmlsignal QtQuick::AnimatedSprite::finished()
+ \since 5.12
+
+ This signal is emitted when the sprite has finished animating.
+
+ It is not emitted when running is set to \c false, nor for sprites whose
+ \l loops property is set to \c AnimatedSprite.Infinite.
+*/
+
QQuickAnimatedSprite::QQuickAnimatedSprite(QQuickItem *parent) :
QQuickItem(*(new QQuickAnimatedSpritePrivate), parent)
{
@@ -806,6 +816,7 @@ void QQuickAnimatedSprite::prepareNextFrame(QSGSpriteNode *node)
frameAt = 0;
d->m_running = false;
emit runningChanged(false);
+ emit finished();
maybeUpdate();
}
} else {
diff --git a/src/quick/items/qquickanimatedsprite_p.h b/src/quick/items/qquickanimatedsprite_p.h
index d7e60b909c..ff59591c9f 100644
--- a/src/quick/items/qquickanimatedsprite_p.h
+++ b/src/quick/items/qquickanimatedsprite_p.h
@@ -135,6 +135,8 @@ Q_SIGNALS:
void loopsChanged(int arg);
void currentFrameChanged(int arg);
+ Q_REVISION(12) void finished();
+
public Q_SLOTS:
void start();
void stop();
diff --git a/src/quick/items/qquickborderimage.cpp b/src/quick/items/qquickborderimage.cpp
index d49829096f..e4e766a129 100644
--- a/src/quick/items/qquickborderimage.cpp
+++ b/src/quick/items/qquickborderimage.cpp
@@ -591,10 +591,18 @@ void QQuickBorderImagePrivate::calculateRects(const QQuickScaleGrid *border,
*innerTargetRect = *targetRect;
if (border) {
- *innerSourceRect = QRectF(border->left() * devicePixelRatio / qreal(sourceSize.width()),
- border->top() * devicePixelRatio / qreal(sourceSize.height()),
- qMax<qreal>(0, sourceSize.width() - (border->right() + border->left()) * devicePixelRatio) / sourceSize.width(),
- qMax<qreal>(0, sourceSize.height() - (border->bottom() + border->top()) * devicePixelRatio) / sourceSize.height());
+ qreal borderLeft = border->left() * devicePixelRatio;
+ qreal borderRight = border->right() * devicePixelRatio;
+ qreal borderTop = border->top() * devicePixelRatio;
+ qreal borderBottom = border->bottom() * devicePixelRatio;
+ if (borderLeft + borderRight > sourceSize.width() && borderLeft < sourceSize.width())
+ borderRight = sourceSize.width() - borderLeft;
+ if (borderTop + borderBottom > sourceSize.height() && borderTop < sourceSize.height())
+ borderBottom = sourceSize.height() - borderTop;
+ *innerSourceRect = QRectF(QPointF(borderLeft / qreal(sourceSize.width()),
+ borderTop * devicePixelRatio / qreal(sourceSize.height())),
+ QPointF((sourceSize.width() - borderRight) / qreal(sourceSize.width()),
+ (sourceSize.height() - borderBottom) / qreal(sourceSize.height()))),
*innerTargetRect = QRectF(border->left(),
border->top(),
qMax<qreal>(0, targetSize.width() - (border->right() + border->left())),
@@ -604,14 +612,16 @@ void QQuickBorderImagePrivate::calculateRects(const QQuickScaleGrid *border,
qreal hTiles = 1;
qreal vTiles = 1;
const QSizeF innerTargetSize = innerTargetRect->size() * devicePixelRatio;
- if (innerSourceRect->width() != 0
- && horizontalTileMode != QQuickBorderImage::Stretch) {
+ if (innerSourceRect->width() <= 0)
+ hTiles = 0;
+ else if (horizontalTileMode != QQuickBorderImage::Stretch) {
hTiles = innerTargetSize.width() / qreal(innerSourceRect->width() * sourceSize.width());
if (horizontalTileMode == QQuickBorderImage::Round)
hTiles = qCeil(hTiles);
}
- if (innerSourceRect->height() != 0
- && verticalTileMode != QQuickBorderImage::Stretch) {
+ if (innerSourceRect->height() <= 0)
+ vTiles = 0;
+ else if (verticalTileMode != QQuickBorderImage::Stretch) {
vTiles = innerTargetSize.height() / qreal(innerSourceRect->height() * sourceSize.height());
if (verticalTileMode == QQuickBorderImage::Round)
vTiles = qCeil(vTiles);
diff --git a/src/quick/items/qquickevents.cpp b/src/quick/items/qquickevents.cpp
index d4aba31e28..31c56b7cb7 100644
--- a/src/quick/items/qquickevents.cpp
+++ b/src/quick/items/qquickevents.cpp
@@ -642,6 +642,11 @@ QQuickPointerDevice *QQuickPointerDevice::touchDevice(const QTouchDevice *d)
return dev;
}
+const QTouchDevice *QQuickPointerDevice::qTouchDevice() const
+{
+ return g_touchDevices->key(const_cast<QQuickPointerDevice *>(this));
+}
+
QList<QQuickPointerDevice*> QQuickPointerDevice::touchDevices()
{
return g_touchDevices->values();
@@ -901,7 +906,7 @@ void QQuickEventPoint::setGrabberPointerHandler(QQuickPointerHandler *grabber, b
if (grabber) {
grabber->onGrabChanged(grabber, GrabExclusive, this);
for (QPointer<QQuickPointerHandler> passiveGrabber : m_passiveGrabbers) {
- if (passiveGrabber != grabber)
+ if (!passiveGrabber.isNull() && passiveGrabber != grabber)
passiveGrabber->onGrabChanged(grabber, OverrideGrabPassive, this);
}
}
@@ -1291,7 +1296,7 @@ QQuickPointerEvent *QQuickPointerMouseEvent::reset(QEvent *event)
Qt::TouchPointState state = Qt::TouchPointStationary;
switch (ev->type()) {
case QEvent::MouseButtonPress:
- m_mousePoint->clearPassiveGrabbers();
+ m_point->clearPassiveGrabbers();
Q_FALLTHROUGH();
case QEvent::MouseButtonDblClick:
state = Qt::TouchPointPressed;
@@ -1305,13 +1310,13 @@ QQuickPointerEvent *QQuickPointerMouseEvent::reset(QEvent *event)
default:
break;
}
- m_mousePoint->reset(state, ev->windowPos(), quint64(1) << 24, ev->timestamp()); // mouse has device ID 1
+ m_point->reset(state, ev->windowPos(), quint64(1) << 24, ev->timestamp()); // mouse has device ID 1
return this;
}
-void QQuickPointerMouseEvent::localize(QQuickItem *target)
+void QQuickSinglePointEvent::localize(QQuickItem *target)
{
- m_mousePoint->localizePosition(target);
+ m_point->localizePosition(target);
}
QQuickPointerEvent *QQuickPointerTouchEvent::reset(QEvent *event)
@@ -1412,35 +1417,54 @@ QQuickPointerEvent *QQuickPointerNativeGestureEvent::reset(QEvent *event)
break;
}
quint64 deviceId = QTouchDevicePrivate::get(const_cast<QTouchDevice *>(ev->device()))->id; // a bit roundabout since QTouchDevice::mTouchDeviceId is protected
- m_gesturePoint->reset(state, ev->windowPos(), deviceId << 24, ev->timestamp());
+ m_point->reset(state, ev->windowPos(), deviceId << 24, ev->timestamp());
return this;
}
-
-void QQuickPointerNativeGestureEvent::localize(QQuickItem *target)
-{
- m_gesturePoint->localizePosition(target);
-}
#endif // QT_CONFIG(gestures)
-QQuickEventPoint *QQuickPointerMouseEvent::point(int i) const {
+QQuickEventPoint *QQuickSinglePointEvent::point(int i) const
+{
if (i == 0)
- return m_mousePoint;
+ return m_point;
return nullptr;
}
-QQuickEventPoint *QQuickPointerTouchEvent::point(int i) const {
- if (i >= 0 && i < m_pointCount)
- return m_touchPoints.at(i);
- return nullptr;
+QQuickPointerEvent *QQuickPointerScrollEvent::reset(QEvent *event)
+{
+ m_event = static_cast<QInputEvent*>(event);
+ if (!event)
+ return this;
+#if QT_CONFIG(wheelevent)
+ if (event->type() == QEvent::Wheel) {
+ auto ev = static_cast<QWheelEvent*>(event);
+ m_device = QQuickPointerDevice::genericMouseDevice();
+ m_device->eventDeliveryTargets().clear();
+ // m_button = Qt::NoButton;
+ m_pressedButtons = ev->buttons();
+ m_angleDelta = QVector2D(ev->angleDelta());
+ m_pixelDelta = QVector2D(ev->pixelDelta());
+ m_phase = ev->phase();
+ m_synthSource = ev->source();
+ m_inverted = ev->inverted();
+
+ m_point->reset(Qt::TouchPointMoved, ev->posF(), quint64(1) << 24, ev->timestamp()); // mouse has device ID 1
+ }
+#endif
+ // TODO else if (event->type() == QEvent::Scroll) ...
+ return this;
}
-#if QT_CONFIG(gestures)
-QQuickEventPoint *QQuickPointerNativeGestureEvent::point(int i) const {
- if (i == 0)
- return m_gesturePoint;
+void QQuickPointerScrollEvent::localize(QQuickItem *target)
+{
+ m_point->localizePosition(target);
+}
+
+QQuickEventPoint *QQuickPointerTouchEvent::point(int i) const
+{
+ if (i >= 0 && i < m_pointCount)
+ return m_touchPoints.at(i);
return nullptr;
}
-#endif // QT_CONFIG(gestures)
QQuickEventPoint::QQuickEventPoint(QQuickPointerEvent *parent)
: QObject(parent), m_pointId(0), m_exclusiveGrabber(nullptr), m_timestamp(0), m_pressTimestamp(0),
@@ -1454,17 +1478,19 @@ QQuickPointerEvent *QQuickEventPoint::pointerEvent() const
return static_cast<QQuickPointerEvent *>(parent());
}
-bool QQuickPointerMouseEvent::allPointsAccepted() const {
- return m_mousePoint->isAccepted();
+bool QQuickSinglePointEvent::allPointsAccepted() const
+{
+ return m_point->isAccepted();
}
-bool QQuickPointerMouseEvent::allUpdatedPointsAccepted() const {
- return m_mousePoint->state() == QQuickEventPoint::Pressed || m_mousePoint->isAccepted();
+bool QQuickSinglePointEvent::allUpdatedPointsAccepted() const
+{
+ return m_point->state() == QQuickEventPoint::Pressed || m_point->isAccepted();
}
-bool QQuickPointerMouseEvent::allPointsGrabbed() const
+bool QQuickSinglePointEvent::allPointsGrabbed() const
{
- return m_mousePoint->exclusiveGrabber() != nullptr;
+ return m_point->exclusiveGrabber() != nullptr;
}
QMouseEvent *QQuickPointerMouseEvent::asMouseEvent(const QPointF &localPos) const
@@ -1477,10 +1503,10 @@ QMouseEvent *QQuickPointerMouseEvent::asMouseEvent(const QPointF &localPos) cons
/*!
Returns the exclusive grabber of this event, if any, in a vector.
*/
-QVector<QObject *> QQuickPointerMouseEvent::exclusiveGrabbers() const
+QVector<QObject *> QQuickSinglePointEvent::exclusiveGrabbers() const
{
QVector<QObject *> result;
- if (QObject *grabber = m_mousePoint->exclusiveGrabber())
+ if (QObject *grabber = m_point->exclusiveGrabber())
result << grabber;
return result;
}
@@ -1488,17 +1514,18 @@ QVector<QObject *> QQuickPointerMouseEvent::exclusiveGrabbers() const
/*!
Remove all passive and exclusive grabbers of this event, without notifying.
*/
-void QQuickPointerMouseEvent::clearGrabbers() const {
- m_mousePoint->setGrabberItem(nullptr);
- m_mousePoint->clearPassiveGrabbers();
+void QQuickSinglePointEvent::clearGrabbers() const
+{
+ m_point->setGrabberItem(nullptr);
+ m_point->clearPassiveGrabbers();
}
/*!
Returns whether the given \a handler is the exclusive grabber of this event.
*/
-bool QQuickPointerMouseEvent::hasExclusiveGrabber(const QQuickPointerHandler *handler) const
+bool QQuickSinglePointEvent::hasExclusiveGrabber(const QQuickPointerHandler *handler) const
{
- return m_mousePoint->exclusiveGrabber() == handler;
+ return handler && (m_point->exclusiveGrabber() == handler);
}
bool QQuickPointerMouseEvent::isPressEvent() const
@@ -1526,7 +1553,8 @@ bool QQuickPointerMouseEvent::isReleaseEvent() const
return me && me->type() == QEvent::MouseButtonRelease;
}
-bool QQuickPointerTouchEvent::allPointsAccepted() const {
+bool QQuickPointerTouchEvent::allPointsAccepted() const
+{
for (int i = 0; i < m_pointCount; ++i) {
if (!m_touchPoints.at(i)->isAccepted())
return false;
@@ -1534,7 +1562,8 @@ bool QQuickPointerTouchEvent::allPointsAccepted() const {
return true;
}
-bool QQuickPointerTouchEvent::allUpdatedPointsAccepted() const {
+bool QQuickPointerTouchEvent::allUpdatedPointsAccepted() const
+{
for (int i = 0; i < m_pointCount; ++i) {
auto point = m_touchPoints.at(i);
if (point->state() != QQuickEventPoint::Pressed && !point->isAccepted())
@@ -1571,7 +1600,8 @@ QVector<QObject *> QQuickPointerTouchEvent::exclusiveGrabbers() const
Remove all passive and exclusive grabbers of all touchpoints in this event,
without notifying.
*/
-void QQuickPointerTouchEvent::clearGrabbers() const {
+void QQuickPointerTouchEvent::clearGrabbers() const
+{
for (auto point: m_touchPoints) {
point->setGrabberItem(nullptr);
point->clearPassiveGrabbers();
@@ -1629,7 +1659,8 @@ QVector<QPointF> QQuickPointerEvent::unacceptedPressedPointScenePositions() cons
If the touchpoint cannot be found, this returns nullptr.
Ownership of the event is NOT transferred to the caller.
*/
-QMouseEvent *QQuickPointerTouchEvent::syntheticMouseEvent(int pointID, QQuickItem *relativeTo) const {
+QMouseEvent *QQuickPointerTouchEvent::syntheticMouseEvent(int pointID, QQuickItem *relativeTo) const
+{
const QTouchEvent::TouchPoint *p = touchPointById(pointID);
if (!p)
return nullptr;
@@ -1669,33 +1700,6 @@ QMouseEvent *QQuickPointerTouchEvent::syntheticMouseEvent(int pointID, QQuickIte
}
#if QT_CONFIG(gestures)
-/*!
- Returns the exclusive grabber of this event, if any, in a vector.
-*/
-QVector<QObject *> QQuickPointerNativeGestureEvent::exclusiveGrabbers() const
-{
- QVector<QObject *> result;
- if (QObject *grabber = m_gesturePoint->exclusiveGrabber())
- result << grabber;
- return result;
-}
-
-/*!
- Remove all passive and exclusive grabbers of this event, without notifying.
-*/
-void QQuickPointerNativeGestureEvent::clearGrabbers() const {
- m_gesturePoint->setGrabberItem(nullptr);
- m_gesturePoint->clearPassiveGrabbers();
-}
-
-/*!
- Returns whether the given \a handler is the exclusive grabber of this event.
-*/
-bool QQuickPointerNativeGestureEvent::hasExclusiveGrabber(const QQuickPointerHandler *handler) const
-{
- return m_gesturePoint->exclusiveGrabber() == handler;
-}
-
bool QQuickPointerNativeGestureEvent::isPressEvent() const
{
return type() == Qt::BeginNativeGesture;
@@ -1729,6 +1733,39 @@ qreal QQuickPointerNativeGestureEvent::value() const
#endif // QT_CONFIG(gestures)
/*!
+ Returns whether the scroll event has Qt::ScrollBegin phase. On touchpads
+ which provide phase information, this is true when the fingers are placed
+ on the touchpad and scrolling begins. On other devices where this
+ information is not available, it remains false.
+*/
+bool QQuickPointerScrollEvent::isPressEvent() const
+{
+ return phase() == Qt::ScrollBegin;
+}
+
+/*!
+ Returns true when the scroll event has Qt::ScrollUpdate phase, or when the
+ phase is unknown. Some multi-touch-capable touchpads and trackpads provide
+ phase information; whereas ordinary mouse wheels and other types of
+ trackpads do not, and in such cases this is always true.
+*/
+bool QQuickPointerScrollEvent::isUpdateEvent() const
+{
+ return phase() == Qt::ScrollUpdate || phase() == Qt::NoScrollPhase;
+}
+
+/*!
+ Returns whether the scroll event has Qt::ScrollBegin phase. On touchpads
+ which provide phase information, this is true when the fingers are lifted
+ from the touchpad. On other devices where this information is not
+ available, it remains false.
+*/
+bool QQuickPointerScrollEvent::isReleaseEvent() const
+{
+ return phase() == Qt::ScrollEnd;
+}
+
+/*!
\internal
Returns a pointer to the QQuickEventPoint which has the \a pointId as
\l {QQuickEventPoint::pointId}{pointId}.
@@ -1736,13 +1773,15 @@ qreal QQuickPointerNativeGestureEvent::value() const
\fn QQuickPointerEvent::pointById(int pointId) const
*/
-QQuickEventPoint *QQuickPointerMouseEvent::pointById(int pointId) const {
- if (m_mousePoint && pointId == m_mousePoint->pointId())
- return m_mousePoint;
+QQuickEventPoint *QQuickSinglePointEvent::pointById(int pointId) const
+{
+ if (m_point && pointId == m_point->pointId())
+ return m_point;
return nullptr;
}
-QQuickEventPoint *QQuickPointerTouchEvent::pointById(int pointId) const {
+QQuickEventPoint *QQuickPointerTouchEvent::pointById(int pointId) const
+{
auto it = std::find_if(m_touchPoints.constBegin(), m_touchPoints.constEnd(),
[pointId](const QQuickEventTouchPoint *tp) { return tp->pointId() == pointId; } );
if (it != m_touchPoints.constEnd())
@@ -1750,21 +1789,14 @@ QQuickEventPoint *QQuickPointerTouchEvent::pointById(int pointId) const {
return nullptr;
}
-#if QT_CONFIG(gestures)
-QQuickEventPoint *QQuickPointerNativeGestureEvent::pointById(int pointId) const {
- if (m_gesturePoint && pointId == m_gesturePoint->pointId())
- return m_gesturePoint;
- return nullptr;
-}
-#endif
-
/*!
\internal
Returns a pointer to the original TouchPoint which has the same
\l {QTouchEvent::TouchPoint::id}{id} as \a pointId, if the original event is a
QTouchEvent, and if that point is found. Otherwise, returns nullptr.
*/
-const QTouchEvent::TouchPoint *QQuickPointerTouchEvent::touchPointById(int pointId) const {
+const QTouchEvent::TouchPoint *QQuickPointerTouchEvent::touchPointById(int pointId) const
+{
const QTouchEvent *ev = asTouchEvent();
if (!ev)
return nullptr;
@@ -1875,24 +1907,10 @@ QTouchEvent *QQuickPointerTouchEvent::asTouchEvent() const
return static_cast<QTouchEvent *>(m_event);
}
-#if QT_CONFIG(gestures)
-bool QQuickPointerNativeGestureEvent::allPointsAccepted() const {
- return m_gesturePoint->isAccepted();
-}
-
-bool QQuickPointerNativeGestureEvent::allUpdatedPointsAccepted() const {
- return m_gesturePoint->state() == QQuickEventPoint::Pressed || m_gesturePoint->isAccepted();
-}
-
-bool QQuickPointerNativeGestureEvent::allPointsGrabbed() const
-{
- return m_gesturePoint->exclusiveGrabber() != nullptr;
-}
-#endif // QT_CONFIG(gestures)
-
#ifndef QT_NO_DEBUG_STREAM
-Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerDevice *dev) {
+Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerDevice *dev)
+{
QDebugStateSaver saver(dbg);
dbg.nospace();
if (!dev) {
@@ -1914,7 +1932,8 @@ Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerDevice *
return dbg;
}
-Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerEvent *event) {
+Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerEvent *event)
+{
QDebugStateSaver saver(dbg);
dbg.nospace();
dbg << "QQuickPointerEvent(";
@@ -1933,7 +1952,8 @@ Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickPointerEvent *e
return dbg;
}
-Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickEventPoint *event) {
+Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QQuickEventPoint *event)
+{
QDebugStateSaver saver(dbg);
dbg.nospace();
dbg << "QQuickEventPoint(accepted:" << event->isAccepted()
diff --git a/src/quick/items/qquickevents_p_p.h b/src/quick/items/qquickevents_p_p.h
index b2642735f2..d1a8bbd901 100644
--- a/src/quick/items/qquickevents_p_p.h
+++ b/src/quick/items/qquickevents_p_p.h
@@ -69,6 +69,7 @@ class QQuickPointerMouseEvent;
#if QT_CONFIG(gestures)
class QQuickPointerNativeGestureEvent;
#endif
+class QQuickPointerScrollEvent;
class QQuickPointerTabletEvent;
class QQuickPointerTouchEvent;
class QQuickPointerHandler;
@@ -76,12 +77,12 @@ class QQuickPointerHandler;
class QQuickKeyEvent : public QObject
{
Q_OBJECT
- Q_PROPERTY(int key READ key)
- Q_PROPERTY(QString text READ text)
- Q_PROPERTY(int modifiers READ modifiers)
- Q_PROPERTY(bool isAutoRepeat READ isAutoRepeat)
- Q_PROPERTY(int count READ count)
- Q_PROPERTY(quint32 nativeScanCode READ nativeScanCode)
+ Q_PROPERTY(int key READ key CONSTANT)
+ Q_PROPERTY(QString text READ text CONSTANT)
+ Q_PROPERTY(int modifiers READ modifiers CONSTANT)
+ Q_PROPERTY(bool isAutoRepeat READ isAutoRepeat CONSTANT)
+ Q_PROPERTY(int count READ count CONSTANT)
+ Q_PROPERTY(quint32 nativeScanCode READ nativeScanCode CONSTANT)
Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
public:
@@ -124,16 +125,16 @@ private:
class Q_QUICK_PRIVATE_EXPORT QQuickMouseEvent : public QObject
{
Q_OBJECT
- Q_PROPERTY(qreal x READ x)
- Q_PROPERTY(qreal y READ y)
- Q_PROPERTY(int button READ button)
- Q_PROPERTY(int buttons READ buttons)
- Q_PROPERTY(int modifiers READ modifiers)
- Q_PROPERTY(int source READ source REVISION 7)
- Q_PROPERTY(bool wasHeld READ wasHeld)
- Q_PROPERTY(bool isClick READ isClick)
+ Q_PROPERTY(qreal x READ x CONSTANT)
+ Q_PROPERTY(qreal y READ y CONSTANT)
+ Q_PROPERTY(int button READ button CONSTANT)
+ Q_PROPERTY(int buttons READ buttons CONSTANT)
+ Q_PROPERTY(int modifiers READ modifiers CONSTANT)
+ Q_PROPERTY(int source READ source CONSTANT REVISION 7)
+ Q_PROPERTY(bool wasHeld READ wasHeld CONSTANT)
+ Q_PROPERTY(bool isClick READ isClick CONSTANT)
Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
- Q_REVISION(11) Q_PROPERTY(int flags READ flags)
+ Q_PROPERTY(int flags READ flags CONSTANT REVISION 11)
public:
QQuickMouseEvent()
@@ -192,13 +193,13 @@ private:
class QQuickWheelEvent : public QObject
{
Q_OBJECT
- Q_PROPERTY(qreal x READ x)
- Q_PROPERTY(qreal y READ y)
- Q_PROPERTY(QPoint angleDelta READ angleDelta)
- Q_PROPERTY(QPoint pixelDelta READ pixelDelta)
- Q_PROPERTY(int buttons READ buttons)
- Q_PROPERTY(int modifiers READ modifiers)
- Q_PROPERTY(bool inverted READ inverted)
+ Q_PROPERTY(qreal x READ x CONSTANT)
+ Q_PROPERTY(qreal y READ y CONSTANT)
+ Q_PROPERTY(QPoint angleDelta READ angleDelta CONSTANT)
+ Q_PROPERTY(QPoint pixelDelta READ pixelDelta CONSTANT)
+ Q_PROPERTY(int buttons READ buttons CONSTANT)
+ Q_PROPERTY(int modifiers READ modifiers CONSTANT)
+ Q_PROPERTY(bool inverted READ inverted CONSTANT)
Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
public:
@@ -258,15 +259,15 @@ private:
class Q_QUICK_PRIVATE_EXPORT QQuickEventPoint : public QObject
{
Q_OBJECT
- Q_PROPERTY(QQuickPointerEvent *event READ pointerEvent)
- Q_PROPERTY(QPointF position READ position)
- Q_PROPERTY(QPointF scenePosition READ scenePosition)
- Q_PROPERTY(QPointF scenePressPosition READ scenePressPosition)
- Q_PROPERTY(QPointF sceneGrabPosition READ sceneGrabPosition)
- Q_PROPERTY(State state READ state)
- Q_PROPERTY(int pointId READ pointId)
- Q_PROPERTY(qreal timeHeld READ timeHeld)
- Q_PROPERTY(QVector2D velocity READ velocity)
+ Q_PROPERTY(QQuickPointerEvent *event READ pointerEvent CONSTANT)
+ Q_PROPERTY(QPointF position READ position CONSTANT)
+ Q_PROPERTY(QPointF scenePosition READ scenePosition CONSTANT)
+ Q_PROPERTY(QPointF scenePressPosition READ scenePressPosition CONSTANT)
+ Q_PROPERTY(QPointF sceneGrabPosition READ sceneGrabPosition CONSTANT)
+ Q_PROPERTY(State state READ state CONSTANT)
+ Q_PROPERTY(int pointId READ pointId CONSTANT)
+ Q_PROPERTY(qreal timeHeld READ timeHeld CONSTANT)
+ Q_PROPERTY(QVector2D velocity READ velocity CONSTANT)
Q_PROPERTY(bool accepted READ isAccepted WRITE setAccepted)
Q_PROPERTY(QObject *exclusiveGrabber READ exclusiveGrabber WRITE setExclusiveGrabber)
@@ -280,7 +281,7 @@ public:
Q_DECLARE_FLAGS(States, State)
Q_FLAG(States)
- enum GrabState {
+ enum GrabTransition {
GrabPassive = 0x01,
UngrabPassive = 0x02,
CancelGrabPassive = 0x03,
@@ -289,7 +290,7 @@ public:
UngrabExclusive = 0x20,
CancelGrabExclusive = 0x30,
};
- Q_ENUM(GrabState)
+ Q_ENUM(GrabTransition)
QQuickEventPoint(QQuickPointerEvent *parent);
@@ -385,10 +386,10 @@ private:
class Q_QUICK_PRIVATE_EXPORT QQuickPointerEvent : public QObject
{
Q_OBJECT
- Q_PROPERTY(QQuickPointerDevice *device READ device)
- Q_PROPERTY(Qt::KeyboardModifiers modifiers READ modifiers)
- Q_PROPERTY(Qt::MouseButtons button READ button)
- Q_PROPERTY(Qt::MouseButtons buttons READ buttons)
+ Q_PROPERTY(QQuickPointerDevice *device READ device CONSTANT)
+ Q_PROPERTY(Qt::KeyboardModifiers modifiers READ modifiers CONSTANT)
+ Q_PROPERTY(Qt::MouseButtons button READ button CONSTANT)
+ Q_PROPERTY(Qt::MouseButtons buttons READ buttons CONSTANT)
public:
QQuickPointerEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
@@ -419,16 +420,18 @@ public: // helpers for C++ only (during event delivery)
#if QT_CONFIG(gestures)
virtual QQuickPointerNativeGestureEvent *asPointerNativeGestureEvent() { return nullptr; }
#endif
+ virtual QQuickPointerScrollEvent *asPointerScrollEvent() { return nullptr; }
virtual const QQuickPointerMouseEvent *asPointerMouseEvent() const { return nullptr; }
virtual const QQuickPointerTouchEvent *asPointerTouchEvent() const { return nullptr; }
virtual const QQuickPointerTabletEvent *asPointerTabletEvent() const { return nullptr; }
#if QT_CONFIG(gestures)
virtual const QQuickPointerNativeGestureEvent *asPointerNativeGestureEvent() const { return nullptr; }
#endif
+ virtual const QQuickPointerScrollEvent *asPointerScrollEvent() const { return nullptr; }
virtual bool allPointsAccepted() const = 0;
virtual bool allUpdatedPointsAccepted() const = 0;
virtual bool allPointsGrabbed() const = 0;
- bool isAccepted() { return m_event->isAccepted(); }
+ bool isAccepted() { return m_event ? m_event->isAccepted() : false; }
void setAccepted(bool accepted) { if (m_event) m_event->setAccepted(accepted); }
QVector<QPointF> unacceptedPressedPointScenePositions() const;
@@ -439,7 +442,7 @@ public: // helpers for C++ only (during event delivery)
virtual void clearGrabbers() const = 0;
virtual bool hasExclusiveGrabber(const QQuickPointerHandler *handler) const = 0;
- ulong timestamp() const { return m_event->timestamp(); }
+ ulong timestamp() const { return m_event ? m_event->timestamp() : 0; }
protected:
QQuickPointerDevice *m_device;
@@ -452,21 +455,14 @@ protected:
Q_DISABLE_COPY(QQuickPointerEvent)
};
-class Q_QUICK_PRIVATE_EXPORT QQuickPointerMouseEvent : public QQuickPointerEvent
+class Q_QUICK_PRIVATE_EXPORT QQuickSinglePointEvent : public QQuickPointerEvent
{
Q_OBJECT
public:
- QQuickPointerMouseEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
- : QQuickPointerEvent(parent, device), m_mousePoint(new QQuickEventPoint(this)) { }
+ QQuickSinglePointEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
+ : QQuickPointerEvent(parent, device), m_point(new QQuickEventPoint(this)) { }
- QQuickPointerEvent *reset(QEvent *) override;
void localize(QQuickItem *target) override;
- bool isPressEvent() const override;
- bool isDoubleClickEvent() const override;
- bool isUpdateEvent() const override;
- bool isReleaseEvent() const override;
- QQuickPointerMouseEvent *asPointerMouseEvent() override { return this; }
- const QQuickPointerMouseEvent *asPointerMouseEvent() const override { return this; }
int pointCount() const override { return 1; }
QQuickEventPoint *point(int i) const override;
QQuickEventPoint *pointById(int pointId) const override;
@@ -477,10 +473,28 @@ public:
void clearGrabbers() const override;
bool hasExclusiveGrabber(const QQuickPointerHandler *handler) const override;
- QMouseEvent *asMouseEvent(const QPointF& localPos) const;
+protected:
+ QQuickEventPoint *m_point;
-private:
- QQuickEventPoint *m_mousePoint;
+ Q_DISABLE_COPY(QQuickSinglePointEvent)
+};
+
+class Q_QUICK_PRIVATE_EXPORT QQuickPointerMouseEvent : public QQuickSinglePointEvent
+{
+ Q_OBJECT
+public:
+ QQuickPointerMouseEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
+ : QQuickSinglePointEvent(parent, device) { }
+
+ QQuickPointerEvent *reset(QEvent *) override;
+ bool isPressEvent() const override;
+ bool isDoubleClickEvent() const override;
+ bool isUpdateEvent() const override;
+ bool isReleaseEvent() const override;
+ QQuickPointerMouseEvent *asPointerMouseEvent() override { return this; }
+ const QQuickPointerMouseEvent *asPointerMouseEvent() const override { return this; }
+
+ QMouseEvent *asMouseEvent(const QPointF& localPos) const;
Q_DISABLE_COPY(QQuickPointerMouseEvent)
};
@@ -528,7 +542,7 @@ private:
};
#if QT_CONFIG(gestures)
-class Q_QUICK_PRIVATE_EXPORT QQuickPointerNativeGestureEvent : public QQuickPointerEvent
+class Q_QUICK_PRIVATE_EXPORT QQuickPointerNativeGestureEvent : public QQuickSinglePointEvent
{
Q_OBJECT
Q_PROPERTY(Qt::NativeGestureType type READ type CONSTANT)
@@ -536,34 +550,65 @@ class Q_QUICK_PRIVATE_EXPORT QQuickPointerNativeGestureEvent : public QQuickPoin
public:
QQuickPointerNativeGestureEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
- : QQuickPointerEvent(parent, device), m_gesturePoint(new QQuickEventPoint(this)) { }
+ : QQuickSinglePointEvent(parent, device) { }
QQuickPointerEvent *reset(QEvent *) override;
- void localize(QQuickItem *target) override;
bool isPressEvent() const override;
bool isUpdateEvent() const override;
bool isReleaseEvent() const override;
QQuickPointerNativeGestureEvent *asPointerNativeGestureEvent() override { return this; }
const QQuickPointerNativeGestureEvent *asPointerNativeGestureEvent() const override { return this; }
- int pointCount() const override { return 1; }
- QQuickEventPoint *point(int i) const override;
- QQuickEventPoint *pointById(int pointId) const override;
- bool allPointsAccepted() const override;
- bool allUpdatedPointsAccepted() const override;
- bool allPointsGrabbed() const override;
- QVector<QObject *> exclusiveGrabbers() const override;
- void clearGrabbers() const override;
- bool hasExclusiveGrabber(const QQuickPointerHandler *handler) const override;
Qt::NativeGestureType type() const;
qreal value() const;
-private:
- QQuickEventPoint *m_gesturePoint;
-
Q_DISABLE_COPY(QQuickPointerNativeGestureEvent)
};
#endif // QT_CONFIG(gestures)
+class Q_QUICK_PRIVATE_EXPORT QQuickPointerScrollEvent : public QQuickSinglePointEvent
+{
+ Q_OBJECT
+ Q_PROPERTY(QVector2D angleDelta READ angleDelta CONSTANT)
+ Q_PROPERTY(QVector2D pixelDelta READ pixelDelta CONSTANT)
+ Q_PROPERTY(bool hasAngleDelta READ hasAngleDelta CONSTANT)
+ Q_PROPERTY(bool hasPixelDelta READ hasPixelDelta CONSTANT)
+ Q_PROPERTY(bool inverted READ isInverted CONSTANT)
+
+public:
+ QQuickPointerScrollEvent(QObject *parent = nullptr, QQuickPointerDevice *device = nullptr)
+ : QQuickSinglePointEvent(parent, device) { }
+
+ QQuickPointerEvent *reset(QEvent *) override;
+ void localize(QQuickItem *target) override;
+ bool isPressEvent() const override;
+ bool isUpdateEvent() const override;
+ bool isReleaseEvent() const override;
+ QQuickPointerScrollEvent *asPointerScrollEvent() override { return this; }
+ const QQuickPointerScrollEvent *asPointerScrollEvent() const override { return this; }
+ QVector2D angleDelta() const { return m_angleDelta; }
+ QVector2D pixelDelta() const { return m_pixelDelta; }
+ bool hasAngleDelta() const { return !angleDelta().isNull(); }
+ bool hasPixelDelta() const { return !pixelDelta().isNull(); }
+ bool isInverted() const { return m_inverted; }
+ Qt::ScrollPhase phase() const { return m_phase; }
+
+private:
+ // TODO add QQuickPointerDevice source() whenever QInputEvent is extended to have a source device
+ // then maybe Qt::MouseEventSource synthSource() will be obsolete... that's why it's not public now
+ Qt::MouseEventSource synthSource() const { return m_synthSource; }
+
+private:
+ QVector2D m_angleDelta;
+ QVector2D m_pixelDelta;
+ Qt::ScrollPhase m_phase = Qt::NoScrollPhase;
+ Qt::MouseEventSource m_synthSource = Qt::MouseEventNotSynthesized;
+ bool m_inverted = false;
+
+ friend class QQuickWindowPrivate;
+
+ Q_DISABLE_COPY(QQuickPointerScrollEvent)
+};
+
// ### Qt 6: move this to qtbase, replace QTouchDevice and the enums in QTabletEvent
class Q_QUICK_PRIVATE_EXPORT QQuickPointerDevice : public QObject
@@ -589,7 +634,6 @@ public:
AllDevices = 0x7FFF
};
Q_DECLARE_FLAGS(DeviceTypes, DeviceType)
- Q_ENUM(DeviceType)
Q_FLAG(DeviceTypes)
enum PointerType : qint16 {
@@ -601,7 +645,6 @@ public:
AllPointerTypes = 0x7FFF
};
Q_DECLARE_FLAGS(PointerTypes, PointerType)
- Q_ENUM(PointerType)
Q_FLAG(PointerTypes)
enum CapabilityFlag : qint16 {
@@ -618,7 +661,6 @@ public:
YTilt = 0x1000
};
Q_DECLARE_FLAGS(Capabilities, CapabilityFlag)
- Q_ENUM(CapabilityFlag)
Q_FLAG(Capabilities)
DeviceType type() const { return m_deviceType; }
@@ -629,6 +671,7 @@ public:
int buttonCount() const { return m_buttonCount; }
QString name() const { return m_name; }
QPointingDeviceUniqueId uniqueId() const { return m_uniqueId; }
+ const QTouchDevice *qTouchDevice() const;
static QQuickPointerDevice *touchDevice(const QTouchDevice *d);
static QList<QQuickPointerDevice *> touchDevices();
diff --git a/src/quick/items/qquickflickable.cpp b/src/quick/items/qquickflickable.cpp
index cc35630fff..85045be411 100644
--- a/src/quick/items/qquickflickable.cpp
+++ b/src/quick/items/qquickflickable.cpp
@@ -69,10 +69,6 @@ static const int FlickThreshold = 15;
// will ensure the Flickable retains the grab on consecutive flicks.
static const int RetainGrabVelocity = 100;
-#ifdef Q_OS_OSX
-static const int MovementEndingTimerInterval = 100;
-#endif
-
// Currently std::round can't be used on Android when using ndk g++, so
// use C version instead. We could just define two versions of Round, one
// for float and one for double, but then only one of them would be used
@@ -248,6 +244,7 @@ QQuickFlickablePrivate::QQuickFlickablePrivate()
, stealMouse(false), pressed(false)
, scrollingPhase(false), interactive(true), calcVelocity(false)
, pixelAligned(false)
+ , syncDrag(false)
, lastPosTime(-1)
, lastPressTime(0)
, deceleration(QML_FLICK_DEFAULTDECELERATION)
@@ -508,7 +505,8 @@ static bool fuzzyLessThanOrEqualTo(qreal a, qreal b)
void QQuickFlickablePrivate::updateBeginningEnd()
{
Q_Q(QQuickFlickable);
- bool atBoundaryChange = false;
+ bool atXBeginningChange = false, atXEndChange = false;
+ bool atYBeginningChange = false, atYEndChange = false;
// Vertical
const qreal maxyextent = -q->maxYExtent();
@@ -519,11 +517,11 @@ void QQuickFlickablePrivate::updateBeginningEnd()
if (atBeginning != vData.atBeginning) {
vData.atBeginning = atBeginning;
- atBoundaryChange = true;
+ atYBeginningChange = true;
}
if (atEnd != vData.atEnd) {
vData.atEnd = atEnd;
- atBoundaryChange = true;
+ atYEndChange = true;
}
// Horizontal
@@ -535,11 +533,11 @@ void QQuickFlickablePrivate::updateBeginningEnd()
if (atBeginning != hData.atBeginning) {
hData.atBeginning = atBeginning;
- atBoundaryChange = true;
+ atXBeginningChange = true;
}
if (atEnd != hData.atEnd) {
hData.atEnd = atEnd;
- atBoundaryChange = true;
+ atXEndChange = true;
}
if (vData.extentsChanged) {
@@ -560,8 +558,16 @@ void QQuickFlickablePrivate::updateBeginningEnd()
}
}
- if (atBoundaryChange)
+ if (atXEndChange || atYEndChange || atXBeginningChange || atYBeginningChange)
emit q->isAtBoundaryChanged();
+ if (atXEndChange)
+ emit q->atXEndChanged();
+ if (atXBeginningChange)
+ emit q->atXBeginningChanged();
+ if (atYEndChange)
+ emit q->atYEndChanged();
+ if (atYBeginningChange)
+ emit q->atYBeginningChanged();
if (visibleArea)
visibleArea->updateVisible();
@@ -984,6 +990,33 @@ void QQuickFlickable::setPixelAligned(bool align)
}
}
+/*!
+ \qmlproperty bool QtQuick::Flickable::synchronousDrag
+ \since 5.12
+
+ If this property is set to true, then when the mouse or touchpoint moves
+ far enough to begin dragging the content, the content will jump, such that
+ the content pixel which was under the cursor or touchpoint when pressed
+ remains under that point.
+
+ The default is \c false, which provides a smoother experience (no jump)
+ at the cost that some of the drag distance is "lost" at the beginning.
+*/
+bool QQuickFlickable::synchronousDrag() const
+{
+ Q_D(const QQuickFlickable);
+ return d->syncDrag;
+}
+
+void QQuickFlickable::setSynchronousDrag(bool v)
+{
+ Q_D(QQuickFlickable);
+ if (v != d->syncDrag) {
+ d->syncDrag = v;
+ emit synchronousDragChanged();
+ }
+}
+
qint64 QQuickFlickablePrivate::computeCurrentTime(QInputEvent *event) const
{
if (0 != event->timestamp())
@@ -1100,7 +1133,7 @@ void QQuickFlickablePrivate::drag(qint64 currentTimestamp, QEvent::Type eventTyp
if (overThreshold || elapsedSincePress > 200) {
if (!vMoved)
vData.dragStartOffset = dy;
- qreal newY = dy + vData.pressPos - vData.dragStartOffset;
+ qreal newY = dy + vData.pressPos - (syncDrag ? 0 : vData.dragStartOffset);
// Recalculate bounds in case margins have changed, but use the content
// size estimate taken at the start of the drag in case the drag causes
// the estimate to be altered
@@ -1176,7 +1209,7 @@ void QQuickFlickablePrivate::drag(qint64 currentTimestamp, QEvent::Type eventTyp
if (overThreshold || elapsedSincePress > 200) {
if (!hMoved)
hData.dragStartOffset = dx;
- qreal newX = dx + hData.pressPos - hData.dragStartOffset;
+ qreal newX = dx + hData.pressPos - (syncDrag ? 0 : hData.dragStartOffset);
const qreal minX = hData.dragMinBound + hData.startMargin;
const qreal maxX = hData.dragMaxBound - hData.endMargin;
if (!(boundsBehavior & QQuickFlickable::DragOverBounds)) {
@@ -1280,7 +1313,7 @@ void QQuickFlickablePrivate::drag(qint64 currentTimestamp, QEvent::Type eventTyp
void QQuickFlickablePrivate::handleMouseMoveEvent(QMouseEvent *event)
{
Q_Q(QQuickFlickable);
- if (!interactive || lastPosTime == -1)
+ if (!interactive || lastPosTime == -1 || event->buttons() == Qt::NoButton)
return;
qint64 currentTimestamp = computeCurrentTime(event);
@@ -1460,23 +1493,24 @@ void QQuickFlickable::wheelEvent(QWheelEvent *event)
case Qt::ScrollUpdate:
if (d->scrollingPhase)
d->pressed = true;
-#ifdef Q_OS_MACOS
- // TODO eliminate this timer when ScrollMomentum has been added
- d->movementEndingTimer.start(MovementEndingTimerInterval, this);
-#endif
+ break;
+ case Qt::ScrollMomentum:
+ d->pressed = false;
+ d->scrollingPhase = false;
+ d->draggingEnding();
+ event->accept();
+ d->lastPosTime = -1;
break;
case Qt::ScrollEnd:
- // TODO most of this should be done at transition to ScrollMomentum phase,
- // then do what the movementEndingTimer triggers at transition to ScrollEnd phase
d->pressed = false;
d->scrollingPhase = false;
d->draggingEnding();
event->accept();
returnToBounds();
d->lastPosTime = -1;
-#ifdef Q_OS_MACOS
- d->movementEndingTimer.start(MovementEndingTimerInterval, this);
-#endif
+ d->stealMouse = false;
+ if (!d->velocityTimeline.isActive() && !d->timeline.isActive())
+ movementEnding(true, true);
return;
}
@@ -1672,14 +1706,6 @@ void QQuickFlickable::timerEvent(QTimerEvent *event)
if (d->delayedPressEvent) {
d->replayDelayedPress();
}
- } else if (event->timerId() == d->movementEndingTimer.timerId()) {
- d->movementEndingTimer.stop();
- if (!d->scrollingPhase) {
- d->pressed = false;
- d->stealMouse = false;
- if (!d->velocityTimeline.isActive() && !d->timeline.isActive())
- movementEnding(true, true);
- }
}
}
@@ -1821,8 +1847,8 @@ void QQuickFlickable::flick(qreal xVelocity, qreal yVelocity)
d->vData.velocity = yVelocity;
d->hData.vTime = d->vData.vTime = d->timeline.time();
- bool flickedX = d->flickX(xVelocity);
- bool flickedY = d->flickY(yVelocity);
+ const bool flickedX = xflick() && !qFuzzyIsNull(xVelocity) && d->flickX(xVelocity);
+ const bool flickedY = yflick() && !qFuzzyIsNull(yVelocity) && d->flickY(yVelocity);
if (flickedX)
d->hMoved = true;
@@ -2540,7 +2566,7 @@ void QQuickFlickablePrivate::draggingStarting()
void QQuickFlickablePrivate::draggingEnding()
{
Q_Q(QQuickFlickable);
- bool wasDragging = hData.dragging || vData.dragging;
+ const bool wasDragging = hData.dragging || vData.dragging;
if (hData.dragging) {
hData.dragging = false;
emit q->draggingHorizontallyChanged();
@@ -2549,12 +2575,14 @@ void QQuickFlickablePrivate::draggingEnding()
vData.dragging = false;
emit q->draggingVerticallyChanged();
}
- if (wasDragging && !hData.dragging && !vData.dragging) {
- emit q->draggingChanged();
- emit q->dragEnded();
+ if (wasDragging) {
+ if (!hData.dragging && !vData.dragging) {
+ emit q->draggingChanged();
+ emit q->dragEnded();
+ }
+ hData.inRebound = false;
+ vData.inRebound = false;
}
- hData.inRebound = false;
- vData.inRebound = false;
}
bool QQuickFlickablePrivate::isViewMoving() const
diff --git a/src/quick/items/qquickflickable_p.h b/src/quick/items/qquickflickable_p.h
index 939e3af698..b7c4fa5b67 100644
--- a/src/quick/items/qquickflickable_p.h
+++ b/src/quick/items/qquickflickable_p.h
@@ -98,14 +98,15 @@ class Q_QUICK_PRIVATE_EXPORT QQuickFlickable : public QQuickItem
Q_PROPERTY(bool interactive READ isInteractive WRITE setInteractive NOTIFY interactiveChanged)
Q_PROPERTY(int pressDelay READ pressDelay WRITE setPressDelay NOTIFY pressDelayChanged)
- Q_PROPERTY(bool atXEnd READ isAtXEnd NOTIFY isAtBoundaryChanged)
- Q_PROPERTY(bool atYEnd READ isAtYEnd NOTIFY isAtBoundaryChanged)
- Q_PROPERTY(bool atXBeginning READ isAtXBeginning NOTIFY isAtBoundaryChanged)
- Q_PROPERTY(bool atYBeginning READ isAtYBeginning NOTIFY isAtBoundaryChanged)
+ Q_PROPERTY(bool atXEnd READ isAtXEnd NOTIFY atXEndChanged)
+ Q_PROPERTY(bool atYEnd READ isAtYEnd NOTIFY atYEndChanged)
+ Q_PROPERTY(bool atXBeginning READ isAtXBeginning NOTIFY atXBeginningChanged)
+ Q_PROPERTY(bool atYBeginning READ isAtYBeginning NOTIFY atYBeginningChanged)
Q_PROPERTY(QQuickFlickableVisibleArea *visibleArea READ visibleArea CONSTANT)
Q_PROPERTY(bool pixelAligned READ pixelAligned WRITE setPixelAligned NOTIFY pixelAlignedChanged)
+ Q_PROPERTY(bool synchronousDrag READ synchronousDrag WRITE setSynchronousDrag NOTIFY synchronousDragChanged REVISION 12)
Q_PROPERTY(qreal horizontalOvershoot READ horizontalOvershoot NOTIFY horizontalOvershootChanged REVISION 9)
Q_PROPERTY(qreal verticalOvershoot READ verticalOvershoot NOTIFY verticalOvershootChanged REVISION 9)
@@ -213,6 +214,9 @@ public:
bool pixelAligned() const;
void setPixelAligned(bool align);
+ bool synchronousDrag() const;
+ void setSynchronousDrag(bool v);
+
qreal horizontalOvershoot() const;
qreal verticalOvershoot() const;
@@ -259,9 +263,16 @@ Q_SIGNALS:
void dragStarted();
void dragEnded();
void pixelAlignedChanged();
+ Q_REVISION(12) void synchronousDragChanged();
Q_REVISION(9) void horizontalOvershootChanged();
Q_REVISION(9) void verticalOvershootChanged();
+ // The next four signals should be marked as Q_REVISION(12). See QTBUG-71243
+ void atXEndChanged();
+ void atYEndChanged();
+ void atXBeginningChanged();
+ void atYBeginningChanged();
+
protected:
bool childMouseEventFilter(QQuickItem *, QEvent *) override;
void mousePressEvent(QMouseEvent *event) override;
diff --git a/src/quick/items/qquickflickable_p_p.h b/src/quick/items/qquickflickable_p_p.h
index 08f069e830..c538cf7878 100644
--- a/src/quick/items/qquickflickable_p_p.h
+++ b/src/quick/items/qquickflickable_p_p.h
@@ -221,8 +221,8 @@ public:
bool interactive : 1;
bool calcVelocity : 1;
bool pixelAligned : 1;
+ bool syncDrag : 1;
QElapsedTimer timer;
- QBasicTimer movementEndingTimer;
qint64 lastPosTime;
qint64 lastPressTime;
QPointF lastPos;
diff --git a/src/quick/items/qquickgridview.cpp b/src/quick/items/qquickgridview.cpp
index f2fa66332c..272d4a4df5 100644
--- a/src/quick/items/qquickgridview.cpp
+++ b/src/quick/items/qquickgridview.cpp
@@ -417,11 +417,11 @@ qreal QQuickGridViewPrivate::contentXForPosition(qreal pos) const
if (flow == QQuickGridView::FlowLeftToRight) {
// vertical scroll
if (q->effectiveLayoutDirection() == Qt::LeftToRight) {
- return 0;
+ return -q->leftMargin();
} else {
qreal colSize = cellWidth;
- int columns = q->width()/colSize;
- return -q->width() + (cellWidth * columns);
+ int columns = (q->width() - q->leftMargin() - q->rightMargin()) / colSize;
+ return -q->width() + q->rightMargin() + (cellWidth * columns);
}
} else {
// horizontal scroll
@@ -444,16 +444,18 @@ qreal QQuickGridViewPrivate::contentYForPosition(qreal pos) const
} else {
// horizontal scroll
if (verticalLayoutDirection == QQuickItemView::TopToBottom)
- return 0;
+ return -q->topMargin();
else
- return -q->height();
+ return -q->height() + q->bottomMargin();
}
}
void QQuickGridViewPrivate::resetColumns()
{
Q_Q(QQuickGridView);
- qreal length = flow == QQuickGridView::FlowLeftToRight ? q->width() : q->height();
+ qreal length = flow == QQuickGridView::FlowLeftToRight
+ ? q->width() - q->leftMargin() - q->rightMargin()
+ : q->height() - q->topMargin() - q->bottomMargin();
columns = qMax(1, qFloor(length / colSize()));
}
@@ -914,7 +916,7 @@ void QQuickGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
qreal tempPosition = isContentFlowReversed() ? -position()-size() : position();
if (snapMode == QQuickGridView::SnapOneRow && moveReason == Mouse) {
// if we've been dragged < rowSize()/2 then bias towards the next row
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = 0;
if (data.velocity > 0 && dist > QML_FLICK_SNAPONETHRESHOLD && dist < rowSize()/2)
bias = rowSize()/2;
@@ -925,13 +927,13 @@ void QQuickGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
tempPosition -= bias;
}
FxViewItem *topItem = snapItemAt(tempPosition+highlightRangeStart);
- if (strictHighlightRange && currentItem && (!topItem || topItem->index != currentIndex)) {
+ if (strictHighlightRange && currentItem && (!topItem || (topItem->index != currentIndex && fixupMode == Immediate))) {
// StrictlyEnforceRange always keeps an item in range
updateHighlight();
topItem = currentItem;
}
FxViewItem *bottomItem = snapItemAt(tempPosition+highlightRangeEnd);
- if (strictHighlightRange && currentItem && (!bottomItem || bottomItem->index != currentIndex)) {
+ if (strictHighlightRange && currentItem && (!bottomItem || (bottomItem->index != currentIndex && fixupMode == Immediate))) {
// StrictlyEnforceRange always keeps an item in range
updateHighlight();
bottomItem = currentItem;
@@ -1013,7 +1015,7 @@ bool QQuickGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExte
if (data.move.value() < minExtent) {
if (snapMode == QQuickGridView::SnapOneRow) {
// if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = dist < rowSize()/2 ? rowSize()/2 : 0;
if (isContentFlowReversed())
bias = -bias;
@@ -1030,7 +1032,7 @@ bool QQuickGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExte
if (data.move.value() > maxExtent) {
if (snapMode == QQuickGridView::SnapOneRow) {
// if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = -dist < rowSize()/2 ? rowSize()/2 : 0;
if (isContentFlowReversed())
bias = -bias;
@@ -1309,13 +1311,14 @@ void QQuickGridView::setHighlightFollowsCurrentItem(bool autoHighlight)
/*!
- \qmlproperty model QtQuick::GridView::model
- This property holds the model providing data for the grid.
+ \qmlproperty model QtQuick::GridView::model
+ This property holds the model providing data for the grid.
The model provides the set of data that is used to create the items
- in the view. Models can be created directly in QML using \l ListModel, \l XmlListModel
- or \l VisualItemModel, or provided by C++ model classes. If a C++ model class is
- used, it must be a subclass of \l QAbstractItemModel or a simple list.
+ in the view. Models can be created directly in QML using \l ListModel,
+ \l XmlListModel, \l DelegateModel, or \l ObjectModel, or provided by C++
+ model classes. If a C++ model class is used, it must be a subclass of
+ \l QAbstractItemModel or a simple list.
\sa {qml-data-models}{Data Models}
*/
diff --git a/src/quick/items/qquickitem.cpp b/src/quick/items/qquickitem.cpp
index 154e3241b1..064406ee3c 100644
--- a/src/quick/items/qquickitem.cpp
+++ b/src/quick/items/qquickitem.cpp
@@ -67,6 +67,7 @@
#include <QtQuick/private/qquickstate_p.h>
#include <private/qquickitem_p.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>
+#include <QtQuick/private/qquickhoverhandler_p.h>
#include <QtQuick/private/qquickpointerhandler_p.h>
#include <private/qv4engine_p.h>
@@ -356,7 +357,7 @@ void QQuickItemKeyFilter::componentComplete()
\qmltype KeyNavigation
\instantiates QQuickKeyNavigationAttached
\inqmlmodule QtQuick
- \ingroup qtquick-input
+ \ingroup qtquick-input-handlers
\brief Supports key navigation by arrow keys.
Key-based user interfaces commonly allow the use of arrow keys to navigate between
@@ -815,7 +816,7 @@ bool QQuickKeysAttached::isConnected(const char *signalName) const
\qmltype Keys
\instantiates QQuickKeysAttached
\inqmlmodule QtQuick
- \ingroup qtquick-input
+ \ingroup qtquick-input-handlers
\brief Provides key handling to Items.
All visual primitives support key handling via the Keys
@@ -2453,20 +2454,19 @@ bool QQuickItemPrivate::canAcceptTabFocus(QQuickItem *item)
return true;
#if QT_CONFIG(accessibility)
- if (QObject *acc = qmlAttachedPropertiesObject<QQuickAccessibleAttached>(item, false)) {
- int role = acc->property("role").toInt();
- if (role == QAccessible::EditableText
- || role == QAccessible::Table
- || role == QAccessible::List
- || role == QAccessible::SpinBox) {
- return true;
- } else if (role == QAccessible::ComboBox) {
- QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(item);
+ QAccessible::Role role = QQuickItemPrivate::get(item)->accessibleRole();
+ if (role == QAccessible::EditableText || role == QAccessible::Table || role == QAccessible::List) {
+ return true;
+ } else if (role == QAccessible::ComboBox || role == QAccessible::SpinBox) {
+ if (QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(item))
return iface->state().editable;
- }
}
#endif
+ QVariant editable = item->property("editable");
+ if (editable.isValid())
+ return editable.toBool();
+
QVariant readonly = item->property("readOnly");
if (readonly.isValid() && !readonly.toBool() && item->property("text").isValid())
return true;
@@ -2565,8 +2565,19 @@ QQuickItem* QQuickItemPrivate::nextPrevItemInTabFocusChain(QQuickItem *item, boo
from = item->parentItem();
}
bool skip = false;
- QQuickItem * startItem = item;
- QQuickItem * firstFromItem = from;
+
+ QQuickItem *startItem = item;
+ // Protect from endless loop:
+ // If we start on an invisible item we will not find it again.
+ // If there is no other item which can become the focus item, we have a forever loop,
+ // since the protection only works if we encounter the first item again.
+ while (startItem && !startItem->isVisible()) {
+ startItem = startItem->parentItem();
+ }
+ if (!startItem)
+ return item;
+
+ QQuickItem *firstFromItem = from;
QQuickItem *current = item;
qCDebug(DBG_FOCUS) << "QQuickItemPrivate::nextPrevItemInTabFocusChain: startItem:" << startItem;
qCDebug(DBG_FOCUS) << "QQuickItemPrivate::nextPrevItemInTabFocusChain: firstFromItem:" << firstFromItem;
@@ -4069,8 +4080,6 @@ void QQuickItem::mouseDoubleClickEvent(QMouseEvent *)
/*!
This event handler can be reimplemented in a subclass to be notified
when a mouse ungrab event has occurred on this item.
-
- \input item.qdocinc accepting-events
*/
void QQuickItem::mouseUngrabEvent()
{
@@ -4080,8 +4089,6 @@ void QQuickItem::mouseUngrabEvent()
/*!
This event handler can be reimplemented in a subclass to be notified
when a touch ungrab event has occurred on this item.
-
- \input item.qdocinc accepting-events
*/
void QQuickItem::touchUngrabEvent()
{
@@ -5201,6 +5208,17 @@ void QQuickItemPrivate::deliverShortcutOverrideEvent(QKeyEvent *event)
}
}
+bool QQuickItemPrivate::anyPointerHandlerWants(QQuickEventPoint *point) const
+{
+ if (!hasPointerHandlers())
+ return false;
+ for (QQuickPointerHandler *handler : extra->pointerHandlers) {
+ if (handler->wantsEventPoint(point))
+ return true;
+ }
+ return false;
+}
+
/*!
\internal
Deliver the \a event to all PointerHandlers which are in the pre-determined
@@ -7404,6 +7422,8 @@ void QQuickItemPrivate::setHasHoverInChild(bool hasHover)
QQuickItemPrivate *otherChildPrivate = QQuickItemPrivate::get(otherChild);
if (otherChildPrivate->subtreeHoverEnabled || otherChildPrivate->hoverEnabled)
return; // nope! sorry, something else wants it kept on.
+ if (otherChildPrivate->hasHoverHandlers())
+ return; // nope! sorry, we have pointer handlers which are interested.
}
}
@@ -8177,6 +8197,16 @@ bool QQuickItemPrivate::hasPointerHandlers() const
return extra.isAllocated() && !extra->pointerHandlers.isEmpty();
}
+bool QQuickItemPrivate::hasHoverHandlers() const
+{
+ if (!hasPointerHandlers())
+ return false;
+ for (QQuickPointerHandler *h : extra->pointerHandlers)
+ if (qmlobject_cast<QQuickHoverHandler *>(h))
+ return true;
+ return false;
+}
+
#if QT_CONFIG(quick_shadereffect)
QQuickItemLayer::QQuickItemLayer(QQuickItem *item)
: m_item(item)
@@ -8762,7 +8792,7 @@ void QV4::Heap::QQuickItemWrapper::markObjects(QV4::Heap::Base *that, QV4::MarkS
quint64 QQuickItemPrivate::_q_createJSWrapper(QV4::ExecutionEngine *engine)
{
- return (engine->memoryManager->allocObject<QQuickItemWrapper>(q_func()))->asReturnedValue();
+ return (engine->memoryManager->allocate<QQuickItemWrapper>(q_func()))->asReturnedValue();
}
QT_END_NAMESPACE
diff --git a/src/quick/items/qquickitem.h b/src/quick/items/qquickitem.h
index cfdb2ad5b7..6f601e0872 100644
--- a/src/quick/items/qquickitem.h
+++ b/src/quick/items/qquickitem.h
@@ -163,6 +163,7 @@ public:
// Remember to increment the size of QQuickItemPrivate::flags
};
Q_DECLARE_FLAGS(Flags, Flag)
+ Q_FLAG(Flags)
enum ItemChange {
ItemChildAddedChange, // value.item
diff --git a/src/quick/items/qquickitem_p.h b/src/quick/items/qquickitem_p.h
index 0204ac07c5..11b47114cf 100644
--- a/src/quick/items/qquickitem_p.h
+++ b/src/quick/items/qquickitem_p.h
@@ -280,6 +280,7 @@ public:
QQuickItemLayer *layer() const;
bool hasPointerHandlers() const;
+ bool hasHoverHandlers() const;
// data property
static void data_append(QQmlListProperty<QObject> *, QObject *);
@@ -330,12 +331,26 @@ public:
Q_DECLARE_FLAGS(ChangeTypes, ChangeType)
struct ChangeListener {
- ChangeListener(QQuickItemChangeListener *l = nullptr, QQuickItemPrivate::ChangeTypes t = nullptr) : listener(l), types(t), gTypes(QQuickGeometryChange::All) {}
- ChangeListener(QQuickItemChangeListener *l, QQuickGeometryChange gt) : listener(l), types(Geometry), gTypes(gt) {}
+ using ChangeTypes = QQuickItemPrivate::ChangeTypes;
+
+ ChangeListener(QQuickItemChangeListener *l = nullptr, ChangeTypes t = nullptr)
+ : listener(l)
+ , types(t)
+ , gTypes(QQuickGeometryChange::All)
+ {}
+
+ ChangeListener(QQuickItemChangeListener *l, QQuickGeometryChange gt)
+ : listener(l)
+ , types(Geometry)
+ , gTypes(gt)
+ {}
+
+ bool operator==(const ChangeListener &other) const
+ { return listener == other.listener && types == other.types; }
+
QQuickItemChangeListener *listener;
- QQuickItemPrivate::ChangeTypes types;
+ ChangeTypes types;
QQuickGeometryChange gTypes; //NOTE: not used for ==
- bool operator==(const ChangeListener &other) const { return listener == other.listener && types == other.types; }
};
struct ExtraData {
@@ -582,6 +597,7 @@ public:
#endif
void deliverShortcutOverrideEvent(QKeyEvent *);
+ bool anyPointerHandlerWants(QQuickEventPoint *point) const;
virtual bool handlePointerEvent(QQuickPointerEvent *, bool avoidExclusiveGrabber = false);
virtual void setVisible(bool visible);
diff --git a/src/quick/items/qquickitemsmodule.cpp b/src/quick/items/qquickitemsmodule.cpp
index 51a91e1f7a..a20150e3b9 100644
--- a/src/quick/items/qquickitemsmodule.cpp
+++ b/src/quick/items/qquickitemsmodule.cpp
@@ -64,6 +64,9 @@
#if QT_CONFIG(quick_pathview)
#include "qquickpathview_p.h"
#endif
+#if QT_CONFIG(quick_tableview)
+#include "qquicktableview_p.h"
+#endif
#if QT_CONFIG(quick_viewtransitions)
#include "qquickitemviewtransition_p.h"
#endif
@@ -113,6 +116,12 @@
#include <private/qqmlmetatype_p.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>
+#include "handlers/qquickdraghandler_p.h"
+#include "handlers/qquickhoverhandler_p.h"
+#include "handlers/qquickpinchhandler_p.h"
+#include "handlers/qquickpointhandler_p.h"
+#include "handlers/qquicktaphandler_p.h"
+
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcTransient)
QT_END_NAMESPACE
@@ -135,6 +144,9 @@ static QQmlPrivate::AutoParentResult qquickitem_autoParent(QObject *obj, QObject
win->setTransientParent(parentItem->window());
return QQmlPrivate::Parented;
}
+ } else if (QQuickPointerHandler *handler = qmlobject_cast<QQuickPointerHandler *>(obj)) {
+ handler->setParent(parent);
+ return QQmlPrivate::Parented;
}
return QQmlPrivate::IncompatibleObject;
} else if (QQuickWindow *parentWindow = qmlobject_cast<QQuickWindow *>(parent)) {
@@ -422,6 +434,42 @@ static void qt_quickitems_defineModule(const char *uri, int major, int minor)
qmlRegisterType<QQuickAnimatedImage, 11>(uri, 2, 11,"AnimatedImage");
#endif
qmlRegisterType<QQuickItem, 11>(uri, 2, 11,"Item");
+ qmlRegisterType<QQuickFlickable, 12>(uri, 2, 12, "Flickable");
+
+ // classes related to Input Handlers which are newly exposed since 5.12
+ qmlRegisterUncreatableType<QQuickPointerEvent>(uri, 2, 12, "PointerEvent",
+ QQuickPointerHandler::tr("PointerEvent is only available as a parameter of several signals in PointerHandler"));
+ qmlRegisterUncreatableType<QQuickPointerMouseEvent>(uri, 2, 12, "PointerMouseEvent",
+ QQuickPointerHandler::tr("PointerMouseEvent is only available as a parameter of several signals in PointerHandler"));
+ qmlRegisterUncreatableType<QQuickPointerTouchEvent>(uri, 2, 12, "PointerTouchEvent",
+ QQuickPointerHandler::tr("PointerTouchEvent is only available as a parameter of several signals in PointerHandler"));
+ qmlRegisterUncreatableType<QQuickEventPoint>(uri, 2, 12, "EventPoint",
+ QQuickPointerHandler::tr("EventPoint is only available as a member of PointerEvent"));
+ qmlRegisterUncreatableType<QQuickEventTouchPoint>(uri, 2, 12, "EventTouchPoint",
+ QQuickPointerHandler::tr("EventTouchPoint is only available as a member of PointerEvent"));
+ qmlRegisterUncreatableType<QQuickPointerDevice>(uri, 2, 12, "PointerDevice",
+ QQuickPointerHandler::tr("PointerDevice is only available as a property of PointerEvent"));
+
+ // Input Handlers are part of QtQuick, not a separate module, since 5.12
+ qmlRegisterUncreatableType<QQuickPointerHandler>(uri, 2, 12, "PointerHandler",
+ QQuickPointerHandler::tr("PointerHandler is an abstract base class"));
+ qmlRegisterType<QQuickPointHandler>(uri, 2, 12, "PointHandler");
+ qmlRegisterType<QQuickDragHandler>(uri, 2, 12, "DragHandler");
+ qmlRegisterUncreatableType<QQuickDragAxis>(uri, 2, 12, "DragAxis",
+ QQuickDragHandler::tr("DragAxis is only available as a grouped property of DragHandler"));
+ qmlRegisterType<QQuickHoverHandler>(uri, 2, 12, "HoverHandler");
+ qmlRegisterType<QQuickPinchHandler>(uri, 2, 12, "PinchHandler");
+ qmlRegisterType<QQuickTapHandler>(uri, 2, 12, "TapHandler");
+ qRegisterMetaType<QQuickHandlerPoint>();
+
+ // The rest of the 5.12 revisions
+ qmlRegisterType<QQuickAnimatedSprite, 12>("QtQuick", 2, 12, "AnimatedSprite");
+ qmlRegisterType<QQuickGradient, 12>(uri, 2, 12, "Gradient");
+ qmlRegisterType<QQuickFlickable, 12>(uri, 2, 12, "Flickable");
+ qmlRegisterType<QQuickText, 12>(uri, 2, 12, "Text");
+#if QT_CONFIG(quick_tableview)
+ qmlRegisterType<QQuickTableView>(uri, 2, 12, "TableView");
+#endif
}
static void initResources()
diff --git a/src/quick/items/qquickitemview.cpp b/src/quick/items/qquickitemview.cpp
index f2e055e874..8dafc16cf4 100644
--- a/src/quick/items/qquickitemview.cpp
+++ b/src/quick/items/qquickitemview.cpp
@@ -38,6 +38,7 @@
****************************************************************************/
#include "qquickitemview_p_p.h"
+#include "qquickitemviewfxitem_p_p.h"
#include <QtQuick/private/qquicktransition_p.h>
#include <QtQml/QQmlInfo>
#include "qplatformdefs.h"
@@ -52,117 +53,14 @@ Q_LOGGING_CATEGORY(lcItemViewDelegateLifecycle, "qt.quick.itemview.lifecycle")
#endif
FxViewItem::FxViewItem(QQuickItem *i, QQuickItemView *v, bool own, QQuickItemViewAttached *attached)
- : item(i)
+ : QQuickItemViewFxItem(i, own, QQuickItemViewPrivate::get(v))
, view(v)
- , transitionableItem(nullptr)
, attached(attached)
- , ownItem(own)
- , releaseAfterTransition(false)
- , trackGeom(false)
{
if (attached) // can be null for default components (see createComponentItem)
attached->setView(view);
}
-FxViewItem::~FxViewItem()
-{
- delete transitionableItem;
- if (ownItem && item) {
- trackGeometry(false);
- item->setParentItem(nullptr);
- item->deleteLater();
- item = nullptr;
- }
-}
-
-qreal FxViewItem::itemX() const
-{
- return transitionableItem ? transitionableItem->itemX() : (item ? item->x() : 0);
-}
-
-qreal FxViewItem::itemY() const
-{
- return transitionableItem ? transitionableItem->itemY() : (item ? item->y() : 0);
-}
-
-void FxViewItem::moveTo(const QPointF &pos, bool immediate)
-{
- if (transitionableItem)
- transitionableItem->moveTo(pos, immediate);
- else if (item)
- item->setPosition(pos);
-}
-
-void FxViewItem::setVisible(bool visible)
-{
- if (!visible && transitionableItem && transitionableItem->transitionScheduledOrRunning())
- return;
- if (item)
- QQuickItemPrivate::get(item)->setCulled(!visible);
-}
-
-void FxViewItem::trackGeometry(bool track)
-{
- if (track) {
- if (!trackGeom) {
- if (item) {
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->addItemChangeListener(QQuickItemViewPrivate::get(view), QQuickItemPrivate::Geometry);
- }
- trackGeom = true;
- }
- } else {
- if (trackGeom) {
- if (item) {
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
- itemPrivate->removeItemChangeListener(QQuickItemViewPrivate::get(view), QQuickItemPrivate::Geometry);
- }
- trackGeom = false;
- }
- }
-}
-
-QQuickItemViewTransitioner::TransitionType FxViewItem::scheduledTransitionType() const
-{
- return transitionableItem ? transitionableItem->nextTransitionType : QQuickItemViewTransitioner::NoTransition;
-}
-
-bool FxViewItem::transitionScheduledOrRunning() const
-{
- return transitionableItem ? transitionableItem->transitionScheduledOrRunning() : false;
-}
-
-bool FxViewItem::transitionRunning() const
-{
- return transitionableItem ? transitionableItem->transitionRunning() : false;
-}
-
-bool FxViewItem::isPendingRemoval() const
-{
- return transitionableItem ? transitionableItem->isPendingRemoval() : false;
-}
-
-void FxViewItem::transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget)
-{
- if (!transitioner)
- return;
- if (!transitionableItem)
- transitionableItem = new QQuickItemViewTransitionableItem(item);
- transitioner->transitionNextReposition(transitionableItem, type, asTarget);
-}
-
-bool FxViewItem::prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds)
-{
- return transitionableItem ? transitionableItem->prepareTransition(transitioner, index, viewBounds) : false;
-}
-
-void FxViewItem::startTransition(QQuickItemViewTransitioner *transitioner)
-{
- if (transitionableItem)
- transitionableItem->startTransition(transitioner, index);
-}
-
-
QQuickItemViewChangeSet::QQuickItemViewChangeSet()
: active(false)
{
@@ -931,6 +829,8 @@ void QQuickItemViewPrivate::positionViewAtIndex(int index, int mode)
if (mode < QQuickItemView::Beginning || mode > QQuickItemView::SnapPosition)
return;
+ Q_Q(QQuickItemView);
+ q->cancelFlick();
applyPendingChanges();
const int modelCount = model->count();
int idx = qMax(qMin(index, modelCount - 1), 0);
@@ -1285,6 +1185,7 @@ void QQuickItemView::modelUpdated(const QQmlChangeSet &changeSet, bool reset)
{
Q_D(QQuickItemView);
if (reset) {
+ cancelFlick();
if (d->transitioner)
d->transitioner->setPopulateTransitionEnabled(true);
d->moveReason = QQuickItemViewPrivate::SetIndex;
@@ -1329,6 +1230,12 @@ void QQuickItemView::trackedPositionChanged()
Q_D(QQuickItemView);
if (!d->trackedItem || !d->currentItem)
return;
+
+ if (d->inLayout) {
+ polish();
+ return;
+ }
+
if (d->moveReason == QQuickItemViewPrivate::SetIndex) {
qreal trackedPos = d->trackedItem->position();
qreal trackedSize = d->trackedItem->size();
diff --git a/src/quick/items/qquickitemview_p_p.h b/src/quick/items/qquickitemview_p_p.h
index e250cf0ccb..ea5b5df9c6 100644
--- a/src/quick/items/qquickitemview_p_p.h
+++ b/src/quick/items/qquickitemview_p_p.h
@@ -56,6 +56,7 @@
QT_REQUIRE_CONFIG(quick_itemview);
#include "qquickitemview_p.h"
+#include "qquickitemviewfxitem_p_p.h"
#include "qquickitemviewtransition_p.h"
#include "qquickflickable_p_p.h"
#include <QtQml/private/qqmlobjectmodel_p.h>
@@ -65,47 +66,13 @@ QT_REQUIRE_CONFIG(quick_itemview);
QT_BEGIN_NAMESPACE
-
-class Q_AUTOTEST_EXPORT FxViewItem
+class Q_AUTOTEST_EXPORT FxViewItem : public QQuickItemViewFxItem
{
public:
FxViewItem(QQuickItem *, QQuickItemView *, bool own, QQuickItemViewAttached *attached);
- virtual ~FxViewItem();
-
- qreal itemX() const;
- qreal itemY() const;
- inline qreal itemWidth() const { return item ? item->width() : 0; }
- inline qreal itemHeight() const { return item ? item->height() : 0; }
-
- void moveTo(const QPointF &pos, bool immediate);
- void setVisible(bool visible);
- void trackGeometry(bool track);
-
- QQuickItemViewTransitioner::TransitionType scheduledTransitionType() const;
- bool transitionScheduledOrRunning() const;
- bool transitionRunning() const;
- bool isPendingRemoval() const;
-
- void transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget);
- bool prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds);
- void startTransition(QQuickItemViewTransitioner *transitioner);
-
- // these are positions and sizes along the current direction of scrolling/flicking
- virtual qreal position() const = 0;
- virtual qreal endPosition() const = 0;
- virtual qreal size() const = 0;
- virtual qreal sectionSize() const = 0;
-
- virtual bool contains(qreal x, qreal y) const = 0;
- QPointer<QQuickItem> item;
QQuickItemView *view;
- QQuickItemViewTransitionableItem *transitionableItem;
QQuickItemViewAttached *attached;
- int index;
- bool ownItem;
- bool releaseAfterTransition;
- bool trackGeom;
};
diff --git a/src/quick/items/qquickitemviewfxitem.cpp b/src/quick/items/qquickitemviewfxitem.cpp
new file mode 100644
index 0000000000..f9c65967ea
--- /dev/null
+++ b/src/quick/items/qquickitemviewfxitem.cpp
@@ -0,0 +1,165 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 "qquickitemviewfxitem_p_p.h"
+#include "qquickitem_p.h"
+#include "qquickitemview_p_p.h"
+
+QT_BEGIN_NAMESPACE
+
+QQuickItemViewFxItem::QQuickItemViewFxItem(QQuickItem *item, bool ownItem, QQuickItemChangeListener* changeListener)
+ : item(item)
+ , ownItem(ownItem)
+ , changeListener(changeListener)
+ , transitionableItem(nullptr)
+ , releaseAfterTransition(false)
+ , trackGeom(false)
+{
+}
+
+QQuickItemViewFxItem::~QQuickItemViewFxItem()
+{
+ delete transitionableItem;
+ if (ownItem && item) {
+ trackGeometry(false);
+ item->setParentItem(0);
+ item->deleteLater();
+ }
+}
+
+qreal QQuickItemViewFxItem::itemX() const
+{
+ return transitionableItem ? transitionableItem->itemX() : (item ? item->x() : 0);
+}
+
+qreal QQuickItemViewFxItem::itemY() const
+{
+ return transitionableItem ? transitionableItem->itemY() : (item ? item->y() : 0);
+}
+
+void QQuickItemViewFxItem::moveTo(const QPointF &pos, bool immediate)
+{
+ if (transitionableItem)
+ transitionableItem->moveTo(pos, immediate);
+ else if (item)
+ item->setPosition(pos);
+}
+
+void QQuickItemViewFxItem::setVisible(bool visible)
+{
+ if (!visible && transitionableItem && transitionableItem->transitionScheduledOrRunning())
+ return;
+ if (item)
+ QQuickItemPrivate::get(item)->setCulled(!visible);
+}
+
+void QQuickItemViewFxItem::trackGeometry(bool track)
+{
+ if (track) {
+ if (!trackGeom) {
+ if (item) {
+ QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
+ itemPrivate->addItemChangeListener(changeListener, QQuickItemPrivate::Geometry);
+ }
+ trackGeom = true;
+ }
+ } else {
+ if (trackGeom) {
+ if (item) {
+ QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
+ itemPrivate->removeItemChangeListener(changeListener, QQuickItemPrivate::Geometry);
+ }
+ trackGeom = false;
+ }
+ }
+}
+
+QRectF QQuickItemViewFxItem::geometry() const
+{
+ return QRectF(item->position(), item->size());
+}
+
+void QQuickItemViewFxItem::setGeometry(const QRectF &geometry)
+{
+ item->setPosition(geometry.topLeft());
+ item->setSize(geometry.size());
+}
+
+QQuickItemViewTransitioner::TransitionType QQuickItemViewFxItem::scheduledTransitionType() const
+{
+ return transitionableItem ? transitionableItem->nextTransitionType : QQuickItemViewTransitioner::NoTransition;
+}
+
+bool QQuickItemViewFxItem::transitionScheduledOrRunning() const
+{
+ return transitionableItem ? transitionableItem->transitionScheduledOrRunning() : false;
+}
+
+bool QQuickItemViewFxItem::transitionRunning() const
+{
+ return transitionableItem ? transitionableItem->transitionRunning() : false;
+}
+
+bool QQuickItemViewFxItem::isPendingRemoval() const
+{
+ return transitionableItem ? transitionableItem->isPendingRemoval() : false;
+}
+
+void QQuickItemViewFxItem::transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget)
+{
+ if (!transitioner)
+ return;
+ if (!transitionableItem)
+ transitionableItem = new QQuickItemViewTransitionableItem(item);
+ transitioner->transitionNextReposition(transitionableItem, type, asTarget);
+}
+
+bool QQuickItemViewFxItem::prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds)
+{
+ return transitionableItem ? transitionableItem->prepareTransition(transitioner, index, viewBounds) : false;
+}
+
+void QQuickItemViewFxItem::startTransition(QQuickItemViewTransitioner *transitioner)
+{
+ if (transitionableItem)
+ transitionableItem->startTransition(transitioner, index);
+}
+
+QT_END_NAMESPACE
+
diff --git a/src/quick/items/qquickitemviewfxitem_p_p.h b/src/quick/items/qquickitemviewfxitem_p_p.h
new file mode 100644
index 0000000000..48ffe248bc
--- /dev/null
+++ b/src/quick/items/qquickitemviewfxitem_p_p.h
@@ -0,0 +1,108 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKFXVIEWITEM_P_P_H
+#define QQUICKFXVIEWITEM_P_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 <QtQuick/private/qtquickglobal_p.h>
+#include <QtQuick/private/qquickitem_p.h>
+#include <QtQuick/private/qquickitemviewtransition_p.h>
+
+QT_REQUIRE_CONFIG(quick_itemview);
+
+QT_BEGIN_NAMESPACE
+
+class Q_AUTOTEST_EXPORT QQuickItemViewFxItem
+{
+public:
+ QQuickItemViewFxItem(QQuickItem *item, bool ownItem, QQuickItemChangeListener *changeListener);
+ virtual ~QQuickItemViewFxItem();
+
+ qreal itemX() const;
+ qreal itemY() const;
+ inline qreal itemWidth() const { return item ? item->width() : 0; }
+ inline qreal itemHeight() const { return item ? item->height() : 0; }
+
+ void moveTo(const QPointF &pos, bool immediate);
+ void setVisible(bool visible);
+ void trackGeometry(bool track);
+
+ QRectF geometry() const;
+ void setGeometry(const QRectF &geometry);
+
+ QQuickItemViewTransitioner::TransitionType scheduledTransitionType() const;
+ bool transitionScheduledOrRunning() const;
+ bool transitionRunning() const;
+ bool isPendingRemoval() const;
+
+ void transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget);
+ bool prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds);
+ void startTransition(QQuickItemViewTransitioner *transitioner);
+
+ // these are positions and sizes along the current direction of scrolling/flicking
+ virtual qreal position() const = 0;
+ virtual qreal endPosition() const = 0;
+ virtual qreal size() const = 0;
+ virtual qreal sectionSize() const = 0;
+
+ virtual bool contains(qreal x, qreal y) const = 0;
+
+ int index = -1;
+ QPointer<QQuickItem> item;
+ bool ownItem;
+ QQuickItemChangeListener *changeListener;
+ QQuickItemViewTransitionableItem *transitionableItem;
+ bool releaseAfterTransition;
+ bool trackGeom;
+};
+
+QT_END_NAMESPACE
+
+#endif // QQUICKFXVIEWITEM_P_P_H
diff --git a/src/quick/items/qquickitemviewtransition.cpp b/src/quick/items/qquickitemviewtransition.cpp
index c06dcce0d9..0fde0beb75 100644
--- a/src/quick/items/qquickitemviewtransition.cpp
+++ b/src/quick/items/qquickitemviewtransition.cpp
@@ -500,6 +500,8 @@ void QQuickItemViewTransitionableItem::startTransition(QQuickItemViewTransitione
}
if (!transition || transition->m_type != nextTransitionType || transition->m_isTarget != isTransitionTarget) {
+ if (transition)
+ transition->cancel();
delete transition;
transition = new QQuickItemViewTransitionJob;
}
diff --git a/src/quick/items/qquicklistview.cpp b/src/quick/items/qquicklistview.cpp
index 19033e03f1..908801ce1c 100644
--- a/src/quick/items/qquicklistview.cpp
+++ b/src/quick/items/qquicklistview.cpp
@@ -515,8 +515,8 @@ QString QQuickListViewPrivate::sectionAt(int modelIndex)
qreal QQuickListViewPrivate::snapPosAt(qreal pos)
{
- if (FxViewItem *snapItem = snapItemAt(pos))
- return snapItem->position();
+ if (FxListItemSG *snapItem = static_cast<FxListItemSG*>(snapItemAt(pos)))
+ return snapItem->itemPosition();
if (visibleItems.count()) {
qreal firstPos = (*visibleItems.constBegin())->position();
qreal endPos = (*(--visibleItems.constEnd()))->position();
@@ -530,22 +530,35 @@ qreal QQuickListViewPrivate::snapPosAt(qreal pos)
FxViewItem *QQuickListViewPrivate::snapItemAt(qreal pos)
{
+ const qreal velocity = orient == QQuickListView::Vertical ? vData.velocity : hData.velocity;
FxViewItem *snapItem = nullptr;
+ FxViewItem *prevItem = nullptr;
qreal prevItemSize = 0;
for (FxViewItem *item : qAsConst(visibleItems)) {
if (item->index == -1)
continue;
- qreal itemTop = item->position();
- if (highlight && itemTop >= pos && item->endPosition() <= pos + highlight->size())
+
+ const FxListItemSG *listItem = static_cast<FxListItemSG *>(item);
+ qreal itemTop = listItem->position();
+ qreal itemSize = listItem->size();
+ if (highlight && itemTop >= pos && listItem->endPosition() <= pos + highlight->size())
return item;
+ if (listItem->section() && velocity > 0) {
+ if (itemTop + listItem->sectionSize() / 2 >= pos && itemTop - prevItemSize / 2 < pos)
+ snapItem = prevItem;
+ itemTop = listItem->itemPosition();
+ itemSize = listItem->itemSize();
+ }
+
// Middle of item and spacing (i.e. the middle of the distance between this item and the next
- qreal halfwayToNextItem = itemTop + (item->size()+spacing) / 2;
+ qreal halfwayToNextItem = itemTop + (itemSize+spacing) / 2;
qreal halfwayToPrevItem = itemTop - (prevItemSize+spacing) / 2;
if (halfwayToNextItem >= pos && halfwayToPrevItem < pos)
snapItem = item;
- prevItemSize = item->size();
+ prevItemSize = listItem->itemSize();
+ prevItem = item;
}
return snapItem;
}
@@ -1501,7 +1514,7 @@ void QQuickListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
qreal tempPosition = isContentFlowReversed() ? -position()-size() : position();
if (snapMode == QQuickListView::SnapOneItem && moveReason == Mouse) {
// if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = 0;
if (data.velocity > 0 && dist > QML_FLICK_SNAPONETHRESHOLD && dist < averageSize/2)
bias = averageSize/2;
@@ -1512,13 +1525,13 @@ void QQuickListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
tempPosition -= bias;
}
FxViewItem *topItem = snapItemAt(tempPosition+highlightRangeStart);
- if (strictHighlightRange && currentItem && (!topItem || topItem->index != currentIndex)) {
+ if (strictHighlightRange && currentItem && (!topItem || (topItem->index != currentIndex && fixupMode == Immediate))) {
// StrictlyEnforceRange always keeps an item in range
updateHighlight();
topItem = currentItem;
}
FxViewItem *bottomItem = snapItemAt(tempPosition+highlightRangeEnd);
- if (strictHighlightRange && currentItem && (!bottomItem || bottomItem->index != currentIndex)) {
+ if (strictHighlightRange && currentItem && (!bottomItem || (bottomItem->index != currentIndex && fixupMode == Immediate))) {
// StrictlyEnforceRange always keeps an item in range
updateHighlight();
bottomItem = currentItem;
@@ -1530,15 +1543,15 @@ void QQuickListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
pos = isContentFlowReversed() ? - header->position() + highlightRangeStart - size() : header->position() - highlightRangeStart;
} else {
if (isContentFlowReversed())
- pos = qMax(qMin(-topItem->position() + highlightRangeStart - size(), -maxExtent), -minExtent);
+ pos = qMax(qMin(-static_cast<FxListItemSG*>(topItem)->itemPosition() + highlightRangeStart - size(), -maxExtent), -minExtent);
else
- pos = qMax(qMin(topItem->position() - highlightRangeStart, -maxExtent), -minExtent);
+ pos = qMax(qMin(static_cast<FxListItemSG*>(topItem)->itemPosition() - highlightRangeStart, -maxExtent), -minExtent);
}
} else if (bottomItem && isInBounds) {
if (isContentFlowReversed())
- pos = qMax(qMin(-bottomItem->position() + highlightRangeEnd - size(), -maxExtent), -minExtent);
+ pos = qMax(qMin(-static_cast<FxListItemSG*>(bottomItem)->itemPosition() + highlightRangeEnd - size(), -maxExtent), -minExtent);
else
- pos = qMax(qMin(bottomItem->position() - highlightRangeEnd, -maxExtent), -minExtent);
+ pos = qMax(qMin(static_cast<FxListItemSG*>(bottomItem)->itemPosition() - highlightRangeEnd, -maxExtent), -minExtent);
} else {
QQuickItemViewPrivate::fixup(data, minExtent, maxExtent);
return;
@@ -1568,7 +1581,10 @@ void QQuickListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExte
timeline.reset(data.move);
if (viewPos != position()) {
if (fixupMode != Immediate) {
- timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
+ if (fixupMode == ExtentChanged && data.fixingUp)
+ timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::OutQuad), fixupDuration/2);
+ else
+ timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2);
data.fixingUp = true;
} else {
timeline.set(data.move, -viewPos);
@@ -1599,7 +1615,7 @@ bool QQuickListViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExte
if (data.move.value() < minExtent) {
if (snapMode == QQuickListView::SnapOneItem && !hData.flicking && !vData.flicking) {
// if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = dist < averageSize/2 ? averageSize/2 : 0;
if (isContentFlowReversed())
bias = -bias;
@@ -1616,7 +1632,7 @@ bool QQuickListViewPrivate::flick(AxisData &data, qreal minExtent, qreal maxExte
if (data.move.value() > maxExtent) {
if (snapMode == QQuickListView::SnapOneItem && !hData.flicking && !vData.flicking) {
// if we've been dragged < averageSize/2 then bias towards the next item
- qreal dist = data.move.value() - (data.pressPos - data.dragStartOffset);
+ qreal dist = data.move.value() - data.pressPos;
qreal bias = -dist < averageSize/2 ? averageSize/2 : 0;
if (isContentFlowReversed())
bias = -bias;
@@ -1982,7 +1998,7 @@ QQuickListView::~QQuickListView()
The model provides the set of data that is used to create the items
in the view. Models can be created directly in QML using \l ListModel, \l XmlListModel
- or \l VisualItemModel, or provided by C++ model classes. If a C++ model class is
+ or \l ObjectModel, or provided by C++ model classes. If a C++ model class is
used, it must be a subclass of \l QAbstractItemModel or a simple list.
\sa {qml-data-models}{Data Models}
@@ -2521,7 +2537,11 @@ void QQuickListView::setHighlightResizeDuration(int duration)
the view.
\li ListView.SnapOneItem - the view settles no more than one item away from the first
visible item at the time the mouse button is released. This mode is particularly
- useful for moving one page at a time.
+ useful for moving one page at a time. When SnapOneItem is enabled, the ListView will
+ show a stronger affinity to neighboring items when movement occurs. For example, a
+ short drag that snaps back to the current item with SnapToItem might snap to a
+ neighboring item with SnapOneItem.
+
\endlist
\c snapMode does not affect the \l currentIndex. To update the
diff --git a/src/quick/items/qquickloader.cpp b/src/quick/items/qquickloader.cpp
index b5ae41daef..d0e29c204e 100644
--- a/src/quick/items/qquickloader.cpp
+++ b/src/quick/items/qquickloader.cpp
@@ -54,7 +54,7 @@ static const QQuickItemPrivate::ChangeTypes watchedChanges
= QQuickItemPrivate::Geometry | QQuickItemPrivate::ImplicitWidth | QQuickItemPrivate::ImplicitHeight;
QQuickLoaderPrivate::QQuickLoaderPrivate()
- : item(nullptr), object(nullptr), component(nullptr), itemContext(nullptr), incubator(nullptr), updatingSize(false),
+ : item(nullptr), object(nullptr), itemContext(nullptr), incubator(nullptr), updatingSize(false),
active(true), loadingFromSource(false), asynchronous(false)
{
}
@@ -111,11 +111,10 @@ void QQuickLoaderPrivate::clear()
QObject::disconnect(component, SIGNAL(progressChanged(qreal)),
q, SIGNAL(progressChanged()));
component->deleteLater();
- component = nullptr;
+ component.setObject(nullptr, q);
} else if (component) {
- component = nullptr;
+ component.setObject(nullptr, q);
}
- componentStrongReference.clear();
source = QUrl();
if (item) {
@@ -441,7 +440,7 @@ void QQuickLoader::loadFromSource()
if (isComponentComplete()) {
QQmlComponent::CompilationMode mode = d->asynchronous ? QQmlComponent::Asynchronous : QQmlComponent::PreferSynchronous;
if (!d->component)
- d->component = new QQmlComponent(qmlEngine(this), d->source, mode, this);
+ d->component.setObject(new QQmlComponent(qmlEngine(this), d->source, mode, this), this);
d->load();
}
}
@@ -484,11 +483,7 @@ void QQuickLoader::setSourceComponent(QQmlComponent *comp)
d->clear();
- d->component = comp;
- if (comp) {
- if (QQmlData *ddata = QQmlData::get(comp))
- d->componentStrongReference = ddata->jsWrapper;
- }
+ d->component.setObject(comp, this);
d->loadingFromSource = false;
if (d->active)
@@ -832,7 +827,7 @@ void QQuickLoader::componentComplete()
if (d->loadingFromSource) {
QQmlComponent::CompilationMode mode = d->asynchronous ? QQmlComponent::Asynchronous : QQmlComponent::PreferSynchronous;
if (!d->component)
- d->component = new QQmlComponent(qmlEngine(this), d->source, mode, this);
+ d->component.setObject(new QQmlComponent(qmlEngine(this), d->source, mode, this), this);
}
d->load();
}
@@ -1007,7 +1002,7 @@ QUrl QQuickLoaderPrivate::resolveSourceUrl(QQmlV4Function *args)
QV4::ReturnedValue QQuickLoaderPrivate::extractInitialPropertyValues(QQmlV4Function *args, QObject *loader, bool *error)
{
QV4::Scope scope(args->v4engine());
- QV4::ScopedValue valuemap(scope, QV4::Primitive::undefinedValue());
+ QV4::ScopedValue valuemap(scope, QV4::Encode::undefined());
if (args->length() >= 2) {
QV4::ScopedValue v(scope, (*args)[1]);
if (!v->isObject() || v->as<QV4::ArrayObject>()) {
diff --git a/src/quick/items/qquickloader_p_p.h b/src/quick/items/qquickloader_p_p.h
index 7492527401..349b5c6c06 100644
--- a/src/quick/items/qquickloader_p_p.h
+++ b/src/quick/items/qquickloader_p_p.h
@@ -103,8 +103,7 @@ public:
QUrl source;
QQuickItem *item;
QObject *object;
- QQmlComponent *component;
- QV4::PersistentValue componentStrongReference; // To ensure GC doesn't delete components created by Qt.createComponent
+ QQmlStrongJSQObjectReference<QQmlComponent> component;
QQmlContext *itemContext;
QQuickLoaderIncubator *incubator;
QV4::PersistentValue initialPropertyValues;
diff --git a/src/quick/items/qquickmultipointtoucharea.cpp b/src/quick/items/qquickmultipointtoucharea.cpp
index b1438d7541..3eca535a67 100644
--- a/src/quick/items/qquickmultipointtoucharea.cpp
+++ b/src/quick/items/qquickmultipointtoucharea.cpp
@@ -610,6 +610,9 @@ void QQuickMultiPointTouchArea::updateTouchData(QEvent *event)
else { // QEvent::MouseButtonPress
addTouchPoint(me);
started = true;
+ _mouseQpaTouchPoint.setStartPos(me->localPos());
+ _mouseQpaTouchPoint.setStartScenePos(me->windowPos());
+ _mouseQpaTouchPoint.setStartScreenPos(me->screenPos());
_mouseQpaTouchPoint.setState(Qt::TouchPointPressed);
}
touchPoints << _mouseQpaTouchPoint;
diff --git a/src/quick/items/qquickmultipointtoucharea_p.h b/src/quick/items/qquickmultipointtoucharea_p.h
index f1550b4ac6..634ea1c2e2 100644
--- a/src/quick/items/qquickmultipointtoucharea_p.h
+++ b/src/quick/items/qquickmultipointtoucharea_p.h
@@ -185,8 +185,8 @@ private:
class QQuickGrabGestureEvent : public QObject
{
Q_OBJECT
- Q_PROPERTY(QQmlListProperty<QObject> touchPoints READ touchPoints)
- Q_PROPERTY(qreal dragThreshold READ dragThreshold)
+ Q_PROPERTY(QQmlListProperty<QObject> touchPoints READ touchPoints CONSTANT)
+ Q_PROPERTY(qreal dragThreshold READ dragThreshold CONSTANT)
public:
QQuickGrabGestureEvent() : _dragThreshold(QGuiApplication::styleHints()->startDragDistance()) {}
diff --git a/src/quick/items/qquickpainteditem.h b/src/quick/items/qquickpainteditem.h
index b057f4295d..ddc1fd99d9 100644
--- a/src/quick/items/qquickpainteditem.h
+++ b/src/quick/items/qquickpainteditem.h
@@ -71,6 +71,7 @@ public:
FastFBOResizing = 0x1
};
Q_DECLARE_FLAGS(PerformanceHints, PerformanceHint)
+ Q_FLAG(PerformanceHints)
void update(const QRect &rect = QRect());
diff --git a/src/quick/items/qquickpositioners.cpp b/src/quick/items/qquickpositioners.cpp
index 55bafd9f83..512f59d799 100644
--- a/src/quick/items/qquickpositioners.cpp
+++ b/src/quick/items/qquickpositioners.cpp
@@ -900,11 +900,7 @@ void QQuickPositionerAttached::setIsLastItem(bool isLastItem)
cases, these lists will be empty. See the \l ViewTransition documentation for more details
and examples on using these transitions.
- \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
- positioner at the time of its creation. From \l {Qt Quick}{Qt Quick 2} onwards, positioners apply the
- \l populate transition to these items instead.
-
- \sa add, ViewTransition, {Qt Quick Examples - Positioners}
+ \sa add, populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
\qmlproperty real QtQuick::Column::spacing
@@ -1089,11 +1085,7 @@ void QQuickColumn::reportConflictingAnchors()
cases, these lists will be empty. See the \l ViewTransition documentation for more details
and examples on using these transitions.
- \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
- positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
- \l populate transition to these items instead.
-
- \sa add, ViewTransition, {Qt Quick Examples - Positioners}
+ \sa add, populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
\qmlproperty real QtQuick::Row::spacing
@@ -1378,11 +1370,7 @@ void QQuickRow::reportConflictingAnchors()
cases, these lists will be empty. See the \l ViewTransition documentation for more details
and examples on using these transitions.
- \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
- positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
- \l populate transition to these items instead.
-
- \sa add, ViewTransition, {Qt Quick Examples - Positioners}
+ \sa add, populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
\qmlproperty qreal QtQuick::Grid::spacing
@@ -1974,11 +1962,7 @@ void QQuickGrid::reportConflictingAnchors()
cases, these lists will be empty. See the \l ViewTransition documentation for more details
and examples on using these transitions.
- \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
- positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
- \l populate transition to these items instead.
-
- \sa add, ViewTransition, {Qt Quick Examples - Positioners}
+ \sa add, populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
\qmlproperty real QtQuick::Flow::spacing
diff --git a/src/quick/items/qquickrectangle.cpp b/src/quick/items/qquickrectangle.cpp
index bf030b9d80..5e217dcd0c 100644
--- a/src/quick/items/qquickrectangle.cpp
+++ b/src/quick/items/qquickrectangle.cpp
@@ -40,9 +40,13 @@
#include "qquickrectangle_p.h"
#include "qquickrectangle_p_p.h"
+#include <QtQml/qqmlinfo.h>
+
#include <QtQuick/private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
+#include <private/qqmlmetatype_p.h>
+
#include <QtGui/qpixmapcache.h>
#include <QtCore/qmath.h>
#include <QtCore/qmetaobject.h>
@@ -219,10 +223,11 @@ void QQuickGradientStop::updateGradient()
of solid color fills or images. Consider using gradients for static items
in a user interface.
- In Qt 5.0, only vertical, linear gradients can be applied to items. If you
- need to apply different orientations of gradients, a combination of rotation
- and clipping will need to be applied to the relevant items. This can
- introduce additional performance requirements for your application.
+ Since Qt 5.12, vertical and horizontal linear gradients can be applied to items.
+ If you need to apply angled gradients, a combination of rotation and clipping
+ can be applied to the relevant items. Alternatively, consider using
+ QtQuick.Shapes::LinearGradient or QtGraphicalEffects::LinearGradient. These
+ approaches can all introduce additional performance requirements for your application.
The use of animations involving gradient stops may not give the desired
result. An alternative way to animate gradients is to use pre-generated
@@ -255,6 +260,28 @@ QQmlListProperty<QQuickGradientStop> QQuickGradient::stops()
return QQmlListProperty<QQuickGradientStop>(this, m_stops);
}
+/*!
+ \qmlproperty enumeration QtQuick::Gradient::orientation
+ \since 5.12
+
+ Set this property to define the direction of the gradient.
+ \list
+ \li Gradient.Vertical - a vertical gradient
+ \li Gradient.Horizontal - a horizontal gradient
+ \endlist
+
+ The default is Gradient.Vertical.
+*/
+void QQuickGradient::setOrientation(Orientation orientation)
+{
+ if (m_orientation == orientation)
+ return;
+
+ m_orientation = orientation;
+ emit orientationChanged();
+ emit updated();
+}
+
QGradientStops QQuickGradient::gradientStops() const
{
QGradientStops stops;
@@ -370,11 +397,11 @@ QQuickPen *QQuickRectangle::border()
}
/*!
- \qmlproperty Gradient QtQuick::Rectangle::gradient
+ \qmlproperty any QtQuick::Rectangle::gradient
The gradient to use to fill the rectangle.
- This property allows for the construction of simple vertical gradients.
+ This property allows for the construction of simple vertical or horizontal gradients.
Other gradients may be formed by adding rotation to the rectangle.
\div {class="float-left"}
@@ -384,37 +411,66 @@ QQuickPen *QQuickRectangle::border()
\snippet qml/rectangle/rectangle-gradient.qml rectangles
\clearfloat
+ The property also accepts gradient presets from QGradient::Preset. Note however
+ that due to Rectangle only supporting simple vertical or horizontal gradients,
+ any preset with an unsupported angle will revert to the closest representation.
+
+ \snippet qml/rectangle/rectangle-gradient.qml presets
+ \clearfloat
+
If both a gradient and a color are specified, the gradient will be used.
\sa Gradient, color
*/
-QQuickGradient *QQuickRectangle::gradient() const
+QJSValue QQuickRectangle::gradient() const
{
Q_D(const QQuickRectangle);
return d->gradient;
}
-void QQuickRectangle::setGradient(QQuickGradient *gradient)
+void QQuickRectangle::setGradient(const QJSValue &gradient)
{
Q_D(QQuickRectangle);
- if (d->gradient == gradient)
+ if (d->gradient.equals(gradient))
return;
- static int updatedSignalIdx = -1;
- if (updatedSignalIdx < 0)
- updatedSignalIdx = QMetaMethod::fromSignal(&QQuickGradient::updated).methodIndex();
+
+ static int updatedSignalIdx = QMetaMethod::fromSignal(&QQuickGradient::updated).methodIndex();
if (d->doUpdateSlotIdx < 0)
d->doUpdateSlotIdx = QQuickRectangle::staticMetaObject.indexOfSlot("doUpdate()");
- if (d->gradient)
- QMetaObject::disconnect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
- d->gradient = gradient;
- if (d->gradient)
- QMetaObject::connect(d->gradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
+
+ if (auto oldGradient = qobject_cast<QQuickGradient*>(d->gradient.toQObject()))
+ QMetaObject::disconnect(oldGradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
+
+ if (gradient.isQObject()) {
+ if (auto newGradient = qobject_cast<QQuickGradient*>(gradient.toQObject())) {
+ d->gradient = gradient;
+ QMetaObject::connect(newGradient, updatedSignalIdx, this, d->doUpdateSlotIdx);
+ } else {
+ qmlWarning(this) << "Can't assign "
+ << QQmlMetaType::prettyTypeName(gradient.toQObject()) << " to gradient property";
+ d->gradient = QJSValue();
+ }
+ } else if (gradient.isNumber() || gradient.isString()) {
+ QGradient preset(gradient.toVariant().value<QGradient::Preset>());
+ if (preset.type() != QGradient::NoGradient) {
+ d->gradient = gradient;
+ } else {
+ qmlWarning(this) << "No such gradient preset '" << gradient.toString() << "'";
+ d->gradient = QJSValue();
+ }
+ } else if (gradient.isNull() || gradient.isUndefined()) {
+ d->gradient = gradient;
+ } else {
+ qmlWarning(this) << "Unknown gradient type. Expected int, string, or Gradient";
+ d->gradient = QJSValue();
+ }
+
update();
}
void QQuickRectangle::resetGradient()
{
- setGradient(nullptr);
+ setGradient(QJSValue());
}
/*!
@@ -510,10 +566,35 @@ QSGNode *QQuickRectangle::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData
rectangle->setAntialiasing(antialiasing());
QGradientStops stops;
- if (d->gradient) {
- stops = d->gradient->gradientStops();
+ bool vertical = true;
+ if (d->gradient.isQObject()) {
+ auto gradient = qobject_cast<QQuickGradient*>(d->gradient.toQObject());
+ Q_ASSERT(gradient);
+ stops = gradient->gradientStops();
+ vertical = gradient->orientation() == QQuickGradient::Vertical;
+ } else if (d->gradient.isNumber() || d->gradient.isString()) {
+ QGradient preset(d->gradient.toVariant().value<QGradient::Preset>());
+ if (preset.type() == QGradient::LinearGradient) {
+ auto linearGradient = static_cast<QLinearGradient&>(preset);
+ const QPointF start = linearGradient.start();
+ const QPointF end = linearGradient.finalStop();
+ vertical = qAbs(start.y() - end.y()) >= qAbs(start.x() - end.x());
+ stops = linearGradient.stops();
+ if ((vertical && start.y() > end.y()) || (!vertical && start.x() > end.x())) {
+ // QSGInternalRectangleNode doesn't support stops in the wrong order,
+ // so we need to manually reverse them here.
+ QGradientStops reverseStops;
+ for (auto it = stops.rbegin(); it != stops.rend(); ++it) {
+ auto stop = *it;
+ stop.first = 1 - stop.first;
+ reverseStops.append(stop);
+ }
+ stops = reverseStops;
+ }
+ }
}
rectangle->setGradientStops(stops);
+ rectangle->setGradientVertical(vertical);
rectangle->update();
diff --git a/src/quick/items/qquickrectangle_p.h b/src/quick/items/qquickrectangle_p.h
index c07ad835fb..d56a03d22d 100644
--- a/src/quick/items/qquickrectangle_p.h
+++ b/src/quick/items/qquickrectangle_p.h
@@ -119,24 +119,35 @@ class Q_QUICK_PRIVATE_EXPORT QQuickGradient : public QObject
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QQuickGradientStop> stops READ stops)
+ Q_PROPERTY(Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged REVISION 12)
Q_CLASSINFO("DefaultProperty", "stops")
+ Q_ENUMS(QGradient::Preset)
public:
QQuickGradient(QObject *parent=nullptr);
~QQuickGradient() override;
+ enum Orientation { Vertical = Qt::Vertical,
+ Horizontal = Qt::Horizontal };
+ Q_ENUM(Orientation)
+
QQmlListProperty<QQuickGradientStop> stops();
+ Orientation orientation() const { return m_orientation; }
+ void setOrientation(Orientation orientation);
+
QGradientStops gradientStops() const;
Q_SIGNALS:
void updated();
+ void orientationChanged();
private:
void doUpdate();
private:
QList<QQuickGradientStop *> m_stops;
+ Orientation m_orientation = Vertical;
friend class QQuickRectangle;
friend class QQuickGradientStop;
};
@@ -147,7 +158,7 @@ class Q_QUICK_PRIVATE_EXPORT QQuickRectangle : public QQuickItem
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
- Q_PROPERTY(QQuickGradient *gradient READ gradient WRITE setGradient RESET resetGradient)
+ Q_PROPERTY(QJSValue gradient READ gradient WRITE setGradient RESET resetGradient)
Q_PROPERTY(QQuickPen * border READ border CONSTANT)
Q_PROPERTY(qreal radius READ radius WRITE setRadius NOTIFY radiusChanged)
public:
@@ -158,8 +169,8 @@ public:
QQuickPen *border();
- QQuickGradient *gradient() const;
- void setGradient(QQuickGradient *gradient);
+ QJSValue gradient() const;
+ void setGradient(const QJSValue &gradient);
void resetGradient();
qreal radius() const;
diff --git a/src/quick/items/qquickrectangle_p_p.h b/src/quick/items/qquickrectangle_p_p.h
index 3c1aaf7661..c7c5293f9b 100644
--- a/src/quick/items/qquickrectangle_p_p.h
+++ b/src/quick/items/qquickrectangle_p_p.h
@@ -73,7 +73,7 @@ public:
}
QColor color;
- QQuickGradient *gradient;
+ QJSValue gradient;
QQuickPen *pen;
qreal radius;
static int doUpdateSlotIdx;
diff --git a/src/quick/items/qquickrendercontrol.cpp b/src/quick/items/qquickrendercontrol.cpp
index fb1c6366f2..025acefec2 100644
--- a/src/quick/items/qquickrendercontrol.cpp
+++ b/src/quick/items/qquickrendercontrol.cpp
@@ -187,7 +187,6 @@ void QQuickRenderControlPrivate::windowDestroyed()
{
if (window) {
rc->invalidate();
- QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
delete QQuickWindowPrivate::get(window)->animationController;
QQuickWindowPrivate::get(window)->animationController = nullptr;
@@ -313,9 +312,6 @@ bool QQuickRenderControl::sync()
void QQuickRenderControl::invalidate()
{
Q_D(QQuickRenderControl);
- if (!d->initialized)
- return;
-
if (!d->window)
return;
@@ -323,6 +319,9 @@ void QQuickRenderControl::invalidate()
cd->fireAboutToStop();
cd->cleanupNodesOnShutdown();
+ if (!d->initialized)
+ return;
+
// We must invalidate since the context can potentially be destroyed by the
// application right after returning from this function. Invalidating is
// also essential to allow a subsequent initialize() to succeed.
@@ -392,6 +391,7 @@ QImage QQuickRenderControl::grab()
grabContent.setDevicePixelRatio(d->window->effectiveDevicePixelRatio());
}
#endif
+#if QT_CONFIG(thread)
} else if (d->window->rendererInterface()->graphicsApi() == QSGRendererInterface::Software) {
QQuickWindowPrivate *cd = QQuickWindowPrivate::get(d->window);
cd->polishItems();
@@ -409,6 +409,7 @@ QImage QQuickRenderControl::grab()
render();
softwareRenderer->setCurrentPaintDevice(prevDev);
}
+#endif
} else {
qWarning("QQuickRenderControl: grabs are not supported with the current Qt Quick backend");
}
diff --git a/src/quick/items/qquickscalegrid.cpp b/src/quick/items/qquickscalegrid.cpp
index d7a0f1b681..23f179be1d 100644
--- a/src/quick/items/qquickscalegrid.cpp
+++ b/src/quick/items/qquickscalegrid.cpp
@@ -66,6 +66,7 @@ void QQuickScaleGrid::setLeft(int pos)
{
if (_left != pos) {
_left = pos;
+ emit leftBorderChanged();
emit borderChanged();
}
}
@@ -74,6 +75,7 @@ void QQuickScaleGrid::setTop(int pos)
{
if (_top != pos) {
_top = pos;
+ emit topBorderChanged();
emit borderChanged();
}
}
@@ -82,6 +84,7 @@ void QQuickScaleGrid::setRight(int pos)
{
if (_right != pos) {
_right = pos;
+ emit rightBorderChanged();
emit borderChanged();
}
}
@@ -90,6 +93,7 @@ void QQuickScaleGrid::setBottom(int pos)
{
if (_bottom != pos) {
_bottom = pos;
+ emit bottomBorderChanged();
emit borderChanged();
}
}
diff --git a/src/quick/items/qquickscalegrid_p_p.h b/src/quick/items/qquickscalegrid_p_p.h
index 5752f61e3f..f5187a8eea 100644
--- a/src/quick/items/qquickscalegrid_p_p.h
+++ b/src/quick/items/qquickscalegrid_p_p.h
@@ -65,10 +65,10 @@ class Q_AUTOTEST_EXPORT QQuickScaleGrid : public QObject
{
Q_OBJECT
- Q_PROPERTY(int left READ left WRITE setLeft NOTIFY borderChanged)
- Q_PROPERTY(int top READ top WRITE setTop NOTIFY borderChanged)
- Q_PROPERTY(int right READ right WRITE setRight NOTIFY borderChanged)
- Q_PROPERTY(int bottom READ bottom WRITE setBottom NOTIFY borderChanged)
+ Q_PROPERTY(int left READ left WRITE setLeft NOTIFY leftBorderChanged)
+ Q_PROPERTY(int top READ top WRITE setTop NOTIFY topBorderChanged)
+ Q_PROPERTY(int right READ right WRITE setRight NOTIFY rightBorderChanged)
+ Q_PROPERTY(int bottom READ bottom WRITE setBottom NOTIFY bottomBorderChanged)
public:
QQuickScaleGrid(QObject *parent=nullptr);
@@ -90,6 +90,10 @@ public:
Q_SIGNALS:
void borderChanged();
+ void leftBorderChanged();
+ void topBorderChanged();
+ void rightBorderChanged();
+ void bottomBorderChanged();
private:
int _left;
diff --git a/src/quick/items/qquickscreen.cpp b/src/quick/items/qquickscreen.cpp
index aea7e44a65..b057fd9d8f 100644
--- a/src/quick/items/qquickscreen.cpp
+++ b/src/quick/items/qquickscreen.cpp
@@ -396,24 +396,24 @@ void QQuickScreenInfo::setWrappedScreen(QScreen *screen)
if (!oldScreen || screen->devicePixelRatio() != oldScreen->devicePixelRatio())
emit devicePixelRatioChanged();
- connect(screen, SIGNAL(geometryChanged(QRect)),
- this, SIGNAL(widthChanged()));
- connect(screen, SIGNAL(geometryChanged(QRect)),
- this, SIGNAL(heightChanged()));
- connect(screen, SIGNAL(geometryChanged(QRect)),
- this, SIGNAL(virtualXChanged()));
- connect(screen, SIGNAL(geometryChanged(QRect)),
- this, SIGNAL(virtualYChanged()));
- connect(screen, SIGNAL(orientationChanged(Qt::ScreenOrientation)),
- this, SIGNAL(orientationChanged()));
- connect(screen, SIGNAL(primaryOrientationChanged(Qt::ScreenOrientation)),
- this, SIGNAL(primaryOrientationChanged()));
- connect(screen, SIGNAL(virtualGeometryChanged(QRect)),
- this, SIGNAL(desktopGeometryChanged()));
- connect(screen, SIGNAL(logicalDotsPerInchChanged(qreal)),
- this, SIGNAL(logicalPixelDensityChanged()));
- connect(screen, SIGNAL(physicalDotsPerInchChanged(qreal)),
- this, SIGNAL(pixelDensityChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(geometryChanged(QRect)),
+ this, QQuickScreenInfo, SIGNAL(widthChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(geometryChanged(QRect)),
+ this, QQuickScreenInfo, SIGNAL(heightChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(geometryChanged(QRect)),
+ this, QQuickScreenInfo, SIGNAL(virtualXChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(geometryChanged(QRect)),
+ this, QQuickScreenInfo, SIGNAL(virtualYChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(orientationChanged(Qt::ScreenOrientation)),
+ this, QQuickScreenInfo, SIGNAL(orientationChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(primaryOrientationChanged(Qt::ScreenOrientation)),
+ this, QQuickScreenInfo, SIGNAL(primaryOrientationChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(virtualGeometryChanged(QRect)),
+ this, QQuickScreenInfo, SIGNAL(desktopGeometryChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(logicalDotsPerInchChanged(qreal)),
+ this, QQuickScreenInfo, SIGNAL(logicalPixelDensityChanged()));
+ qmlobject_connect(screen, QScreen, SIGNAL(physicalDotsPerInchChanged(qreal)),
+ this, QQuickScreenInfo, SIGNAL(pixelDensityChanged()));
}
QScreen *QQuickScreenInfo::wrappedScreen() const
@@ -473,11 +473,11 @@ int QQuickScreenAttached::angleBetween(int a, int b)
void QQuickScreenAttached::windowChanged(QQuickWindow* c)
{
if (m_window)
- disconnect(m_window, SIGNAL(screenChanged(QScreen*)), this, SLOT(screenChanged(QScreen*)));
+ qmlobject_disconnect(m_window, QQuickWindow, SIGNAL(screenChanged(QScreen*)), this, QQuickScreenAttached, SLOT(screenChanged(QScreen*)));
m_window = c;
screenChanged(c ? c->screen() : nullptr);
if (c)
- connect(c, SIGNAL(screenChanged(QScreen*)), this, SLOT(screenChanged(QScreen*)));
+ qmlobject_connect(c, QQuickWindow, SIGNAL(screenChanged(QScreen*)), this, QQuickScreenAttached, SLOT(screenChanged(QScreen*)));
}
void QQuickScreenAttached::screenChanged(QScreen *screen)
diff --git a/src/quick/items/qquickshadereffectmesh.cpp b/src/quick/items/qquickshadereffectmesh.cpp
index 77b7cbc78d..804f548d21 100644
--- a/src/quick/items/qquickshadereffectmesh.cpp
+++ b/src/quick/items/qquickshadereffectmesh.cpp
@@ -64,6 +64,11 @@ QQuickShaderEffectMesh::QQuickShaderEffectMesh(QObject *parent)
{
}
+QQuickShaderEffectMesh::QQuickShaderEffectMesh(QObjectPrivate &dd, QObject *parent)
+ : QObject(dd, parent)
+{
+}
+
/*!
\qmltype GridMesh
\instantiates QQuickGridMesh
diff --git a/src/quick/items/qquickshadereffectmesh_p.h b/src/quick/items/qquickshadereffectmesh_p.h
index 5d6641429a..62a9798e40 100644
--- a/src/quick/items/qquickshadereffectmesh_p.h
+++ b/src/quick/items/qquickshadereffectmesh_p.h
@@ -72,7 +72,7 @@ const char *qtTexCoordAttributeName();
class QSGGeometry;
class QRectF;
-class QQuickShaderEffectMesh : public QObject
+class Q_QUICK_PRIVATE_EXPORT QQuickShaderEffectMesh : public QObject
{
Q_OBJECT
public:
@@ -87,9 +87,12 @@ public:
Q_SIGNALS:
// Emitted when the geometry needs to be updated.
void geometryChanged();
+
+protected:
+ QQuickShaderEffectMesh(QObjectPrivate &dd, QObject *parent = nullptr);
};
-class QQuickGridMesh : public QQuickShaderEffectMesh
+class Q_QUICK_PRIVATE_EXPORT QQuickGridMesh : public QQuickShaderEffectMesh
{
Q_OBJECT
Q_PROPERTY(QSize resolution READ resolution WRITE setResolution NOTIFY resolutionChanged)
diff --git a/src/quick/items/qquickspriteengine_p.h b/src/quick/items/qquickspriteengine_p.h
index da917683b6..d3944b4620 100644
--- a/src/quick/items/qquickspriteengine_p.h
+++ b/src/quick/items/qquickspriteengine_p.h
@@ -109,7 +109,7 @@ public:
virtual int variedDuration() const
{
- return qMax(qreal(0.0) , m_duration
+ return qMax(0.0 , m_duration
+ (m_durationVariation * QRandomGenerator::global()->bounded(2.0))
- m_durationVariation);
}
diff --git a/src/quick/items/qquicktableview.cpp b/src/quick/items/qquicktableview.cpp
new file mode 100644
index 0000000000..44c16e2d7e
--- /dev/null
+++ b/src/quick/items/qquicktableview.cpp
@@ -0,0 +1,2034 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 "qquicktableview_p.h"
+#include "qquicktableview_p_p.h"
+
+#include <QtCore/qtimer.h>
+#include <QtCore/qdir.h>
+#include <QtQml/private/qqmldelegatemodel_p.h>
+#include <QtQml/private/qqmldelegatemodel_p_p.h>
+#include <QtQml/private/qqmlincubator_p.h>
+#include <QtQml/private/qqmlchangeset_p.h>
+#include <QtQml/qqmlinfo.h>
+
+#include <QtQuick/private/qquickflickable_p_p.h>
+#include <QtQuick/private/qquickitemviewfxitem_p_p.h>
+
+/*!
+ \qmltype TableView
+ \instantiates QQuickTableView
+ \inqmlmodule QtQuick
+ \ingroup qtquick-views
+ \inherits Flickable
+ \brief Provides a table view of items provided by the model.
+
+ A TableView has a \l model that defines the data to be displayed, and a
+ \l delegate that defines how the data should be displayed.
+
+ TableView inherits \l Flickable. This means that while the model can have
+ any number of rows and columns, only a subsection of the table is usually
+ visible inside the viewport. As soon as you flick, new rows and columns
+ enter the viewport, while old ones exit and are removed from the viewport.
+ The rows and columns that move out are reused for building the rows and columns
+ that move into the viewport. As such, the TableView support models of any
+ size without affecting performance.
+
+ A TableView displays data from models created from built-in QML types
+ such as ListModel and XmlListModel, which populates the first column only
+ in a TableView. To create models with multiple columns, create a model in
+ C++ that inherits QAbstractItemModel, and expose it to QML.
+
+ \section1 Example Usage
+
+ The following example shows how to create a model from C++ with multiple
+ columns:
+
+ \snippet qml/tableview/tablemodel.cpp 0
+
+ And then how to use it from QML:
+
+ \snippet qml/tableview/tablemodel.qml 0
+
+ \section1 Reusing items
+
+ TableView recycles delegate items by default, instead of instantiating from
+ the \l delegate whenever new rows and columns are flicked into view. This
+ can give a huge performance boost, depending on the complexity of the
+ delegate.
+
+ When an item is flicked out, it moves to the \e{reuse pool}, which is an
+ internal cache of unused items. When this happens, the \l TableView::pooled
+ signal is emitted to inform the item about it. Likewise, when the item is
+ moved back from the pool, the \l TableView::reused signal is emitted.
+
+ Any item properties that come from the model are updated when the
+ item is reused. This includes \c index, \c row, and \c column, but also
+ any model roles.
+
+ \note Avoid storing any state inside a delegate. If you do, reset it
+ manually on receiving the \l TableView::reused signal.
+
+ If an item has timers or animations, consider pausing them on receiving
+ the \l TableView::pooled signal. That way you avoid using the CPU resources
+ for items that are not visible. Likewise, if an item has resources that
+ cannot be reused, they could be freed up.
+
+ If you don't want to reuse items or if the \l delegate cannot support it,
+ you can set the \l reuseItems property to \c false.
+
+ \note While an item is in the pool, it might still be alive and respond
+ to connected signals and bindings.
+
+ The following example shows a delegate that animates a spinning rectangle. When
+ it is pooled, the animation is temporarily paused:
+
+ \snippet qml/tableview/reusabledelegate.qml 0
+
+ \section1 Row heights and column widths
+
+ When a new column is flicked into view, TableView will determine its width
+ by calling the \l columnWidthProvider function. TableView itself will never
+ store row height or column width, as it's designed to support large models
+ containing any number of rows and columns. Instead, it will ask the
+ application whenever it needs to know.
+
+ TableView uses the largest \c implicitWidth among the items as the column
+ width, unless the \l columnWidthProvider property is explicitly set. Once
+ the column width is found, all other items in the same column are resized
+ to this width, even if new items that are flicked in later have larger
+ \c implicitWidth. Setting an explicit \l width on an item is ignored and
+ overwritten.
+
+ \note The calculated width of a column is discarded when it is flicked out
+ of the viewport, and is recalculated if the column is flicked back in. The
+ calculation is always based on the items that are visible when the column
+ is flicked in. This means that it can end up different each time, depending
+ on which row you're at when the column enters. You should therefore have the
+ same \c implicitWidth for all items in a column, or set
+ \l columnWidthProvider. The same logic applies for the row height
+ calculation.
+
+ If you change the values that a \l rowHeightProvider or a
+ \l columnWidthProvider return for rows and columns inside the viewport, you
+ must call \l forceLayout. This informs TableView that it needs to use the
+ provider functions again to recalculate and update the layout.
+
+ \note The size of a row or column should be a whole number to avoid
+ sub-pixel alignment of items.
+
+ The following example shows how to set a simple \c columnWidthProvider
+ together with a timer that modifies the values the function returns. When
+ the array is modified, \l forceLayout is called to let the changes
+ take effect:
+
+ \snippet qml/tableview/tableviewwithprovider.qml 0
+
+ \section1 Overlays and underlays
+
+ Tableview inherits \l Flickable. And when new items are instantiated from the
+ delegate, it will parent them to the \l{Flickable::}{contentItem}
+ with a \c z value equal to \c 1. You can add your own items inside the
+ Tableview, as child items of the Flickable. By controlling their \c z
+ value, you can make them be on top of or underneath the table items.
+
+ Here is an example that shows how to add some text on top of the table, that
+ moves together with the table as you flick:
+
+ \snippet qml/tableview/tableviewwithheader.qml 0
+*/
+
+/*!
+ \qmlproperty int QtQuick::TableView::rows
+
+ This property holds the number of rows in the table. This is
+ equal to the number of rows in the model.
+
+ This property is read only.
+*/
+
+/*!
+ \qmlproperty int QtQuick::TableView::columns
+
+ This property holds the number of columns in the table. This is
+ equal to the number of columns in the model. If the model is
+ a list, columns will be 1.
+
+ This property is read only.
+*/
+
+/*!
+ \qmlproperty real QtQuick::TableView::rowSpacing
+
+ This property holds the spacing between the rows.
+
+ The default value is 0.
+*/
+
+/*!
+ \qmlproperty real QtQuick::TableView::columnSpacing
+
+ This property holds the spacing between the columns.
+
+ The default value is 0.
+*/
+
+/*!
+ \qmlproperty var QtQuick::TableView::rowHeightProvider
+
+ This property can hold a function that returns the row height for each row
+ in the model. When assigned, it will be called whenever TableView needs to
+ know the height of a specific row. The function takes one argument, \c row,
+ for which the TableView needs to know the height.
+
+ \note The height of a row must always be greater than \c 0.
+
+ \sa columnWidthProvider, {Row heights and column widths}
+*/
+
+/*!
+ \qmlproperty var QtQuick::TableView::columnWidthProvider
+
+ This property can hold a function that returns the column width for each
+ column in the model. When assigned, it is called whenever TableView needs
+ to know the width of a specific column. The function takes one argument,
+ \c column, for which the TableView needs to know the width.
+
+ \note The width of a column must always be greater than \c 0.
+
+ \sa rowHeightProvider, {Row heights and column widths}
+*/
+
+/*!
+ \qmlproperty model QtQuick::TableView::model
+ This property holds the model that provides data for the table.
+
+ The model provides the set of data that is used to create the items
+ in the view. Models can be created directly in QML using \l ListModel,
+ \l XmlListModel or \l ObjectModel, or provided by a custom C++ model
+ class. If it is a C++ model, it must be a subclass of \l QAbstractItemModel
+ or a simple list.
+
+ \sa {qml-data-models}{Data Models}
+*/
+
+/*!
+ \qmlproperty Component QtQuick::TableView::delegate
+
+ The delegate provides a template defining each cell item instantiated by the
+ view. The model index is exposed as an accessible \c index property. The same
+ applies to \c row and \c column. Properties of the model are also available
+ depending upon the type of \l {qml-data-models}{Data Model}.
+
+ A delegate should specify its size using \l implicitWidth and \l implicitHeight.
+ The TableView lays out the items based on that information. Explicit \l width or
+ \l height settings are ignored and overwritten.
+
+ \note Delegates are instantiated as needed and may be destroyed at any time.
+ They are also reused if the \l reuseItems property is set to \c true. You
+ should therefore avoid storing state information in the delegates.
+
+ \sa {Row heights and column widths}, {Reusing items}
+*/
+
+/*!
+ \qmlproperty bool QtQuick::TableView::reuseItems
+
+ This property holds whether or not items instantiated from the \l delegate
+ should be reused. If set to \c false, any currently pooled items
+ are destroyed.
+
+ \sa {Reusing items}, TableView::pooled, TableView::reused
+*/
+
+/*!
+ \qmlproperty real QtQuick::TableView::contentWidth
+
+ This property holds the width of the \l contentView, which is also
+ the width of the table (including margins). As a TableView cannot
+ always know the exact width of the table without loading all columns
+ in the model, the \c contentWidth is usually an estimated width based on
+ the columns it has seen so far. This estimate is recalculated whenever
+ new columns are flicked into view, which means that the content width
+ can change dynamically.
+
+ If you know up front what the width of the table will be, assign a value
+ to \c contentWidth explicitly, to avoid unnecessary calculations and
+ updates to the TableView.
+
+ \sa contentHeight
+*/
+
+/*!
+ \qmlproperty real QtQuick::TableView::contentHeight
+
+ This property holds the height of the \l contentView, which is also
+ the height of the table (including margins). As a TableView cannot
+ always know the exact height of the table without loading all rows
+ in the model, the \c contentHeight is usually an estimated height
+ based on the rows it has seen so far. This estimate is recalculated
+ whenever new rows are flicked into view, which means that the content height
+ can change dynamically.
+
+ If you know up front what the height of the table will be, assign a
+ value to \c contentHeight explicitly, to avoid unnecessary calculations and
+ updates to the TableView.
+
+ \sa contentWidth
+*/
+
+/*!
+ \qmlmethod real QtQuick::TableView::forceLayout
+
+ Responding to changes in the model are batched so that they are handled
+ only once per frame. This means the TableView delays showing any changes
+ while a script is being run. The same is also true when changing
+ properties such as \l rowSpacing or \l leftMargin.
+
+ This method forces the TableView to immediately update the layout so
+ that any recent changes take effect.
+
+ Calling this function re-evaluates the size and position of each visible
+ row and column. This is needed if the functions assigned to
+ \l rowHeightProvider or \l columnWidthProvider return different values than
+ what is already assigned.
+*/
+
+/*!
+ \qmlattachedproperty TableView QtQuick::TableView::view
+
+ This attached property holds the view that manages the delegate instance.
+ It is attached to each instance of the delegate.
+*/
+
+/*!
+ \qmlattachedsignal QtQuick::TableView::pooled
+
+ This signal is emitted after an item has been added to the reuse
+ pool. You can use it to pause ongoing timers or animations inside
+ the item, or free up resources that cannot be reused.
+
+ This signal is emitted only if the \l reuseItems property is \c true.
+
+ \sa {Reusing items}, reuseItems, reused
+*/
+
+/*!
+ \qmlattachedsignal QtQuick::TableView::reused
+
+ This signal is emitted after an item has been reused. At this point, the
+ item has been taken out of the pool and placed inside the content view,
+ and the model properties such as index, row, and column have been updated.
+
+ Other properties that are not provided by the model does not change when an item
+ is reused. You should avoid storing any state inside a delegate, but if you do,
+ manually reset that state on receiving this signal.
+
+ This signal is emitted when the item is reused, and not the first time the
+ item is created.
+
+ This signal is emitted only if the \l reuseItems property is \c true.
+
+ \sa {Reusing items}, reuseItems, pooled
+*/
+
+QT_BEGIN_NAMESPACE
+
+Q_LOGGING_CATEGORY(lcTableViewDelegateLifecycle, "qt.quick.tableview.lifecycle")
+
+#define Q_TABLEVIEW_UNREACHABLE(output) { dumpTable(); qWarning() << "output:" << output; Q_UNREACHABLE(); }
+#define Q_TABLEVIEW_ASSERT(cond, output) Q_ASSERT((cond) || [&](){ dumpTable(); qWarning() << "output:" << output; return false;}())
+
+static const Qt::Edge allTableEdges[] = { Qt::LeftEdge, Qt::RightEdge, Qt::TopEdge, Qt::BottomEdge };
+
+static QLine rectangleEdge(const QRect &rect, Qt::Edge tableEdge)
+{
+ switch (tableEdge) {
+ case Qt::LeftEdge:
+ return QLine(rect.topLeft(), rect.bottomLeft());
+ case Qt::RightEdge:
+ return QLine(rect.topRight(), rect.bottomRight());
+ case Qt::TopEdge:
+ return QLine(rect.topLeft(), rect.topRight());
+ case Qt::BottomEdge:
+ return QLine(rect.bottomLeft(), rect.bottomRight());
+ }
+ return QLine();
+}
+
+static QRect expandedRect(const QRect &rect, Qt::Edge edge, int increment)
+{
+ switch (edge) {
+ case Qt::LeftEdge:
+ return rect.adjusted(-increment, 0, 0, 0);
+ case Qt::RightEdge:
+ return rect.adjusted(0, 0, increment, 0);
+ case Qt::TopEdge:
+ return rect.adjusted(0, -increment, 0, 0);
+ case Qt::BottomEdge:
+ return rect.adjusted(0, 0, 0, increment);
+ }
+ return QRect();
+}
+
+const QPoint QQuickTableViewPrivate::kLeft = QPoint(-1, 0);
+const QPoint QQuickTableViewPrivate::kRight = QPoint(1, 0);
+const QPoint QQuickTableViewPrivate::kUp = QPoint(0, -1);
+const QPoint QQuickTableViewPrivate::kDown = QPoint(0, 1);
+
+QQuickTableViewPrivate::QQuickTableViewPrivate()
+ : QQuickFlickablePrivate()
+{
+}
+
+QQuickTableViewPrivate::~QQuickTableViewPrivate()
+{
+ releaseLoadedItems(QQmlTableInstanceModel::NotReusable);
+ if (tableModel)
+ delete tableModel;
+}
+
+QString QQuickTableViewPrivate::tableLayoutToString() const
+{
+ return QString(QLatin1String("table cells: (%1,%2) -> (%3,%4), item count: %5, table rect: %6,%7 x %8,%9"))
+ .arg(loadedTable.topLeft().x()).arg(loadedTable.topLeft().y())
+ .arg(loadedTable.bottomRight().x()).arg(loadedTable.bottomRight().y())
+ .arg(loadedItems.count())
+ .arg(loadedTableOuterRect.x())
+ .arg(loadedTableOuterRect.y())
+ .arg(loadedTableOuterRect.width())
+ .arg(loadedTableOuterRect.height());
+}
+
+void QQuickTableViewPrivate::dumpTable() const
+{
+ auto listCopy = loadedItems.values();
+ std::stable_sort(listCopy.begin(), listCopy.end(),
+ [](const FxTableItem *lhs, const FxTableItem *rhs)
+ { return lhs->index < rhs->index; });
+
+ qWarning() << QStringLiteral("******* TABLE DUMP *******");
+ for (int i = 0; i < listCopy.count(); ++i)
+ qWarning() << static_cast<FxTableItem *>(listCopy.at(i))->cell;
+ qWarning() << tableLayoutToString();
+
+ const QString filename = QStringLiteral("QQuickTableView_dumptable_capture.png");
+ const QString path = QDir::current().absoluteFilePath(filename);
+ if (q_func()->window() && q_func()->window()->grabWindow().save(path))
+ qWarning() << "Window capture saved to:" << path;
+}
+
+QQuickTableViewAttached *QQuickTableViewPrivate::getAttachedObject(const QObject *object) const
+{
+ QObject *attachedObject = qmlAttachedPropertiesObject<QQuickTableView>(object);
+ return static_cast<QQuickTableViewAttached *>(attachedObject);
+}
+
+int QQuickTableViewPrivate::modelIndexAtCell(const QPoint &cell) const
+{
+ int availableRows = tableSize.height();
+ int modelIndex = cell.y() + (cell.x() * availableRows);
+ Q_TABLEVIEW_ASSERT(modelIndex < model->count(),
+ "modelIndex:" << modelIndex << "cell:" << cell << "count:" << model->count());
+ return modelIndex;
+}
+
+QPoint QQuickTableViewPrivate::cellAtModelIndex(int modelIndex) const
+{
+ int availableRows = tableSize.height();
+ Q_TABLEVIEW_ASSERT(availableRows > 0, availableRows);
+ int column = int(modelIndex / availableRows);
+ int row = modelIndex % availableRows;
+ return QPoint(column, row);
+}
+
+void QQuickTableViewPrivate::updateContentWidth()
+{
+ Q_Q(QQuickTableView);
+
+ if (explicitContentWidth.isValid()) {
+ // Don't calculate contentWidth when it
+ // was set explicitly by the application.
+ return;
+ }
+
+ const qreal thresholdBeforeAdjust = 0.1;
+ int currentRightColumn = loadedTable.right();
+
+ if (currentRightColumn > contentSizeBenchMarkPoint.x()) {
+ contentSizeBenchMarkPoint.setX(currentRightColumn);
+
+ const qreal spacing = currentRightColumn * cellSpacing.width();
+ qreal currentWidth = loadedTableOuterRect.right();
+ const qreal averageCellWidth = (currentWidth - spacing) / (currentRightColumn + 1);
+ qreal estimatedWidth = (tableSize.width() * (averageCellWidth + cellSpacing.width())) - cellSpacing.width();
+
+ if (currentRightColumn >= tableSize.width() - 1) {
+ // We are at the last column, and can set the exact width
+ if (!qFuzzyCompare(currentWidth, q->implicitWidth()))
+ q->QQuickFlickable::setContentWidth(currentWidth);
+ } else if (currentWidth >= q->implicitWidth()) {
+ // We are at the estimated width, but there are still more columns
+ q->QQuickFlickable::setContentWidth(estimatedWidth);
+ } else {
+ // Only set a new width if the new estimate is substantially different
+ qreal diff = 1 - (estimatedWidth / q->implicitWidth());
+ if (qAbs(diff) > thresholdBeforeAdjust)
+ q->QQuickFlickable::setContentWidth(estimatedWidth);
+ }
+ }
+}
+
+void QQuickTableViewPrivate::updateContentHeight()
+{
+ Q_Q(QQuickTableView);
+
+ if (explicitContentHeight.isValid()) {
+ // Don't calculate contentHeight when it
+ // was set explicitly by the application.
+ return;
+ }
+
+ const qreal thresholdBeforeAdjust = 0.1;
+ int currentBottomRow = loadedTable.bottom();
+
+ if (currentBottomRow > contentSizeBenchMarkPoint.y()) {
+ contentSizeBenchMarkPoint.setY(currentBottomRow);
+
+ const qreal spacing = currentBottomRow * cellSpacing.height();
+ qreal currentHeight = loadedTableOuterRect.bottom();
+ const qreal averageCellHeight = (currentHeight - spacing) / (currentBottomRow + 1);
+ qreal estimatedHeight = (tableSize.height() * (averageCellHeight + cellSpacing.height())) - cellSpacing.height();
+
+ if (currentBottomRow >= tableSize.height() - 1) {
+ // We are at the last row, and can set the exact height
+ if (!qFuzzyCompare(currentHeight, q->implicitHeight()))
+ q->QQuickFlickable::setContentHeight(currentHeight);
+ } else if (currentHeight >= q->implicitHeight()) {
+ // We are at the estimated height, but there are still more rows
+ q->QQuickFlickable::setContentHeight(estimatedHeight);
+ } else {
+ // Only set a new height if the new estimate is substantially different
+ qreal diff = 1 - (estimatedHeight / q->implicitHeight());
+ if (qAbs(diff) > thresholdBeforeAdjust)
+ q->QQuickFlickable::setContentHeight(estimatedHeight);
+ }
+ }
+}
+
+void QQuickTableViewPrivate::enforceTableAtOrigin()
+{
+ // Gaps before the first row/column can happen if rows/columns
+ // changes size while flicking e.g because of spacing changes or
+ // changes to a column maxWidth/row maxHeight. Check for this, and
+ // move the whole table rect accordingly.
+ bool layoutNeeded = false;
+ const qreal flickMargin = 50;
+
+ if (loadedTable.x() == 0 && loadedTableOuterRect.x() > 0) {
+ // The table is at the beginning, but not at the edge of the
+ // content view. So move the table to origin.
+ loadedTableOuterRect.moveLeft(0);
+ layoutNeeded = true;
+ } else if (loadedTableOuterRect.x() < 0) {
+ // The table is outside the beginning of the content view. Move
+ // the whole table inside, and make some room for flicking.
+ loadedTableOuterRect.moveLeft(loadedTable.x() == 0 ? 0 : flickMargin);
+ layoutNeeded = true;
+ }
+
+ if (loadedTable.y() == 0 && loadedTableOuterRect.y() > 0) {
+ loadedTableOuterRect.moveTop(0);
+ layoutNeeded = true;
+ } else if (loadedTableOuterRect.y() < 0) {
+ loadedTableOuterRect.moveTop(loadedTable.y() == 0 ? 0 : flickMargin);
+ layoutNeeded = true;
+ }
+
+ if (layoutNeeded) {
+ qCDebug(lcTableViewDelegateLifecycle);
+ relayoutTableItems();
+ }
+}
+
+void QQuickTableViewPrivate::updateAverageEdgeSize()
+{
+ int bottomCell = loadedTable.bottom();
+ int rightCell = loadedTable.right();
+ qreal accRowSpacing = bottomCell * cellSpacing.height();
+ qreal accColumnSpacing = rightCell * cellSpacing.width();
+ averageEdgeSize.setHeight((loadedTableOuterRect.bottom() - accRowSpacing) / (bottomCell + 1));
+ averageEdgeSize.setWidth((loadedTableOuterRect.right() - accColumnSpacing) / (rightCell + 1));
+}
+
+void QQuickTableViewPrivate::syncLoadedTableRectFromLoadedTable()
+{
+ QRectF topLeftRect = loadedTableItem(loadedTable.topLeft())->geometry();
+ QRectF bottomRightRect = loadedTableItem(loadedTable.bottomRight())->geometry();
+ loadedTableOuterRect = topLeftRect.united(bottomRightRect);
+ loadedTableInnerRect = QRectF(topLeftRect.bottomRight(), bottomRightRect.topLeft());
+}
+
+void QQuickTableViewPrivate::syncLoadedTableFromLoadRequest()
+{
+ if (loadRequest.edge() == Qt::Edge(0)) {
+ // No edge means we're loading the top-left item
+ loadedTable = QRect(loadRequest.firstCell(), loadRequest.lastCell());
+ return;
+ }
+
+ switch (loadRequest.edge()) {
+ case Qt::LeftEdge:
+ case Qt::TopEdge:
+ loadedTable.setTopLeft(loadRequest.firstCell());
+ break;
+ case Qt::RightEdge:
+ case Qt::BottomEdge:
+ loadedTable.setBottomRight(loadRequest.lastCell());
+ break;
+ }
+}
+
+FxTableItem *QQuickTableViewPrivate::itemNextTo(const FxTableItem *fxTableItem, const QPoint &direction) const
+{
+ return loadedTableItem(fxTableItem->cell + direction);
+}
+
+FxTableItem *QQuickTableViewPrivate::loadedTableItem(const QPoint &cell) const
+{
+ const int modelIndex = modelIndexAtCell(cell);
+ Q_TABLEVIEW_ASSERT(loadedItems.contains(modelIndex), modelIndex << cell);
+ return loadedItems.value(modelIndex);
+}
+
+FxTableItem *QQuickTableViewPrivate::createFxTableItem(const QPoint &cell, QQmlIncubator::IncubationMode incubationMode)
+{
+ Q_Q(QQuickTableView);
+
+ bool ownItem = false;
+ int modelIndex = modelIndexAtCell(cell);
+
+ QObject* object = model->object(modelIndex, incubationMode);
+ if (!object) {
+ if (model->incubationStatus(modelIndex) == QQmlIncubator::Loading) {
+ // Item is incubating. Return nullptr for now, and let the table call this
+ // function again once we get a callback to itemCreatedCallback().
+ return nullptr;
+ }
+
+ qWarning() << "TableView: failed loading index:" << modelIndex;
+ object = new QQuickItem();
+ ownItem = true;
+ }
+
+ QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
+ if (!item) {
+ // The model could not provide an QQuickItem for the
+ // given index, so we create a placeholder instead.
+ qWarning() << "TableView: delegate is not an item:" << modelIndex;
+ model->release(object);
+ item = new QQuickItem();
+ ownItem = true;
+ } else {
+ QQuickAnchors *anchors = QQuickItemPrivate::get(item)->_anchors;
+ if (anchors && anchors->activeDirections())
+ qmlWarning(item) << "TableView: detected anchors on delegate with index: " << modelIndex
+ << ". Use implicitWidth and implicitHeight instead.";
+ }
+
+ if (ownItem) {
+ // Parent item is normally set early on from initItemCallback (to
+ // allow bindings to the parent property). But if we created the item
+ // within this function, we need to set it explicit.
+ item->setImplicitWidth(kDefaultColumnWidth);
+ item->setImplicitHeight(kDefaultRowHeight);
+ item->setParentItem(q->contentItem());
+ }
+ Q_TABLEVIEW_ASSERT(item->parentItem() == q->contentItem(), item->parentItem());
+
+ FxTableItem *fxTableItem = new FxTableItem(item, q, ownItem);
+ fxTableItem->setVisible(false);
+ fxTableItem->cell = cell;
+ fxTableItem->index = modelIndex;
+ return fxTableItem;
+}
+
+FxTableItem *QQuickTableViewPrivate::loadFxTableItem(const QPoint &cell, QQmlIncubator::IncubationMode incubationMode)
+{
+#ifdef QT_DEBUG
+ // Since TableView needs to work flawlessly when e.g incubating inside an async
+ // loader, being able to override all loading to async while debugging can be helpful.
+ static const bool forcedAsync = forcedIncubationMode == QLatin1String("async");
+ if (forcedAsync)
+ incubationMode = QQmlIncubator::Asynchronous;
+#endif
+
+ // Note that even if incubation mode is asynchronous, the item might
+ // be ready immediately since the model has a cache of items.
+ QBoolBlocker guard(blockItemCreatedCallback);
+ auto item = createFxTableItem(cell, incubationMode);
+ qCDebug(lcTableViewDelegateLifecycle) << cell << "ready?" << bool(item);
+ return item;
+}
+
+void QQuickTableViewPrivate::releaseLoadedItems(QQmlTableInstanceModel::ReusableFlag reusableFlag) {
+ // Make a copy and clear the list of items first to avoid destroyed
+ // items being accessed during the loop (QTBUG-61294)
+ auto const tmpList = loadedItems;
+ loadedItems.clear();
+ for (FxTableItem *item : tmpList)
+ releaseItem(item, reusableFlag);
+}
+
+void QQuickTableViewPrivate::releaseItem(FxTableItem *fxTableItem, QQmlTableInstanceModel::ReusableFlag reusableFlag)
+{
+ Q_Q(QQuickTableView);
+ auto item = fxTableItem->item;
+ Q_TABLEVIEW_ASSERT(item, fxTableItem->index);
+
+ if (fxTableItem->ownItem) {
+ delete item;
+ } else {
+ // Only QQmlTableInstanceModel supports reusing items
+ auto releaseFlag = tableModel ?
+ tableModel->release(item, reusableFlag) :
+ model->release(item);
+
+ if (releaseFlag != QQmlInstanceModel::Destroyed) {
+ // When items are not destroyed, it typically means that the
+ // item is reused, or that the model is an ObjectModel. If
+ // so, we just hide the item instead.
+ fxTableItem->setVisible(false);
+
+ // If the item (or a descendant) has focus, remove it, so
+ // that the item doesn't enter with focus when it's reused.
+ if (QQuickWindow *window = item->window()) {
+ const auto focusItem = qobject_cast<QQuickItem *>(window->focusObject());
+ if (focusItem) {
+ const bool hasFocus = item == focusItem || item->isAncestorOf(focusItem);
+ if (hasFocus) {
+ const auto focusChild = QQuickItemPrivate::get(q)->subFocusItem;
+ QQuickWindowPrivate::get(window)->clearFocusInScope(q, focusChild, Qt::OtherFocusReason);
+ }
+ }
+ }
+ }
+ }
+
+ delete fxTableItem;
+}
+
+void QQuickTableViewPrivate::unloadItem(const QPoint &cell)
+{
+ const int modelIndex = modelIndexAtCell(cell);
+ Q_TABLEVIEW_ASSERT(loadedItems.contains(modelIndex), modelIndex << cell);
+ releaseItem(loadedItems.take(modelIndex), reusableFlag);
+}
+
+void QQuickTableViewPrivate::unloadItems(const QLine &items)
+{
+ qCDebug(lcTableViewDelegateLifecycle) << items;
+
+ if (items.dx()) {
+ int y = items.p1().y();
+ for (int x = items.p1().x(); x <= items.p2().x(); ++x)
+ unloadItem(QPoint(x, y));
+ } else {
+ int x = items.p1().x();
+ for (int y = items.p1().y(); y <= items.p2().y(); ++y)
+ unloadItem(QPoint(x, y));
+ }
+}
+
+bool QQuickTableViewPrivate::canLoadTableEdge(Qt::Edge tableEdge, const QRectF fillRect) const
+{
+ switch (tableEdge) {
+ case Qt::LeftEdge:
+ if (loadedTable.topLeft().x() == 0)
+ return false;
+ return loadedTableOuterRect.left() > fillRect.left() + cellSpacing.width();
+ case Qt::RightEdge:
+ if (loadedTable.bottomRight().x() >= tableSize.width() - 1)
+ return false;
+ return loadedTableOuterRect.right() < fillRect.right() - cellSpacing.width();
+ case Qt::TopEdge:
+ if (loadedTable.topLeft().y() == 0)
+ return false;
+ return loadedTableOuterRect.top() > fillRect.top() + cellSpacing.height();
+ case Qt::BottomEdge:
+ if (loadedTable.bottomRight().y() >= tableSize.height() - 1)
+ return false;
+ return loadedTableOuterRect.bottom() < fillRect.bottom() - cellSpacing.height();
+ }
+
+ return false;
+}
+
+bool QQuickTableViewPrivate::canUnloadTableEdge(Qt::Edge tableEdge, const QRectF fillRect) const
+{
+ // Note: if there is only one row or column left, we cannot unload, since
+ // they are needed as anchor point for further layouting.
+ switch (tableEdge) {
+ case Qt::LeftEdge:
+ if (loadedTable.width() <= 1)
+ return false;
+ return loadedTableInnerRect.left() <= fillRect.left();
+ case Qt::RightEdge:
+ if (loadedTable.width() <= 1)
+ return false;
+ return loadedTableInnerRect.right() >= fillRect.right();
+ case Qt::TopEdge:
+ if (loadedTable.height() <= 1)
+ return false;
+ return loadedTableInnerRect.top() <= fillRect.top();
+ case Qt::BottomEdge:
+ if (loadedTable.height() <= 1)
+ return false;
+ return loadedTableInnerRect.bottom() >= fillRect.bottom();
+ }
+ Q_TABLEVIEW_UNREACHABLE(tableEdge);
+ return false;
+}
+
+Qt::Edge QQuickTableViewPrivate::nextEdgeToLoad(const QRectF rect)
+{
+ for (Qt::Edge edge : allTableEdges) {
+ if (canLoadTableEdge(edge, rect))
+ return edge;
+ }
+ return Qt::Edge(0);
+}
+
+Qt::Edge QQuickTableViewPrivate::nextEdgeToUnload(const QRectF rect)
+{
+ for (Qt::Edge edge : allTableEdges) {
+ if (canUnloadTableEdge(edge, rect))
+ return edge;
+ }
+ return Qt::Edge(0);
+}
+
+qreal QQuickTableViewPrivate::cellWidth(const QPoint& cell)
+{
+ // Using an items width directly is not an option, since we change
+ // it during layout (which would also cause problems when recycling items).
+ auto const cellItem = loadedTableItem(cell)->item;
+ return cellItem->implicitWidth();
+}
+
+qreal QQuickTableViewPrivate::cellHeight(const QPoint& cell)
+{
+ // Using an items height directly is not an option, since we change
+ // it during layout (which would also cause problems when recycling items).
+ auto const cellItem = loadedTableItem(cell)->item;
+ return cellItem->implicitHeight();
+}
+
+qreal QQuickTableViewPrivate::sizeHintForColumn(int column)
+{
+ // Find the widest cell in the column, and return its width
+ qreal columnWidth = 0;
+ for (int row = loadedTable.top(); row <= loadedTable.bottom(); ++row)
+ columnWidth = qMax(columnWidth, cellWidth(QPoint(column, row)));
+
+ return columnWidth;
+}
+
+qreal QQuickTableViewPrivate::sizeHintForRow(int row)
+{
+ // Find the highest cell in the row, and return its height
+ qreal rowHeight = 0;
+ for (int column = loadedTable.left(); column <= loadedTable.right(); ++column)
+ rowHeight = qMax(rowHeight, cellHeight(QPoint(column, row)));
+
+ return rowHeight;
+}
+
+void QQuickTableViewPrivate::calculateTableSize()
+{
+ // tableSize is the same as row and column count, and will always
+ // be the same as the number of rows and columns in the model.
+ Q_Q(QQuickTableView);
+ QSize prevTableSize = tableSize;
+
+ if (tableModel)
+ tableSize = QSize(tableModel->columns(), tableModel->rows());
+ else if (model)
+ tableSize = QSize(1, model->count());
+ else
+ tableSize = QSize(0, 0);
+
+ if (prevTableSize.width() != tableSize.width())
+ emit q->columnsChanged();
+ if (prevTableSize.height() != tableSize.height())
+ emit q->rowsChanged();
+}
+
+qreal QQuickTableViewPrivate::resolveColumnWidth(int column)
+{
+ Q_TABLEVIEW_ASSERT(column >= loadedTable.left() && column <= loadedTable.right(), column);
+ qreal columnWidth = -1;
+
+ if (!columnWidthProvider.isUndefined()) {
+ if (columnWidthProvider.isCallable()) {
+ auto const columnAsArgument = QJSValueList() << QJSValue(column);
+ columnWidth = columnWidthProvider.call(columnAsArgument).toNumber();
+ if (qIsNaN(columnWidth) || columnWidth <= 0) {
+ // The column width needs to be greater than 0, otherwise we never reach the edge
+ // while loading/refilling columns. This would cause the application to hang.
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "columnWidthProvider did not return a valid width for column: " << column;
+ }
+ columnWidth = kDefaultColumnWidth;
+ }
+ } else {
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "columnWidthProvider doesn't contain a function";
+ }
+ columnWidth = kDefaultColumnWidth;
+ }
+ } else {
+ // If columnWidthProvider is left unspecified, we just iterate over the currently visible items in
+ // the column. The downside of doing that, is that the column width will then only be based
+ // on the implicit width of the currently loaded items (which can be different depending on
+ // which row you're at when the column is flicked in). The upshot is that you don't have to
+ // bother setting columnWidthProvider for small tables, or if the implicit width doesn't vary.
+ columnWidth = sizeHintForColumn(column);
+ if (qIsNaN(columnWidth) || columnWidth <= 0) {
+ // The column width needs to be greater than 0, otherwise we never reach the edge
+ // while loading/refilling columns. This would cause the application to hang.
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "the delegate's implicitWidth needs to be greater than zero";
+ }
+ columnWidth = kDefaultColumnWidth;
+ }
+ }
+
+ return columnWidth;
+}
+
+qreal QQuickTableViewPrivate::resolveRowHeight(int row)
+{
+ Q_TABLEVIEW_ASSERT(row >= loadedTable.top() && row <= loadedTable.bottom(), row);
+ qreal rowHeight = -1;
+
+ if (!rowHeightProvider.isUndefined()) {
+ if (rowHeightProvider.isCallable()) {
+ auto const rowAsArgument = QJSValueList() << QJSValue(row);
+ rowHeight = rowHeightProvider.call(rowAsArgument).toNumber();
+ if (qIsNaN(rowHeight) || rowHeight <= 0) {
+ // The row height needs to be greater than 0, otherwise we never reach the edge
+ // while loading/refilling rows. This would cause the application to hang.
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "rowHeightProvider did not return a valid height for row: " << row;
+ }
+ rowHeight = kDefaultRowHeight;
+ }
+ } else {
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "rowHeightProvider doesn't contain a function";
+ }
+ rowHeight = kDefaultRowHeight;
+ }
+ } else {
+ // If rowHeightProvider is left unspecified, we just iterate over the currently visible items in
+ // the row. The downside of doing that, is that the row height will then only be based
+ // on the implicit height of the currently loaded items (which can be different depending on
+ // which column you're at when the row is flicked in). The upshot is that you don't have to
+ // bother setting rowHeightProvider for small tables, or if the implicit height doesn't vary.
+ rowHeight = sizeHintForRow(row);
+ if (qIsNaN(rowHeight) || rowHeight <= 0) {
+ if (!layoutWarningIssued) {
+ layoutWarningIssued = true;
+ qmlWarning(q_func()) << "the delegate's implicitHeight needs to be greater than zero";
+ }
+ rowHeight = kDefaultRowHeight;
+ }
+ }
+
+ return rowHeight;
+}
+
+void QQuickTableViewPrivate::relayoutTable()
+{
+ relayoutTableItems();
+ syncLoadedTableRectFromLoadedTable();
+ enforceTableAtOrigin();
+ contentSizeBenchMarkPoint = QPoint(-1, -1);
+ updateContentWidth();
+ updateContentHeight();
+ // Return back to updatePolish to loadAndUnloadVisibleEdges()
+ // since the re-layout might have caused some edges to be pushed
+ // out, while others might have been pushed in.
+}
+
+void QQuickTableViewPrivate::relayoutTableItems()
+{
+ qCDebug(lcTableViewDelegateLifecycle);
+ columnRowPositionsInvalid = false;
+
+ qreal nextColumnX = loadedTableOuterRect.x();
+ qreal nextRowY = loadedTableOuterRect.y();
+
+ for (int column = loadedTable.left(); column <= loadedTable.right(); ++column) {
+ // Adjust the geometry of all cells in the current column
+ const qreal width = resolveColumnWidth(column);
+
+ for (int row = loadedTable.top(); row <= loadedTable.bottom(); ++row) {
+ auto item = loadedTableItem(QPoint(column, row));
+ QRectF geometry = item->geometry();
+ geometry.moveLeft(nextColumnX);
+ geometry.setWidth(width);
+ item->setGeometry(geometry);
+ }
+
+ nextColumnX += width + cellSpacing.width();
+ }
+
+ for (int row = loadedTable.top(); row <= loadedTable.bottom(); ++row) {
+ // Adjust the geometry of all cells in the current row
+ const qreal height = resolveRowHeight(row);
+
+ for (int column = loadedTable.left(); column <= loadedTable.right(); ++column) {
+ auto item = loadedTableItem(QPoint(column, row));
+ QRectF geometry = item->geometry();
+ geometry.moveTop(nextRowY);
+ geometry.setHeight(height);
+ item->setGeometry(geometry);
+ }
+
+ nextRowY += height + cellSpacing.height();
+ }
+
+ if (Q_UNLIKELY(lcTableViewDelegateLifecycle().isDebugEnabled())) {
+ for (int column = loadedTable.left(); column <= loadedTable.right(); ++column) {
+ for (int row = loadedTable.top(); row <= loadedTable.bottom(); ++row) {
+ QPoint cell = QPoint(column, row);
+ qCDebug(lcTableViewDelegateLifecycle()) << "relayout item:" << cell << loadedTableItem(cell)->geometry();
+ }
+ }
+ }
+}
+
+void QQuickTableViewPrivate::layoutVerticalEdge(Qt::Edge tableEdge)
+{
+ int column = (tableEdge == Qt::LeftEdge) ? loadedTable.left() : loadedTable.right();
+ QPoint neighbourDirection = (tableEdge == Qt::LeftEdge) ? kRight : kLeft;
+ qreal width = resolveColumnWidth(column);
+
+ for (int row = loadedTable.top(); row <= loadedTable.bottom(); ++row) {
+ auto fxTableItem = loadedTableItem(QPoint(column, row));
+ auto const neighbourItem = itemNextTo(fxTableItem, neighbourDirection);
+
+ QRectF geometry = fxTableItem->geometry();
+ geometry.setWidth(width);
+ geometry.setHeight(neighbourItem->geometry().height());
+ qreal left = tableEdge == Qt::LeftEdge ?
+ neighbourItem->geometry().left() - cellSpacing.width() - geometry.width() :
+ neighbourItem->geometry().right() + cellSpacing.width();
+
+ geometry.moveLeft(left);
+ geometry.moveTop(neighbourItem->geometry().top());
+
+ fxTableItem->setGeometry(geometry);
+ fxTableItem->setVisible(true);
+
+ qCDebug(lcTableViewDelegateLifecycle()) << "layout item:" << QPoint(column, row) << fxTableItem->geometry();
+ }
+}
+
+void QQuickTableViewPrivate::layoutHorizontalEdge(Qt::Edge tableEdge)
+{
+ int row = (tableEdge == Qt::TopEdge) ? loadedTable.top() : loadedTable.bottom();
+ QPoint neighbourDirection = (tableEdge == Qt::TopEdge) ? kDown : kUp;
+ qreal height = resolveRowHeight(row);
+
+ for (int column = loadedTable.left(); column <= loadedTable.right(); ++column) {
+ auto fxTableItem = loadedTableItem(QPoint(column, row));
+ auto const neighbourItem = itemNextTo(fxTableItem, neighbourDirection);
+
+ QRectF geometry = fxTableItem->geometry();
+ geometry.setWidth(neighbourItem->geometry().width());
+ geometry.setHeight(height);
+ qreal top = tableEdge == Qt::TopEdge ?
+ neighbourItem->geometry().top() - cellSpacing.height() - geometry.height() :
+ neighbourItem->geometry().bottom() + cellSpacing.height();
+
+ geometry.moveTop(top);
+ geometry.moveLeft(neighbourItem->geometry().left());
+
+ fxTableItem->setGeometry(geometry);
+ fxTableItem->setVisible(true);
+
+ qCDebug(lcTableViewDelegateLifecycle()) << "layout item:" << QPoint(column, row) << fxTableItem->geometry();
+ }
+}
+
+void QQuickTableViewPrivate::layoutTopLeftItem()
+{
+ const QPoint cell = loadRequest.firstCell();
+ auto topLeftItem = loadedTableItem(cell);
+ auto item = topLeftItem->item;
+
+ item->setPosition(loadRequest.startPosition());
+ item->setSize(QSizeF(resolveColumnWidth(cell.x()), resolveRowHeight(cell.y())));
+ topLeftItem->setVisible(true);
+ qCDebug(lcTableViewDelegateLifecycle) << "geometry:" << topLeftItem->geometry();
+}
+
+void QQuickTableViewPrivate::layoutTableEdgeFromLoadRequest()
+{
+ if (loadRequest.edge() == Qt::Edge(0)) {
+ // No edge means we're loading the top-left item
+ layoutTopLeftItem();
+ return;
+ }
+
+ switch (loadRequest.edge()) {
+ case Qt::LeftEdge:
+ case Qt::RightEdge:
+ layoutVerticalEdge(loadRequest.edge());
+ break;
+ case Qt::TopEdge:
+ case Qt::BottomEdge:
+ layoutHorizontalEdge(loadRequest.edge());
+ break;
+ }
+}
+
+void QQuickTableViewPrivate::cancelLoadRequest()
+{
+ loadRequest.markAsDone();
+ model->cancel(modelIndexAtCell(loadRequest.currentCell()));
+
+ if (rebuildScheduled) {
+ // No reason to rollback already loaded edge items
+ // since we anyway are about to reload all items.
+ return;
+ }
+
+ if (loadRequest.atBeginning()) {
+ // No items have yet been loaded, so nothing to unload
+ return;
+ }
+
+ QLine rollbackItems;
+ rollbackItems.setP1(loadRequest.firstCell());
+ rollbackItems.setP2(loadRequest.previousCell());
+ qCDebug(lcTableViewDelegateLifecycle()) << "rollback:" << rollbackItems << tableLayoutToString();
+ unloadItems(rollbackItems);
+}
+
+void QQuickTableViewPrivate::processLoadRequest()
+{
+ Q_TABLEVIEW_ASSERT(loadRequest.isActive(), "");
+
+ while (loadRequest.hasCurrentCell()) {
+ QPoint cell = loadRequest.currentCell();
+ FxTableItem *fxTableItem = loadFxTableItem(cell, loadRequest.incubationMode());
+
+ if (!fxTableItem) {
+ // Requested item is not yet ready. Just leave, and wait for this
+ // function to be called again when the item is ready.
+ return;
+ }
+
+ loadedItems.insert(modelIndexAtCell(cell), fxTableItem);
+ loadRequest.moveToNextCell();
+ }
+
+ qCDebug(lcTableViewDelegateLifecycle()) << "all items loaded!";
+
+ syncLoadedTableFromLoadRequest();
+ layoutTableEdgeFromLoadRequest();
+ syncLoadedTableRectFromLoadedTable();
+
+ if (rebuildState == RebuildState::Done) {
+ enforceTableAtOrigin();
+ updateContentWidth();
+ updateContentHeight();
+ drainReusePoolAfterLoadRequest();
+ }
+
+ loadRequest.markAsDone();
+
+ qCDebug(lcTableViewDelegateLifecycle()) << "request completed! Table:" << tableLayoutToString();
+}
+
+void QQuickTableViewPrivate::processRebuildTable()
+{
+ moveToNextRebuildState();
+
+ if (rebuildState == RebuildState::LoadInitalTable) {
+ beginRebuildTable();
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ if (rebuildState == RebuildState::VerifyTable) {
+ if (loadedItems.isEmpty()) {
+ qCDebug(lcTableViewDelegateLifecycle()) << "no items loaded, meaning empty model or no delegate";
+ rebuildState = RebuildState::Done;
+ return;
+ }
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ if (rebuildState == RebuildState::LayoutTable) {
+ layoutAfterLoadingInitialTable();
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ if (rebuildState == RebuildState::LoadAndUnloadAfterLayout) {
+ loadAndUnloadVisibleEdges();
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ const bool preload = (rebuildOptions & RebuildOption::All
+ && reusableFlag == QQmlTableInstanceModel::Reusable);
+
+ if (rebuildState == RebuildState::PreloadColumns) {
+ if (preload && loadedTable.right() < tableSize.width() - 1)
+ loadEdge(Qt::RightEdge, QQmlIncubator::AsynchronousIfNested);
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ if (rebuildState == RebuildState::PreloadRows) {
+ if (preload && loadedTable.bottom() < tableSize.height() - 1)
+ loadEdge(Qt::BottomEdge, QQmlIncubator::AsynchronousIfNested);
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ if (rebuildState == RebuildState::MovePreloadedItemsToPool) {
+ while (Qt::Edge edge = nextEdgeToUnload(viewportRect))
+ unloadEdge(edge);
+ if (!moveToNextRebuildState())
+ return;
+ }
+
+ Q_TABLEVIEW_ASSERT(rebuildState == RebuildState::Done, int(rebuildState));
+}
+
+bool QQuickTableViewPrivate::moveToNextRebuildState()
+{
+ if (loadRequest.isActive()) {
+ // Items are still loading async, which means
+ // that the current state is not yet done.
+ return false;
+ }
+ rebuildState = RebuildState(int(rebuildState) + 1);
+ qCDebug(lcTableViewDelegateLifecycle()) << int(rebuildState);
+ return true;
+}
+
+void QQuickTableViewPrivate::beginRebuildTable()
+{
+ if (loadRequest.isActive())
+ cancelLoadRequest();
+
+ calculateTableSize();
+
+ QPoint topLeft;
+ QPointF topLeftPos;
+
+ if (rebuildOptions & RebuildOption::All) {
+ qCDebug(lcTableViewDelegateLifecycle()) << "RebuildOption::All";
+ releaseLoadedItems(QQmlTableInstanceModel::NotReusable);
+ } else if (rebuildOptions & RebuildOption::ViewportOnly) {
+ qCDebug(lcTableViewDelegateLifecycle()) << "RebuildOption::ViewportOnly";
+ releaseLoadedItems(reusableFlag);
+
+ if (rebuildOptions & RebuildOption::CalculateNewTopLeftRow) {
+ const int newRow = int(viewportRect.y() / (averageEdgeSize.height() + cellSpacing.height()));
+ topLeft.ry() = qBound(0, newRow, tableSize.height() - 1);
+ topLeftPos.ry() = topLeft.y() * (averageEdgeSize.height() + cellSpacing.height());
+ } else {
+ topLeft.ry() = qBound(0, loadedTable.topLeft().y(), tableSize.height() - 1);
+ topLeftPos.ry() = loadedTableOuterRect.topLeft().y();
+ }
+ if (rebuildOptions & RebuildOption::CalculateNewTopLeftColumn) {
+ const int newColumn = int(viewportRect.x() / (averageEdgeSize.width() + cellSpacing.width()));
+ topLeft.rx() = qBound(0, newColumn, tableSize.width() - 1);
+ topLeftPos.rx() = topLeft.x() * (averageEdgeSize.width() + cellSpacing.width());
+ } else {
+ topLeft.rx() = qBound(0, loadedTable.topLeft().x(), tableSize.width() - 1);
+ topLeftPos.rx() = loadedTableOuterRect.topLeft().x();
+ }
+ } else {
+ Q_TABLEVIEW_UNREACHABLE(rebuildOptions);
+ }
+
+ loadedTable = QRect();
+ loadedTableOuterRect = QRect();
+ loadedTableInnerRect = QRect();
+ contentSizeBenchMarkPoint = QPoint(-1, -1);
+ columnRowPositionsInvalid = false;
+
+ loadInitialTopLeftItem(topLeft, topLeftPos);
+ loadAndUnloadVisibleEdges();
+}
+
+void QQuickTableViewPrivate::layoutAfterLoadingInitialTable()
+{
+ if (rowHeightProvider.isUndefined() || columnWidthProvider.isUndefined()) {
+ // Since we don't have both size providers, we need to calculate the
+ // size of each row and column based on the size of the delegate items.
+ // This couldn't be done while we were loading the initial rows and
+ // columns, since during the process, we didn't have all the items
+ // available yet for the calculation. So we do it now.
+ relayoutTable();
+ }
+
+ updateAverageEdgeSize();
+ updateContentWidth();
+ updateContentHeight();
+}
+
+void QQuickTableViewPrivate::loadInitialTopLeftItem(const QPoint &cell, const QPointF &pos)
+{
+ Q_TABLEVIEW_ASSERT(loadedItems.isEmpty(), "");
+
+ if (tableSize.isEmpty())
+ return;
+
+ if (model->count() == 0)
+ return;
+
+ if (tableModel && !tableModel->delegate())
+ return;
+
+ // Load top-left item. After loaded, loadItemsInsideRect() will take
+ // care of filling out the rest of the table.
+ loadRequest.begin(cell, pos, QQmlIncubator::AsynchronousIfNested);
+ processLoadRequest();
+}
+
+void QQuickTableViewPrivate::unloadEdge(Qt::Edge edge)
+{
+ unloadItems(rectangleEdge(loadedTable, edge));
+ loadedTable = expandedRect(loadedTable, edge, -1);
+ syncLoadedTableRectFromLoadedTable();
+ qCDebug(lcTableViewDelegateLifecycle) << tableLayoutToString();
+}
+
+void QQuickTableViewPrivate::loadEdge(Qt::Edge edge, QQmlIncubator::IncubationMode incubationMode)
+{
+ QLine cellsToLoad = rectangleEdge(expandedRect(loadedTable, edge, 1), edge);
+ loadRequest.begin(cellsToLoad, edge, incubationMode);
+ processLoadRequest();
+}
+
+void QQuickTableViewPrivate::loadAndUnloadVisibleEdges()
+{
+ // Unload table edges that have been moved outside the visible part of the
+ // table (including buffer area), and load new edges that has been moved inside.
+ // Note: an important point is that we always keep the table rectangular
+ // and without holes to reduce complexity (we never leave the table in
+ // a half-loaded state, or keep track of multiple patches).
+ // We load only one edge (row or column) at a time. This is especially
+ // important when loading into the buffer, since we need to be able to
+ // cancel the buffering quickly if the user starts to flick, and then
+ // focus all further loading on the edges that are flicked into view.
+
+ if (loadRequest.isActive()) {
+ // Don't start loading more edges while we're
+ // already waiting for another one to load.
+ return;
+ }
+
+ if (loadedItems.isEmpty()) {
+ // We need at least the top-left item to be loaded before we can
+ // start loading edges around it. Not having a top-left item at
+ // this point means that the model is empty (or no delegate).
+ return;
+ }
+
+ bool tableModified;
+
+ do {
+ tableModified = false;
+
+ if (Qt::Edge edge = nextEdgeToUnload(viewportRect)) {
+ tableModified = true;
+ unloadEdge(edge);
+ }
+
+ if (Qt::Edge edge = nextEdgeToLoad(viewportRect)) {
+ tableModified = true;
+ loadEdge(edge, QQmlIncubator::AsynchronousIfNested);
+ if (loadRequest.isActive())
+ return;
+ }
+ } while (tableModified);
+
+}
+
+void QQuickTableViewPrivate::drainReusePoolAfterLoadRequest()
+{
+ Q_Q(QQuickTableView);
+
+ if (reusableFlag == QQmlTableInstanceModel::NotReusable || !tableModel)
+ return;
+
+ if (!qFuzzyIsNull(q->verticalOvershoot()) || !qFuzzyIsNull(q->horizontalOvershoot())) {
+ // Don't drain while we're overshooting, since this will fill up the
+ // pool, but we expect to reuse them all once the content item moves back.
+ return;
+ }
+
+ // When loading edges, we don't want to drain the reuse pool too aggressively. Normally,
+ // all the items in the pool are reused rapidly as the content view is flicked around
+ // anyway. Even if the table is temporarily flicked to a section that contains fewer
+ // cells than what used to be (e.g if the flicked-in rows are taller than average), it
+ // still makes sense to keep all the items in circulation; Chances are, that soon enough,
+ // thinner rows are flicked back in again (meaning that we can fit more items into the
+ // view). But at the same time, if a delegate chooser is in use, the pool might contain
+ // items created from different delegates. And some of those delegates might be used only
+ // occasionally. So to avoid situations where an item ends up in the pool for too long, we
+ // call drain after each load request, but with a sufficiently large pool time. (If an item
+ // in the pool has a large pool time, it means that it hasn't been reused for an equal
+ // amount of load cycles, and should be released).
+ //
+ // We calculate an appropriate pool time by figuring out what the minimum time must be to
+ // not disturb frequently reused items. Since the number of items in a row might be higher
+ // than in a column (or vice versa), the minimum pool time should take into account that
+ // you might be flicking out a single row (filling up the pool), before you continue
+ // flicking in several new columns (taking them out again, but now in smaller chunks). This
+ // will increase the number of load cycles items are kept in the pool (poolTime), but still,
+ // we shouldn't release them, as they are still being reused frequently.
+ // To get a flexible maxValue (that e.g tolerates rows and columns being flicked
+ // in with varying sizes, causing some items not to be resued immediately), we multiply the
+ // value by 2. Note that we also add an extra +1 to the column count, because the number of
+ // visible columns will fluctuate between +1/-1 while flicking.
+ const int w = loadedTable.width();
+ const int h = loadedTable.height();
+ const int minTime = int(std::ceil(w > h ? qreal(w + 1) / h : qreal(h + 1) / w));
+ const int maxTime = minTime * 2;
+ tableModel->drainReusableItemsPool(maxTime);
+}
+
+void QQuickTableViewPrivate::scheduleRebuildTable(RebuildOptions options) {
+ if (!q_func()->isComponentComplete()) {
+ // We'll rebuild the table once complete anyway
+ return;
+ }
+
+ rebuildScheduled = true;
+ scheduledRebuildOptions |= options;
+ q_func()->polish();
+}
+
+void QQuickTableViewPrivate::invalidateColumnRowPositions() {
+ columnRowPositionsInvalid = true;
+ q_func()->polish();
+}
+
+void QQuickTableViewPrivate::updatePolish()
+{
+ // Whenever something changes, e.g viewport moves, spacing is set to a
+ // new value, model changes etc, this function will end up being called. Here
+ // we check what needs to be done, and load/unload cells accordingly.
+
+ Q_TABLEVIEW_ASSERT(!polishing, "recursive updatePolish() calls are not allowed!");
+ QBoolBlocker polishGuard(polishing, true);
+
+ if (loadRequest.isActive()) {
+ // We're currently loading items async to build a new edge in the table. We see the loading
+ // as an atomic operation, which means that we don't continue doing anything else until all
+ // items have been received and laid out. Note that updatePolish is then called once more
+ // after the loadRequest has completed to handle anything that might have occurred in-between.
+ return;
+ }
+
+ if (rebuildState != RebuildState::Done) {
+ processRebuildTable();
+ return;
+ }
+
+ syncWithPendingChanges();
+
+ if (rebuildState == RebuildState::Begin) {
+ processRebuildTable();
+ return;
+ }
+
+ if (loadedItems.isEmpty())
+ return;
+
+ if (columnRowPositionsInvalid)
+ relayoutTable();
+
+ loadAndUnloadVisibleEdges();
+}
+
+void QQuickTableViewPrivate::fixup(QQuickFlickablePrivate::AxisData &data, qreal minExtent, qreal maxExtent)
+{
+ if (rebuildScheduled || rebuildState != RebuildState::Done)
+ return;
+
+ QQuickFlickablePrivate::fixup(data, minExtent, maxExtent);
+}
+
+void QQuickTableViewPrivate::createWrapperModel()
+{
+ Q_Q(QQuickTableView);
+ // When the assigned model is not an instance model, we create a wrapper
+ // model (QQmlTableInstanceModel) that keeps a pointer to both the
+ // assigned model and the assigned delegate. This model will give us a
+ // common interface to any kind of model (js arrays, QAIM, number etc), and
+ // help us create delegate instances.
+ tableModel = new QQmlTableInstanceModel(qmlContext(q));
+ model = tableModel;
+}
+
+void QQuickTableViewPrivate::itemCreatedCallback(int modelIndex, QObject*)
+{
+ if (blockItemCreatedCallback)
+ return;
+
+ qCDebug(lcTableViewDelegateLifecycle) << "item done loading:"
+ << cellAtModelIndex(modelIndex);
+
+ // Since the item we waited for has finished incubating, we can
+ // continue with the load request. processLoadRequest will
+ // ask the model for the requested item once more, which will be
+ // quick since the model has cached it.
+ processLoadRequest();
+ loadAndUnloadVisibleEdges();
+ updatePolish();
+}
+
+void QQuickTableViewPrivate::initItemCallback(int modelIndex, QObject *object)
+{
+ Q_UNUSED(modelIndex);
+ Q_Q(QQuickTableView);
+
+ if (auto item = qmlobject_cast<QQuickItem*>(object)) {
+ item->setParentItem(q->contentItem());
+ item->setZ(1);
+ }
+
+ if (auto attached = getAttachedObject(object))
+ attached->setView(q);
+}
+
+void QQuickTableViewPrivate::itemPooledCallback(int modelIndex, QObject *object)
+{
+ Q_UNUSED(modelIndex);
+
+ if (auto attached = getAttachedObject(object))
+ emit attached->pooled();
+}
+
+void QQuickTableViewPrivate::itemReusedCallback(int modelIndex, QObject *object)
+{
+ Q_UNUSED(modelIndex);
+
+ if (auto attached = getAttachedObject(object))
+ emit attached->reused();
+}
+
+void QQuickTableViewPrivate::syncWithPendingChanges()
+{
+ // The application can change properties like the model or the delegate while
+ // we're e.g in the middle of e.g loading a new row. Since this will lead to
+ // unpredicted behavior, and possibly a crash, we need to postpone taking
+ // such assignments into effect until we're in a state that allows it.
+ Q_Q(QQuickTableView);
+ viewportRect = QRectF(q->contentX(), q->contentY(), q->width(), q->height());
+ syncRebuildOptions();
+ syncModel();
+ syncDelegate();
+}
+
+void QQuickTableViewPrivate::syncRebuildOptions()
+{
+ if (!rebuildScheduled)
+ return;
+
+ rebuildState = RebuildState::Begin;
+ rebuildOptions = scheduledRebuildOptions;
+ scheduledRebuildOptions = RebuildOption::None;
+ rebuildScheduled = false;
+}
+
+void QQuickTableViewPrivate::syncDelegate()
+{
+ if (tableModel && assignedDelegate == tableModel->delegate())
+ return;
+
+ if (!tableModel)
+ createWrapperModel();
+
+ tableModel->setDelegate(assignedDelegate);
+}
+
+void QQuickTableViewPrivate::syncModel()
+{
+ if (modelVariant == assignedModel)
+ return;
+
+ if (model)
+ disconnectFromModel();
+
+ modelVariant = assignedModel;
+ QVariant effectiveModelVariant = modelVariant;
+ if (effectiveModelVariant.userType() == qMetaTypeId<QJSValue>())
+ effectiveModelVariant = effectiveModelVariant.value<QJSValue>().toVariant();
+
+ const auto instanceModel = qobject_cast<QQmlInstanceModel *>(qvariant_cast<QObject*>(effectiveModelVariant));
+
+ if (instanceModel) {
+ if (tableModel) {
+ delete tableModel;
+ tableModel = nullptr;
+ }
+ model = instanceModel;
+ } else {
+ if (!tableModel)
+ createWrapperModel();
+ tableModel->setModel(effectiveModelVariant);
+ }
+
+ connectToModel();
+}
+
+void QQuickTableViewPrivate::connectToModel()
+{
+ Q_TABLEVIEW_ASSERT(model, "");
+
+ QObjectPrivate::connect(model, &QQmlInstanceModel::createdItem, this, &QQuickTableViewPrivate::itemCreatedCallback);
+ QObjectPrivate::connect(model, &QQmlInstanceModel::initItem, this, &QQuickTableViewPrivate::initItemCallback);
+
+ if (tableModel) {
+ QObjectPrivate::connect(tableModel, &QQmlTableInstanceModel::itemPooled, this, &QQuickTableViewPrivate::itemPooledCallback);
+ QObjectPrivate::connect(tableModel, &QQmlTableInstanceModel::itemReused, this, &QQuickTableViewPrivate::itemReusedCallback);
+ }
+
+ if (auto const aim = model->abstractItemModel()) {
+ // When the model exposes a QAIM, we connect to it directly. This means that if the current model is
+ // a QQmlDelegateModel, we just ignore all the change sets it emits. In most cases, the model will instead
+ // be our own QQmlTableInstanceModel, which doesn't bother creating change sets at all. For models that are
+ // not based on QAIM (like QQmlObjectModel, QQmlListModel, javascript arrays etc), there is currently no way
+ // to modify the model at runtime without also re-setting the model on the view.
+ connect(aim, &QAbstractItemModel::rowsMoved, this, &QQuickTableViewPrivate::rowsMovedCallback);
+ connect(aim, &QAbstractItemModel::columnsMoved, this, &QQuickTableViewPrivate::columnsMovedCallback);
+ connect(aim, &QAbstractItemModel::rowsInserted, this, &QQuickTableViewPrivate::rowsInsertedCallback);
+ connect(aim, &QAbstractItemModel::rowsRemoved, this, &QQuickTableViewPrivate::rowsRemovedCallback);
+ connect(aim, &QAbstractItemModel::columnsInserted, this, &QQuickTableViewPrivate::columnsInsertedCallback);
+ connect(aim, &QAbstractItemModel::columnsRemoved, this, &QQuickTableViewPrivate::columnsRemovedCallback);
+ connect(aim, &QAbstractItemModel::modelReset, this, &QQuickTableViewPrivate::modelResetCallback);
+ connect(aim, &QAbstractItemModel::layoutChanged, this, &QQuickTableViewPrivate::layoutChangedCallback);
+ } else {
+ QObjectPrivate::connect(model, &QQmlInstanceModel::modelUpdated, this, &QQuickTableViewPrivate::modelUpdated);
+ }
+}
+
+void QQuickTableViewPrivate::disconnectFromModel()
+{
+ Q_TABLEVIEW_ASSERT(model, "");
+
+ QObjectPrivate::disconnect(model, &QQmlInstanceModel::createdItem, this, &QQuickTableViewPrivate::itemCreatedCallback);
+ QObjectPrivate::disconnect(model, &QQmlInstanceModel::initItem, this, &QQuickTableViewPrivate::initItemCallback);
+
+ if (tableModel) {
+ QObjectPrivate::disconnect(tableModel, &QQmlTableInstanceModel::itemPooled, this, &QQuickTableViewPrivate::itemPooledCallback);
+ QObjectPrivate::disconnect(tableModel, &QQmlTableInstanceModel::itemReused, this, &QQuickTableViewPrivate::itemReusedCallback);
+ }
+
+ if (auto const aim = model->abstractItemModel()) {
+ disconnect(aim, &QAbstractItemModel::rowsMoved, this, &QQuickTableViewPrivate::rowsMovedCallback);
+ disconnect(aim, &QAbstractItemModel::columnsMoved, this, &QQuickTableViewPrivate::columnsMovedCallback);
+ disconnect(aim, &QAbstractItemModel::rowsInserted, this, &QQuickTableViewPrivate::rowsInsertedCallback);
+ disconnect(aim, &QAbstractItemModel::rowsRemoved, this, &QQuickTableViewPrivate::rowsRemovedCallback);
+ disconnect(aim, &QAbstractItemModel::columnsInserted, this, &QQuickTableViewPrivate::columnsInsertedCallback);
+ disconnect(aim, &QAbstractItemModel::columnsRemoved, this, &QQuickTableViewPrivate::columnsRemovedCallback);
+ disconnect(aim, &QAbstractItemModel::modelReset, this, &QQuickTableViewPrivate::modelResetCallback);
+ disconnect(aim, &QAbstractItemModel::layoutChanged, this, &QQuickTableViewPrivate::layoutChangedCallback);
+ } else {
+ QObjectPrivate::disconnect(model, &QQmlInstanceModel::modelUpdated, this, &QQuickTableViewPrivate::modelUpdated);
+ }
+}
+
+void QQuickTableViewPrivate::modelUpdated(const QQmlChangeSet &changeSet, bool reset)
+{
+ Q_UNUSED(changeSet);
+ Q_UNUSED(reset);
+
+ Q_TABLEVIEW_ASSERT(!model->abstractItemModel(), "");
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::rowsMovedCallback(const QModelIndex &parent, int, int, const QModelIndex &, int )
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::columnsMovedCallback(const QModelIndex &parent, int, int, const QModelIndex &, int)
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::rowsInsertedCallback(const QModelIndex &parent, int, int)
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::rowsRemovedCallback(const QModelIndex &parent, int, int)
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::columnsInsertedCallback(const QModelIndex &parent, int, int)
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::columnsRemovedCallback(const QModelIndex &parent, int, int)
+{
+ if (parent != QModelIndex())
+ return;
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::layoutChangedCallback(const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint)
+{
+ Q_UNUSED(parents);
+ Q_UNUSED(hint);
+
+ scheduleRebuildTable(RebuildOption::ViewportOnly);
+}
+
+void QQuickTableViewPrivate::modelResetCallback()
+{
+ scheduleRebuildTable(RebuildOption::All);
+}
+
+QQuickTableView::QQuickTableView(QQuickItem *parent)
+ : QQuickFlickable(*(new QQuickTableViewPrivate), parent)
+{
+ setFlag(QQuickItem::ItemIsFocusScope);
+}
+
+int QQuickTableView::rows() const
+{
+ return d_func()->tableSize.height();
+}
+
+int QQuickTableView::columns() const
+{
+ return d_func()->tableSize.width();
+}
+
+qreal QQuickTableView::rowSpacing() const
+{
+ return d_func()->cellSpacing.height();
+}
+
+void QQuickTableView::setRowSpacing(qreal spacing)
+{
+ Q_D(QQuickTableView);
+ if (qt_is_nan(spacing) || !qt_is_finite(spacing) || spacing < 0)
+ return;
+ if (qFuzzyCompare(d->cellSpacing.height(), spacing))
+ return;
+
+ d->cellSpacing.setHeight(spacing);
+ d->invalidateColumnRowPositions();
+ emit rowSpacingChanged();
+}
+
+qreal QQuickTableView::columnSpacing() const
+{
+ return d_func()->cellSpacing.width();
+}
+
+void QQuickTableView::setColumnSpacing(qreal spacing)
+{
+ Q_D(QQuickTableView);
+ if (qt_is_nan(spacing) || !qt_is_finite(spacing) || spacing < 0)
+ return;
+ if (qFuzzyCompare(d->cellSpacing.width(), spacing))
+ return;
+
+ d->cellSpacing.setWidth(spacing);
+ d->invalidateColumnRowPositions();
+ emit columnSpacingChanged();
+}
+
+QJSValue QQuickTableView::rowHeightProvider() const
+{
+ return d_func()->rowHeightProvider;
+}
+
+void QQuickTableView::setRowHeightProvider(QJSValue provider)
+{
+ Q_D(QQuickTableView);
+ if (provider.strictlyEquals(d->rowHeightProvider))
+ return;
+
+ d->rowHeightProvider = provider;
+ d->scheduleRebuildTable(QQuickTableViewPrivate::RebuildOption::ViewportOnly);
+ emit rowHeightProviderChanged();
+}
+
+QJSValue QQuickTableView::columnWidthProvider() const
+{
+ return d_func()->columnWidthProvider;
+}
+
+void QQuickTableView::setColumnWidthProvider(QJSValue provider)
+{
+ Q_D(QQuickTableView);
+ if (provider.strictlyEquals(d->columnWidthProvider))
+ return;
+
+ d->columnWidthProvider = provider;
+ d->scheduleRebuildTable(QQuickTableViewPrivate::RebuildOption::ViewportOnly);
+ emit columnWidthProviderChanged();
+}
+
+QVariant QQuickTableView::model() const
+{
+ return d_func()->assignedModel;
+}
+
+void QQuickTableView::setModel(const QVariant &newModel)
+{
+ Q_D(QQuickTableView);
+ if (newModel == d->assignedModel)
+ return;
+
+ d->assignedModel = newModel;
+ d->scheduleRebuildTable(QQuickTableViewPrivate::RebuildOption::All);
+ emit modelChanged();
+}
+
+QQmlComponent *QQuickTableView::delegate() const
+{
+ return d_func()->assignedDelegate;
+}
+
+void QQuickTableView::setDelegate(QQmlComponent *newDelegate)
+{
+ Q_D(QQuickTableView);
+ if (newDelegate == d->assignedDelegate)
+ return;
+
+ d->assignedDelegate = newDelegate;
+ d->scheduleRebuildTable(QQuickTableViewPrivate::RebuildOption::All);
+
+ emit delegateChanged();
+}
+
+bool QQuickTableView::reuseItems() const
+{
+ return bool(d_func()->reusableFlag == QQmlTableInstanceModel::Reusable);
+}
+
+void QQuickTableView::setReuseItems(bool reuse)
+{
+ Q_D(QQuickTableView);
+ if (reuseItems() == reuse)
+ return;
+
+ d->reusableFlag = reuse ? QQmlTableInstanceModel::Reusable : QQmlTableInstanceModel::NotReusable;
+
+ if (!reuse && d->tableModel) {
+ // When we're told to not reuse items, we
+ // immediately, as documented, drain the pool.
+ d->tableModel->drainReusableItemsPool(0);
+ }
+
+ emit reuseItemsChanged();
+}
+
+void QQuickTableView::setContentWidth(qreal width)
+{
+ Q_D(QQuickTableView);
+ d->explicitContentWidth = width;
+ QQuickFlickable::setContentWidth(width);
+}
+
+void QQuickTableView::setContentHeight(qreal height)
+{
+ Q_D(QQuickTableView);
+ d->explicitContentHeight = height;
+ QQuickFlickable::setContentHeight(height);
+}
+
+void QQuickTableView::forceLayout()
+{
+ Q_D(QQuickTableView);
+ d->columnRowPositionsInvalid = true;
+
+ if (d->polishing) {
+ qWarning() << "TableView::forceLayout(): Cannot do an immediate re-layout during an ongoing layout!";
+ polish();
+ return;
+ }
+
+ d->updatePolish();
+}
+
+QQuickTableViewAttached *QQuickTableView::qmlAttachedProperties(QObject *obj)
+{
+ return new QQuickTableViewAttached(obj);
+}
+
+void QQuickTableView::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
+{
+ Q_D(QQuickTableView);
+ QQuickFlickable::geometryChanged(newGeometry, oldGeometry);
+
+ if (d->tableModel) {
+ // When the view changes size, we force the pool to
+ // shrink by releasing all pooled items.
+ d->tableModel->drainReusableItemsPool(0);
+ }
+
+ polish();
+}
+
+void QQuickTableView::viewportMoved(Qt::Orientations orientation)
+{
+ Q_D(QQuickTableView);
+ QQuickFlickable::viewportMoved(orientation);
+
+ QQuickTableViewPrivate::RebuildOptions options = QQuickTableViewPrivate::RebuildOption::None;
+
+ // Check the viewport moved more than one page vertically
+ if (!d->viewportRect.intersects(QRectF(d->viewportRect.x(), contentY(), 1, height())))
+ options |= QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftRow;
+ // Check the viewport moved more than one page horizontally
+ if (!d->viewportRect.intersects(QRectF(contentX(), d->viewportRect.y(), width(), 1)))
+ options |= QQuickTableViewPrivate::RebuildOption::CalculateNewTopLeftColumn;
+
+ if (options) {
+ // When the viewport has moved more than one page vertically or horizontally, we switch
+ // strategy from refilling edges around the current table to instead rebuild the table
+ // from scratch inside the new viewport. This will greatly improve performance when flicking
+ // a long distance in one go, which can easily happen when dragging on scrollbars.
+ options |= QQuickTableViewPrivate::RebuildOption::ViewportOnly;
+ d->scheduleRebuildTable(options);
+ }
+
+ if (d->rebuildScheduled) {
+ // No reason to do anything, since we're about to rebuild the whole table anyway.
+ // Besides, calling updatePolish, which will start the rebuild, can easily cause
+ // binding loops to happen since we usually end up modifying the geometry of the
+ // viewport (contentItem) as well.
+ return;
+ }
+
+ // Calling polish() will schedule a polish event. But while the user is flicking, several
+ // mouse events will be handled before we get an updatePolish() call. And the updatePolish()
+ // call will only see the last mouse position. This results in a stuttering flick experience
+ // (especially on windows). We improve on this by calling updatePolish() directly. But this
+ // has the pitfall that we open up for recursive callbacks. E.g while inside updatePolish(), we
+ // load/unload items, and emit signals. The application can listen to those signals and set a
+ // new contentX/Y on the flickable. So we need to guard for this, to avoid unexpected behavior.
+ if (d->polishing)
+ polish();
+ else
+ d->updatePolish();
+}
+
+void QQuickTableViewPrivate::_q_componentFinalized()
+{
+ // Now that all bindings are evaluated, and we know
+ // our final geometery, we can build the table.
+ qCDebug(lcTableViewDelegateLifecycle);
+ updatePolish();
+}
+
+void QQuickTableViewPrivate::registerCallbackWhenBindingsAreEvaluated()
+{
+ // componentComplete() is called on us after all static values have been assigned, but
+ // before bindings to any anchestors has been evaluated. Especially this means that
+ // if our size is bound to the parents size, it will still be empty at that point.
+ // And we cannot build the table without knowing our own size. We could wait until we
+ // got the first updatePolish() callback, but at that time, any asynchronous loaders that we
+ // might be inside have already finished loading, which means that we would load all
+ // the delegate items synchronously instead of asynchronously. We therefore add a componentFinalized
+ // function that gets called after all the bindings we rely on has been evaluated.
+ // When receiving this call, we load the delegate items (and build the table).
+ Q_Q(QQuickTableView);
+ QQmlEnginePrivate *engPriv = QQmlEnginePrivate::get(qmlEngine(q));
+ static int finalizedIdx = -1;
+ if (finalizedIdx < 0)
+ finalizedIdx = q->metaObject()->indexOfSlot("_q_componentFinalized()");
+ engPriv->registerFinalizeCallback(q, finalizedIdx);
+}
+
+void QQuickTableView::componentComplete()
+{
+ QQuickFlickable::componentComplete();
+ d_func()->registerCallbackWhenBindingsAreEvaluated();
+}
+
+#include "moc_qquicktableview_p.cpp"
+
+QT_END_NAMESPACE
diff --git a/src/quick/items/qquicktableview_p.h b/src/quick/items/qquicktableview_p.h
new file mode 100644
index 0000000000..9fcd4c6c17
--- /dev/null
+++ b/src/quick/items/qquicktableview_p.h
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKTABLEVIEW_P_H
+#define QQUICKTABLEVIEW_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 <private/qtquickglobal_p.h>
+QT_REQUIRE_CONFIG(quick_tableview);
+
+#include <QtCore/qpointer.h>
+#include <QtQuick/private/qtquickglobal_p.h>
+#include <QtQuick/private/qquickflickable_p.h>
+#include <QtQml/private/qqmlnullablevalue_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QQuickTableViewAttached;
+class QQuickTableViewPrivate;
+
+class Q_QUICK_PRIVATE_EXPORT QQuickTableView : public QQuickFlickable
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int rows READ rows NOTIFY rowsChanged)
+ Q_PROPERTY(int columns READ columns NOTIFY columnsChanged)
+ Q_PROPERTY(qreal rowSpacing READ rowSpacing WRITE setRowSpacing NOTIFY rowSpacingChanged)
+ Q_PROPERTY(qreal columnSpacing READ columnSpacing WRITE setColumnSpacing NOTIFY columnSpacingChanged)
+ Q_PROPERTY(QJSValue rowHeightProvider READ rowHeightProvider WRITE setRowHeightProvider NOTIFY rowHeightProviderChanged)
+ Q_PROPERTY(QJSValue columnWidthProvider READ columnWidthProvider WRITE setColumnWidthProvider NOTIFY columnWidthProviderChanged)
+ Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged)
+ Q_PROPERTY(QQmlComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged)
+ Q_PROPERTY(bool reuseItems READ reuseItems WRITE setReuseItems NOTIFY reuseItemsChanged)
+ Q_PROPERTY(qreal contentWidth READ contentWidth WRITE setContentWidth NOTIFY contentWidthChanged)
+ Q_PROPERTY(qreal contentHeight READ contentHeight WRITE setContentWidth NOTIFY contentHeightChanged)
+
+public:
+ QQuickTableView(QQuickItem *parent = nullptr);
+
+ int rows() const;
+ int columns() const;
+
+ qreal rowSpacing() const;
+ void setRowSpacing(qreal spacing);
+
+ qreal columnSpacing() const;
+ void setColumnSpacing(qreal spacing);
+
+ QJSValue rowHeightProvider() const;
+ void setRowHeightProvider(QJSValue provider);
+
+ QJSValue columnWidthProvider() const;
+ void setColumnWidthProvider(QJSValue provider);
+
+ QVariant model() const;
+ void setModel(const QVariant &newModel);
+
+ QQmlComponent *delegate() const;
+ void setDelegate(QQmlComponent *);
+
+ bool reuseItems() const;
+ void setReuseItems(bool reuseItems);
+
+ void setContentWidth(qreal width);
+ void setContentHeight(qreal height);
+
+ Q_INVOKABLE void forceLayout();
+
+ static QQuickTableViewAttached *qmlAttachedProperties(QObject *);
+
+Q_SIGNALS:
+ void rowsChanged();
+ void columnsChanged();
+ void rowSpacingChanged();
+ void columnSpacingChanged();
+ void rowHeightProviderChanged();
+ void columnWidthProviderChanged();
+ void modelChanged();
+ void delegateChanged();
+ void reuseItemsChanged();
+
+protected:
+ void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) override;
+ void viewportMoved(Qt::Orientations orientation) override;
+ void componentComplete() override;
+
+private:
+ Q_DISABLE_COPY(QQuickTableView)
+ Q_DECLARE_PRIVATE(QQuickTableView)
+
+ Q_PRIVATE_SLOT(d_func(), void _q_componentFinalized())
+};
+
+class Q_QUICK_PRIVATE_EXPORT QQuickTableViewAttached : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QQuickTableView *view READ view NOTIFY viewChanged)
+
+public:
+ QQuickTableViewAttached(QObject *parent)
+ : QObject(parent) {}
+
+ QQuickTableView *view() const { return m_view; }
+ void setView(QQuickTableView *newTableView) {
+ if (newTableView == m_view)
+ return;
+ m_view = newTableView;
+ Q_EMIT viewChanged();
+ }
+
+Q_SIGNALS:
+ void viewChanged();
+ void pooled();
+ void reused();
+
+private:
+ QPointer<QQuickTableView> m_view;
+
+ friend class QQuickTableViewPrivate;
+};
+
+QT_END_NAMESPACE
+
+QML_DECLARE_TYPE(QQuickTableView)
+QML_DECLARE_TYPEINFO(QQuickTableView, QML_HAS_ATTACHED_PROPERTIES)
+
+#endif // QQUICKTABLEVIEW_P_H
diff --git a/src/quick/items/qquicktableview_p_p.h b/src/quick/items/qquicktableview_p_p.h
new file mode 100644
index 0000000000..2ed04f8d29
--- /dev/null
+++ b/src/quick/items/qquicktableview_p_p.h
@@ -0,0 +1,388 @@
+/****************************************************************************
+**
+** Copyright (C) 2018 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the QtQuick 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 QQUICKTABLEVIEW_P_P_H
+#define QQUICKTABLEVIEW_P_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 "qquicktableview_p.h"
+
+#include <QtCore/qtimer.h>
+#include <QtQml/private/qqmltableinstancemodel_p.h>
+#include <QtQml/private/qqmlincubator_p.h>
+#include <QtQml/private/qqmlchangeset_p.h>
+#include <QtQml/qqmlinfo.h>
+
+#include <QtQuick/private/qquickflickable_p_p.h>
+#include <QtQuick/private/qquickitemviewfxitem_p_p.h>
+
+QT_BEGIN_NAMESPACE
+
+Q_DECLARE_LOGGING_CATEGORY(lcTableViewDelegateLifecycle)
+
+static const qreal kDefaultRowHeight = 50;
+static const qreal kDefaultColumnWidth = 50;
+
+class FxTableItem;
+
+class Q_QML_AUTOTEST_EXPORT QQuickTableViewPrivate : public QQuickFlickablePrivate
+{
+ Q_DECLARE_PUBLIC(QQuickTableView)
+
+public:
+ class TableEdgeLoadRequest
+ {
+ // Whenever we need to load new rows or columns in the
+ // table, we fill out a TableEdgeLoadRequest.
+ // TableEdgeLoadRequest is just a struct that keeps track
+ // of which cells that needs to be loaded, and which cell
+ // the table is currently loading. The loading itself is
+ // done by QQuickTableView.
+
+ public:
+ void begin(const QPoint &cell, const QPointF &pos, QQmlIncubator::IncubationMode incubationMode)
+ {
+ Q_ASSERT(!active);
+ active = true;
+ tableEdge = Qt::Edge(0);
+ tableCells = QLine(cell, cell);
+ mode = incubationMode;
+ cellCount = 1;
+ currentIndex = 0;
+ startPos = pos;
+ qCDebug(lcTableViewDelegateLifecycle()) << "begin top-left:" << toString();
+ }
+
+ void begin(const QLine cellsToLoad, Qt::Edge edgeToLoad, QQmlIncubator::IncubationMode incubationMode)
+ {
+ Q_ASSERT(!active);
+ active = true;
+ tableEdge = edgeToLoad;
+ tableCells = cellsToLoad;
+ mode = incubationMode;
+ cellCount = tableCells.x2() - tableCells.x1() + tableCells.y2() - tableCells.y1() + 1;
+ currentIndex = 0;
+ qCDebug(lcTableViewDelegateLifecycle()) << "begin:" << toString();
+ }
+
+ inline void markAsDone() { active = false; }
+ inline bool isActive() { return active; }
+
+ inline QPoint firstCell() { return tableCells.p1(); }
+ inline QPoint lastCell() { return tableCells.p2(); }
+ inline QPoint currentCell() { return cellAt(currentIndex); }
+ inline QPoint previousCell() { return cellAt(currentIndex - 1); }
+
+ inline bool atBeginning() { return currentIndex == 0; }
+ inline bool hasCurrentCell() { return currentIndex < cellCount; }
+ inline void moveToNextCell() { ++currentIndex; }
+
+ inline Qt::Edge edge() { return tableEdge; }
+ inline QQmlIncubator::IncubationMode incubationMode() { return mode; }
+
+ inline QPointF startPosition() { return startPos; }
+
+ QString toString()
+ {
+ QString str;
+ QDebug dbg(&str);
+ dbg.nospace() << "TableSectionLoadRequest(" << "edge:"
+ << tableEdge << " cells:" << tableCells << " incubation:";
+
+ switch (mode) {
+ case QQmlIncubator::Asynchronous:
+ dbg << "Asynchronous";
+ break;
+ case QQmlIncubator::AsynchronousIfNested:
+ dbg << "AsynchronousIfNested";
+ break;
+ case QQmlIncubator::Synchronous:
+ dbg << "Synchronous";
+ break;
+ }
+
+ return str;
+ }
+
+ private:
+ Qt::Edge tableEdge = Qt::Edge(0);
+ QLine tableCells;
+ int currentIndex = 0;
+ int cellCount = 0;
+ bool active = false;
+ QQmlIncubator::IncubationMode mode = QQmlIncubator::AsynchronousIfNested;
+ QPointF startPos;
+
+ QPoint cellAt(int index)
+ {
+ int x = tableCells.p1().x() + (tableCells.dx() ? index : 0);
+ int y = tableCells.p1().y() + (tableCells.dy() ? index : 0);
+ return QPoint(x, y);
+ }
+ };
+
+ enum class RebuildState {
+ Begin = 0,
+ LoadInitalTable,
+ VerifyTable,
+ LayoutTable,
+ LoadAndUnloadAfterLayout,
+ PreloadColumns,
+ PreloadRows,
+ MovePreloadedItemsToPool,
+ Done
+ };
+
+ enum class RebuildOption {
+ None = 0,
+ ViewportOnly = 0x1,
+ CalculateNewTopLeftRow = 0x2,
+ CalculateNewTopLeftColumn = 0x4,
+ All = 0x8,
+ };
+ Q_DECLARE_FLAGS(RebuildOptions, RebuildOption)
+
+public:
+ QQuickTableViewPrivate();
+ ~QQuickTableViewPrivate() override;
+
+ static inline QQuickTableViewPrivate *get(QQuickTableView *q) { return q->d_func(); }
+
+ void updatePolish() override;
+ void fixup(AxisData &data, qreal minExtent, qreal maxExtent) override;
+
+public:
+ QHash<int, FxTableItem *> loadedItems;
+
+ // model, tableModel and modelVariant all point to the same model. modelVariant
+ // is the model assigned by the user. And tableModel is the wrapper model we create
+ // around it. But if the model is an instance model directly, we cannot wrap it, so
+ // we need a pointer for that case as well.
+ QQmlInstanceModel* model = nullptr;
+ QPointer<QQmlTableInstanceModel> tableModel = nullptr;
+ QVariant modelVariant;
+
+ // When the applications assignes a new model or delegate to the view, we keep them
+ // around until we're ready to take them into use (syncWithPendingChanges).
+ QVariant assignedModel = QVariant(int(0));
+ QQmlComponent *assignedDelegate = nullptr;
+
+ // loadedTable describes the table cells that are currently loaded (from top left
+ // row/column to bottom right row/column). loadedTableOuterRect describes the actual
+ // pixels that those cells cover, and is matched agains the viewport to determine when
+ // we need to fill up with more rows/columns. loadedTableInnerRect describes the pixels
+ // that the loaded table covers if you remove one row/column on each side of the table, and
+ // is used to determine rows/columns that are no longer visible and can be unloaded.
+ QRect loadedTable;
+ QRectF loadedTableOuterRect;
+ QRectF loadedTableInnerRect;
+
+ QRectF viewportRect = QRectF(0, 0, -1, -1);
+
+ QSize tableSize;
+
+ RebuildState rebuildState = RebuildState::Done;
+ RebuildOptions rebuildOptions = RebuildOption::All;
+ RebuildOptions scheduledRebuildOptions = RebuildOption::All;
+
+ TableEdgeLoadRequest loadRequest;
+
+ QPoint contentSizeBenchMarkPoint = QPoint(-1, -1);
+ QSizeF cellSpacing = QSizeF(0, 0);
+
+ QQmlTableInstanceModel::ReusableFlag reusableFlag = QQmlTableInstanceModel::Reusable;
+
+ bool blockItemCreatedCallback = false;
+ bool columnRowPositionsInvalid = false;
+ bool layoutWarningIssued = false;
+ bool polishing = false;
+ bool rebuildScheduled = true;
+
+ QJSValue rowHeightProvider;
+ QJSValue columnWidthProvider;
+
+ // TableView uses contentWidth/height to report the size of the table (this
+ // will e.g make scrollbars written for Flickable work out of the box). This
+ // value is continuously calculated, and will change/improve as more columns
+ // are loaded into view. At the same time, we want to open up for the
+ // possibility that the application can set the content width explicitly, in
+ // case it knows what the exact width should be from the start. We therefore
+ // override the contentWidth/height properties from QQuickFlickable, to be able
+ // to implement this combined behavior. This also lets us lazy build the table
+ // if the application needs to know the content size early on.
+ QQmlNullableValue<qreal> explicitContentWidth;
+ QQmlNullableValue<qreal> explicitContentHeight;
+
+ QSizeF averageEdgeSize;
+
+ const static QPoint kLeft;
+ const static QPoint kRight;
+ const static QPoint kUp;
+ const static QPoint kDown;
+
+#ifdef QT_DEBUG
+ QString forcedIncubationMode = qEnvironmentVariable("QT_TABLEVIEW_INCUBATION_MODE");
+#endif
+
+public:
+ QQuickTableViewAttached *getAttachedObject(const QObject *object) const;
+
+ int modelIndexAtCell(const QPoint &cell) const;
+ QPoint cellAtModelIndex(int modelIndex) const;
+
+ qreal sizeHintForColumn(int column);
+ qreal sizeHintForRow(int row);
+ void calculateTableSize();
+
+ qreal resolveColumnWidth(int column);
+ qreal resolveRowHeight(int row);
+
+ void relayoutTable();
+ void relayoutTableItems();
+
+ void layoutVerticalEdge(Qt::Edge tableEdge);
+ void layoutHorizontalEdge(Qt::Edge tableEdge);
+ void layoutTopLeftItem();
+ void layoutTableEdgeFromLoadRequest();
+
+ void updateContentWidth();
+ void updateContentHeight();
+ void updateAverageEdgeSize();
+
+ void enforceTableAtOrigin();
+ void syncLoadedTableRectFromLoadedTable();
+ void syncLoadedTableFromLoadRequest();
+
+ bool canLoadTableEdge(Qt::Edge tableEdge, const QRectF fillRect) const;
+ bool canUnloadTableEdge(Qt::Edge tableEdge, const QRectF fillRect) const;
+ Qt::Edge nextEdgeToLoad(const QRectF rect);
+ Qt::Edge nextEdgeToUnload(const QRectF rect);
+
+ qreal cellWidth(const QPoint &cell);
+ qreal cellHeight(const QPoint &cell);
+
+ FxTableItem *loadedTableItem(const QPoint &cell) const;
+ FxTableItem *itemNextTo(const FxTableItem *fxTableItem, const QPoint &direction) const;
+ FxTableItem *createFxTableItem(const QPoint &cell, QQmlIncubator::IncubationMode incubationMode);
+ FxTableItem *loadFxTableItem(const QPoint &cell, QQmlIncubator::IncubationMode incubationMode);
+
+ void releaseItem(FxTableItem *fxTableItem, QQmlTableInstanceModel::ReusableFlag reusableFlag);
+ void releaseLoadedItems(QQmlTableInstanceModel::ReusableFlag reusableFlag);
+
+ void unloadItem(const QPoint &cell);
+ void unloadItems(const QLine &items);
+
+ void loadInitialTopLeftItem(const QPoint &cell, const QPointF &pos);
+ void loadEdge(Qt::Edge edge, QQmlIncubator::IncubationMode incubationMode);
+ void unloadEdge(Qt::Edge edge);
+ void loadAndUnloadVisibleEdges();
+ void drainReusePoolAfterLoadRequest();
+ void cancelLoadRequest();
+ void processLoadRequest();
+
+ void processRebuildTable();
+ bool moveToNextRebuildState();
+ void beginRebuildTable();
+ void layoutAfterLoadingInitialTable();
+
+ void scheduleRebuildTable(QQuickTableViewPrivate::RebuildOptions options);
+ void invalidateColumnRowPositions();
+
+ void createWrapperModel();
+
+ void initItemCallback(int modelIndex, QObject *item);
+ void itemCreatedCallback(int modelIndex, QObject *object);
+ void itemPooledCallback(int modelIndex, QObject *object);
+ void itemReusedCallback(int modelIndex, QObject *object);
+ void modelUpdated(const QQmlChangeSet &changeSet, bool reset);
+
+ inline void syncWithPendingChanges();
+ inline void syncDelegate();
+ inline void syncModel();
+ inline void syncRebuildOptions();
+
+ void connectToModel();
+ void disconnectFromModel();
+
+ void rowsMovedCallback(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row);
+ void columnsMovedCallback(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int column);
+ void rowsInsertedCallback(const QModelIndex &parent, int begin, int end);
+ void rowsRemovedCallback(const QModelIndex &parent, int begin, int end);
+ void columnsInsertedCallback(const QModelIndex &parent, int begin, int end);
+ void columnsRemovedCallback(const QModelIndex &parent, int begin, int end);
+ void layoutChangedCallback(const QList<QPersistentModelIndex> &parents, QAbstractItemModel::LayoutChangeHint hint);
+ void modelResetCallback();
+
+ void _q_componentFinalized();
+ void registerCallbackWhenBindingsAreEvaluated();
+
+ inline QString tableLayoutToString() const;
+ void dumpTable() const;
+};
+
+class FxTableItem : public QQuickItemViewFxItem
+{
+public:
+ FxTableItem(QQuickItem *item, QQuickTableView *table, bool own)
+ : QQuickItemViewFxItem(item, own, QQuickTableViewPrivate::get(table))
+ {
+ }
+
+ qreal position() const override { return 0; }
+ qreal endPosition() const override { return 0; }
+ qreal size() const override { return 0; }
+ qreal sectionSize() const override { return 0; }
+ bool contains(qreal, qreal) const override { return false; }
+
+ QPoint cell;
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/quick/items/qquicktext.cpp b/src/quick/items/qquicktext.cpp
index 76720e5c5d..3cce30aaf6 100644
--- a/src/quick/items/qquicktext.cpp
+++ b/src/quick/items/qquicktext.cpp
@@ -88,6 +88,7 @@ QQuickTextPrivate::QQuickTextPrivate()
, truncated(false), hAlignImplicit(true), rightToLeftText(false)
, layoutTextElided(false), textHasChanged(true), needToUpdateLayout(false), formatModifiesFontSize(false)
, polishSize(false)
+ , updateSizeRecursionGuard(false)
{
implicitAntialiasing = true;
}
@@ -442,6 +443,7 @@ void QQuickTextPrivate::updateSize()
//### need to confirm cost of always setting these for richText
internalWidthUpdate = true;
+ qreal oldWidth = q->width();
qreal iWidth = -1;
if (!q->widthValid())
iWidth = size.width();
@@ -449,30 +451,45 @@ void QQuickTextPrivate::updateSize()
q->setImplicitSize(iWidth + hPadding, size.height() + vPadding);
internalWidthUpdate = false;
- if (iWidth == -1)
- q->setImplicitHeight(size.height() + vPadding);
-
- QTextBlock firstBlock = extra->doc->firstBlock();
- while (firstBlock.layout()->lineCount() == 0)
- firstBlock = firstBlock.next();
-
- QTextBlock lastBlock = extra->doc->lastBlock();
- while (lastBlock.layout()->lineCount() == 0)
- lastBlock = lastBlock.previous();
-
- if (firstBlock.lineCount() > 0 && lastBlock.lineCount() > 0) {
- QTextLine firstLine = firstBlock.layout()->lineAt(0);
- QTextLine lastLine = lastBlock.layout()->lineAt(lastBlock.layout()->lineCount() - 1);
- advance = QSizeF(lastLine.horizontalAdvance(),
- (lastLine.y() + lastBlock.layout()->position().y()) - (firstLine.y() + firstBlock.layout()->position().y()));
+ // If the implicit width update caused a recursive change of the width,
+ // we will have skipped integral parts of the layout due to the
+ // internalWidthUpdate recursion guard. To make sure everything is up
+ // to date, we need to run a second pass over the layout when updateSize()
+ // is done.
+ if (!qFuzzyCompare(q->width(), oldWidth) && !updateSizeRecursionGuard) {
+ updateSizeRecursionGuard = true;
+ updateSize();
+ updateSizeRecursionGuard = false;
} else {
- advance = QSizeF();
+ if (iWidth == -1)
+ q->setImplicitHeight(size.height() + vPadding);
+
+ QTextBlock firstBlock = extra->doc->firstBlock();
+ while (firstBlock.layout()->lineCount() == 0)
+ firstBlock = firstBlock.next();
+
+ QTextBlock lastBlock = extra->doc->lastBlock();
+ while (lastBlock.layout()->lineCount() == 0)
+ lastBlock = lastBlock.previous();
+
+ if (firstBlock.lineCount() > 0 && lastBlock.lineCount() > 0) {
+ QTextLine firstLine = firstBlock.layout()->lineAt(0);
+ QTextLine lastLine = lastBlock.layout()->lineAt(lastBlock.layout()->lineCount() - 1);
+ advance = QSizeF(lastLine.horizontalAdvance(),
+ (lastLine.y() + lastBlock.layout()->position().y()) - (firstLine.y() + firstBlock.layout()->position().y()));
+ } else {
+ advance = QSizeF();
+ }
}
}
if (layedOutTextRect.size() != previousSize)
emit q->contentSizeChanged();
+ if (layedOutTextRect.width() != previousSize.width())
+ emit q->contentWidthChanged(layedOutTextRect.width());
+ if (layedOutTextRect.height() != previousSize.height())
+ emit q->contentHeightChanged(layedOutTextRect.height());
updateType = UpdatePaintNode;
q->update();
}
diff --git a/src/quick/items/qquicktext_p.h b/src/quick/items/qquicktext_p.h
index 15e989c13d..1af60051fb 100644
--- a/src/quick/items/qquicktext_p.h
+++ b/src/quick/items/qquicktext_p.h
@@ -79,10 +79,10 @@ class Q_QUICK_PRIVATE_EXPORT QQuickText : public QQuickImplicitSizeItem
Q_PROPERTY(TextFormat textFormat READ textFormat WRITE setTextFormat NOTIFY textFormatChanged)
Q_PROPERTY(TextElideMode elide READ elideMode WRITE setElideMode NOTIFY elideModeChanged) //### elideMode?
- Q_PROPERTY(qreal contentWidth READ contentWidth NOTIFY contentSizeChanged)
- Q_PROPERTY(qreal contentHeight READ contentHeight NOTIFY contentSizeChanged)
- Q_PROPERTY(qreal paintedWidth READ contentWidth NOTIFY contentSizeChanged) // Compatibility
- Q_PROPERTY(qreal paintedHeight READ contentHeight NOTIFY contentSizeChanged)
+ Q_PROPERTY(qreal contentWidth READ contentWidth NOTIFY contentWidthChanged)
+ Q_PROPERTY(qreal contentHeight READ contentHeight NOTIFY contentHeightChanged)
+ Q_PROPERTY(qreal paintedWidth READ contentWidth NOTIFY contentWidthChanged) // Compatibility
+ Q_PROPERTY(qreal paintedHeight READ contentHeight NOTIFY contentHeightChanged)
Q_PROPERTY(qreal lineHeight READ lineHeight WRITE setLineHeight NOTIFY lineHeightChanged)
Q_PROPERTY(LineHeightMode lineHeightMode READ lineHeightMode WRITE setLineHeightMode NOTIFY lineHeightModeChanged)
Q_PROPERTY(QUrl baseUrl READ baseUrl WRITE setBaseUrl RESET resetBaseUrl NOTIFY baseUrlChanged)
@@ -272,6 +272,10 @@ Q_SIGNALS:
void textFormatChanged(QQuickText::TextFormat textFormat);
void elideModeChanged(QQuickText::TextElideMode mode);
void contentSizeChanged();
+ // The next two signals should be marked as Q_REVISION(12). See QTBUG-71247
+ void contentWidthChanged(qreal contentWidth);
+ void contentHeightChanged(qreal contentHeight);
+
void lineHeightChanged(qreal lineHeight);
void lineHeightModeChanged(LineHeightMode mode);
void fontSizeModeChanged();
diff --git a/src/quick/items/qquicktext_p_p.h b/src/quick/items/qquicktext_p_p.h
index b0b1492d57..fd26d966c8 100644
--- a/src/quick/items/qquicktext_p_p.h
+++ b/src/quick/items/qquicktext_p_p.h
@@ -174,6 +174,7 @@ public:
bool needToUpdateLayout:1;
bool formatModifiesFontSize:1;
bool polishSize:1; // Workaround for problem with polish called after updateSize (QTBUG-42636)
+ bool updateSizeRecursionGuard:1;
static const QChar elideChar;
diff --git a/src/quick/items/qquickwindow.cpp b/src/quick/items/qquickwindow.cpp
index 53c0231f87..4f14eedd39 100644
--- a/src/quick/items/qquickwindow.cpp
+++ b/src/quick/items/qquickwindow.cpp
@@ -46,6 +46,7 @@
#include "qquickevents_p_p.h"
#include <private/qquickdrag_p.h>
+#include <private/qquickhoverhandler_p.h>
#include <private/qquickpointerhandler_p.h>
#include <QtQuick/private/qsgrenderer_p.h>
@@ -88,6 +89,8 @@ Q_LOGGING_CATEGORY(DBG_TOUCH, "qt.quick.touch")
Q_LOGGING_CATEGORY(DBG_TOUCH_TARGET, "qt.quick.touch.target")
Q_LOGGING_CATEGORY(DBG_MOUSE, "qt.quick.mouse")
Q_LOGGING_CATEGORY(DBG_MOUSE_TARGET, "qt.quick.mouse.target")
+Q_LOGGING_CATEGORY(lcWheelTarget, "qt.quick.wheel.target")
+Q_LOGGING_CATEGORY(lcGestureTarget, "qt.quick.gesture.target")
Q_LOGGING_CATEGORY(DBG_HOVER_TRACE, "qt.quick.hover.trace")
Q_LOGGING_CATEGORY(DBG_FOCUS, "qt.quick.focus")
Q_LOGGING_CATEGORY(DBG_DIRTY, "qt.quick.dirty")
@@ -256,14 +259,16 @@ void QQuickWindow::hideEvent(QHideEvent *)
void QQuickWindow::focusOutEvent(QFocusEvent *ev)
{
Q_D(QQuickWindow);
- d->contentItem->setFocus(false, ev->reason());
+ if (d->contentItem)
+ d->contentItem->setFocus(false, ev->reason());
}
/*! \reimp */
void QQuickWindow::focusInEvent(QFocusEvent *ev)
{
Q_D(QQuickWindow);
- d->contentItem->setFocus(true, ev->reason());
+ if (d->contentItem)
+ d->contentItem->setFocus(true, ev->reason());
d->updateFocusItemTransform();
}
@@ -610,6 +615,7 @@ QQmlListProperty<QObject> QQuickWindowPrivate::data()
static QMouseEvent *touchToMouseEvent(QEvent::Type type, const QTouchEvent::TouchPoint &p, QTouchEvent *event, QQuickItem *item, bool transformNeeded = true)
{
+ Q_ASSERT(QCoreApplication::testAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents));
// The touch point local position and velocity are not yet transformed.
QMouseEvent *me = new QMouseEvent(type, transformNeeded ? item->mapFromScene(p.scenePos()) : p.pos(), p.scenePos(), p.screenPos(),
Qt::LeftButton, (type == QEvent::MouseButtonRelease ? Qt::NoButton : Qt::LeftButton), event->modifiers());
@@ -651,6 +657,7 @@ bool QQuickWindowPrivate::checkIfDoubleClicked(ulong newPressEventTimestamp)
bool QQuickWindowPrivate::deliverTouchAsMouse(QQuickItem *item, QQuickPointerEvent *pointerEvent)
{
+ Q_ASSERT(QCoreApplication::testAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents));
Q_Q(QQuickWindow);
auto device = pointerEvent->device();
@@ -767,6 +774,7 @@ bool QQuickWindowPrivate::deliverTouchAsMouse(QQuickItem *item, QQuickPointerEve
void QQuickWindowPrivate::grabTouchPoints(QObject *grabber, const QVector<int> &ids)
{
+ QQuickPointerEvent *ev = nullptr;
for (int i = 0; i < ids.count(); ++i) {
int id = ids.at(i);
if (Q_UNLIKELY(id < 0)) {
@@ -786,15 +794,26 @@ void QQuickWindowPrivate::grabTouchPoints(QObject *grabber, const QVector<int> &
qCDebug(DBG_MOUSE_TARGET) << "grabTouchPoints: mouse grabber changed due to grabTouchPoints:" << touchMouseGrabber << "-> null";
}
+ // optimization to avoid the loop over devices below:
+ // all ids are probably from the same event, so we don't have to search
+ if (ev) {
+ auto point = ev->pointById(id);
+ if (point && point->exclusiveGrabber() != grabber) {
+ point->setExclusiveGrabber(grabber);
+ continue; // next id in the ids loop
+ }
+ }
+ // search all devices for a QQuickPointerEvent instance that is delivering the point with id
const auto touchDevices = QQuickPointerDevice::touchDevices();
for (auto device : touchDevices) {
- auto point = pointerEventInstance(device)->pointById(id);
- if (!point)
- continue;
- QObject *oldGrabber = point->exclusiveGrabber();
- if (oldGrabber == grabber)
- continue;
- point->setExclusiveGrabber(grabber);
+ QQuickPointerEvent *pev = pointerEventInstance(device);
+ auto point = pev->pointById(id);
+ if (point) {
+ ev = pev;
+ if (point->exclusiveGrabber() != grabber)
+ point->setExclusiveGrabber(grabber);
+ break; // out of touchDevices loop
+ }
}
}
}
@@ -1315,7 +1334,9 @@ QQuickWindow::~QQuickWindow()
#if QT_CONFIG(draganddrop)
delete d->dragGrabber; d->dragGrabber = nullptr;
#endif
- delete d->contentItem; d->contentItem = nullptr;
+ QQuickRootItem *root = d->contentItem;
+ d->contentItem = nullptr;
+ delete root;
qDeleteAll(d->pointerEventInstances);
d->pointerEventInstances.clear();
@@ -1540,8 +1561,20 @@ bool QQuickWindowPrivate::clearHover(ulong timestamp)
QPointF pos = q->mapFromGlobal(QGuiApplicationPrivate::lastCursorPosition.toPoint());
bool accepted = false;
- for (QQuickItem* item : qAsConst(hoverItems))
+ for (QQuickItem* item : qAsConst(hoverItems)) {
accepted = sendHoverEvent(QEvent::HoverLeave, item, pos, pos, QGuiApplication::keyboardModifiers(), timestamp, true) || accepted;
+ QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
+ if (itemPrivate->hasPointerHandlers()) {
+ pos = q->mapFromGlobal(QCursor::pos());
+ QQuickPointerEvent *pointerEvent = pointerEventInstance(QQuickPointerDevice::genericMouseDevice(), QEvent::MouseMove);
+ pointerEvent->point(0)->reset(Qt::TouchPointMoved, pos, quint64(1) << 24 /* mouse has device ID 1 */, timestamp, QVector2D());
+ pointerEvent->point(0)->setAccepted(true);
+ pointerEvent->localize(item);
+ for (QQuickPointerHandler *h : itemPrivate->extra->pointerHandlers)
+ if (QQuickHoverHandler *hh = qmlobject_cast<QQuickHoverHandler *>(h))
+ hh->handlePointerEvent(pointerEvent);
+ }
+ }
hoverItems.clear();
return accepted;
}
@@ -1571,6 +1604,8 @@ bool QQuickWindow::event(QEvent *e)
return d->deliverTouchCancelEvent(static_cast<QTouchEvent*>(e));
break;
case QEvent::Enter: {
+ if (!d->contentItem)
+ return false;
QEnterEvent *enter = static_cast<QEnterEvent*>(e);
bool accepted = enter->isAccepted();
bool delivered = d->deliverHoverEvent(d->contentItem, enter->windowPos(), d->lastMousePosition,
@@ -1592,7 +1627,8 @@ bool QQuickWindow::event(QEvent *e)
break;
#endif
case QEvent::WindowDeactivate:
- contentItem()->windowDeactivateEvent();
+ if (d->contentItem)
+ d->contentItem->windowDeactivateEvent();
break;
case QEvent::Close: {
// TOOD Qt 6 (binary incompatible)
@@ -1617,7 +1653,7 @@ bool QQuickWindow::event(QEvent *e)
}
#if QT_CONFIG(gestures)
case QEvent::NativeGesture:
- d->deliverNativeGestureEvent(d->contentItem, static_cast<QNativeGestureEvent*>(e));
+ d->deliverSinglePointEventUntilAccepted(d->pointerEventInstance(e));
break;
#endif
case QEvent::ShortcutOverride:
@@ -1684,6 +1720,7 @@ void QQuickWindowPrivate::deliverToPassiveGrabbers(const QVector<QPointer <QQuic
{
const QVector<QQuickPointerHandler *> &eventDeliveryTargets = pointerEvent->device()->eventDeliveryTargets();
QVarLengthArray<QPair<QQuickItem *, bool>, 4> sendFilteredPointerEventResult;
+ hasFiltered.clear();
for (auto handler : passiveGrabbers) {
// a null pointer in passiveGrabbers is unlikely, unless the grabbing handler was deleted dynamically
if (Q_LIKELY(handler) && !eventDeliveryTargets.contains(handler)) {
@@ -1723,6 +1760,7 @@ void QQuickWindowPrivate::deliverMouseEvent(QQuickPointerMouseEvent *pointerEven
if (grabberItem) {
bool handled = false;
+ hasFiltered.clear();
if (sendFilteredPointerEvent(pointerEvent, grabberItem))
handled = true;
// if the grabber is an Item:
@@ -1747,8 +1785,10 @@ void QQuickWindowPrivate::deliverMouseEvent(QQuickPointerMouseEvent *pointerEven
// release event: ungrab if no buttons are pressed anymore
if (mouseIsReleased)
removeGrabber(grabberItem, true, isDeliveringTouchAsMouse());
- } else if (auto handler = point->grabberPointerHandler()) {
+ deliverToPassiveGrabbers(point->passiveGrabbers(), pointerEvent);
+ } else if (auto handler = point->grabberPointerHandler()) {
pointerEvent->localize(handler->parentItem());
+ hasFiltered.clear();
if (!sendFilteredPointerEvent(pointerEvent, handler->parentItem()))
handler->handlePointerEvent(pointerEvent);
if (mouseIsReleased)
@@ -1767,12 +1807,13 @@ void QQuickWindowPrivate::deliverMouseEvent(QQuickPointerMouseEvent *pointerEven
// If some points weren't grabbed, deliver to non-grabber PointerHandlers in reverse paint order
if (!pointerEvent->allPointsGrabbed() && pointerEvent->buttons()) {
- QVector<QQuickItem *> targetItems = pointerTargets(contentItem, point->scenePosition(), false, false);
+ QVector<QQuickItem *> targetItems = pointerTargets(contentItem, point, false, false);
for (QQuickItem *item : targetItems) {
QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
if (!itemPrivate->extra.isAllocated() || itemPrivate->extra->pointerHandlers.isEmpty())
continue;
pointerEvent->localize(item);
+ hasFiltered.clear();
if (!sendFilteredPointerEvent(pointerEvent, item)) {
if (itemPrivate->handlePointerEvent(pointerEvent, true)) // avoid re-delivering to grabbers
delivered = true;
@@ -1834,6 +1875,16 @@ bool QQuickWindowPrivate::deliverHoverEvent(QQuickItem *item, const QPointF &sce
}
}
+ if (itemPrivate->hasPointerHandlers()) {
+ QQuickPointerEvent *pointerEvent = pointerEventInstance(QQuickPointerDevice::genericMouseDevice(), QEvent::MouseMove);
+ pointerEvent->point(0)->reset(Qt::TouchPointMoved, scenePos, quint64(1) << 24 /* mouse has device ID 1 */, timestamp, QVector2D());
+ pointerEvent->point(0)->setAccepted(true);
+ pointerEvent->localize(item);
+ for (QQuickPointerHandler *h : itemPrivate->extra->pointerHandlers)
+ if (QQuickHoverHandler *hh = qmlobject_cast<QQuickHoverHandler *>(h))
+ hh->handlePointerEvent(pointerEvent);
+ }
+
if (itemPrivate->hoverEnabled) {
QPointF p = item->mapFromScene(scenePos);
if (item->contains(p)) {
@@ -1886,43 +1937,57 @@ bool QQuickWindowPrivate::deliverHoverEvent(QQuickItem *item, const QPointF &sce
return false;
}
-#if QT_CONFIG(wheelevent)
-bool QQuickWindowPrivate::deliverWheelEvent(QQuickItem *item, QWheelEvent *event)
+// Simple delivery of non-mouse, non-touch Pointer Events: visit the items and handlers
+// in the usual reverse-paint-order until propagation is stopped
+bool QQuickWindowPrivate::deliverSinglePointEventUntilAccepted(QQuickPointerEvent *event)
{
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
+ Q_ASSERT(event->pointCount() == 1);
+ QQuickEventPoint *point = event->point(0);
+ QVector<QQuickItem *> targetItems = pointerTargets(contentItem, point, false, false);
- if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
- QPointF p = item->mapFromScene(event->posF());
- if (!item->contains(p))
- return false;
- }
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled() || QQuickItemPrivate::get(child)->culled)
- continue;
- if (deliverWheelEvent(child, event))
- return true;
- }
-
- QPointF p = item->mapFromScene(event->posF());
-
- if (item->contains(p)) {
- QWheelEvent wheel(p, event->globalPosF(), event->pixelDelta(), event->angleDelta(), event->delta(),
- event->orientation(), event->buttons(), event->modifiers(), event->phase(), event->source(), event->inverted());
- wheel.setTimestamp(event->timestamp());
- wheel.accept();
- QCoreApplication::sendEvent(item, &wheel);
- if (wheel.isAccepted()) {
- event->accept();
+ for (QQuickItem *item : targetItems) {
+ QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
+ event->localize(item);
+ // Let Pointer Handlers have the first shot
+ itemPrivate->handlePointerEvent(event);
+ if (point->isAccepted())
return true;
+ QPointF g = item->window()->mapToGlobal(point->scenePosition().toPoint());
+#if QT_CONFIG(wheelevent)
+ // Let the Item have a chance to handle it
+ if (QQuickPointerScrollEvent *pse = event->asPointerScrollEvent()) {
+ QWheelEvent wheel(point->position(), g, pse->pixelDelta().toPoint(), pse->angleDelta().toPoint(),
+ pse->buttons(), pse->modifiers(), pse->phase(),
+ pse->isInverted(), pse->synthSource());
+ wheel.setTimestamp(pse->timestamp());
+ wheel.accept();
+ QCoreApplication::sendEvent(item, &wheel);
+ if (wheel.isAccepted()) {
+ qCDebug(lcWheelTarget) << &wheel << "->" << item;
+ event->setAccepted(true);
+ return true;
+ }
+ }
+#endif
+#if QT_CONFIG(gestures)
+ if (QQuickPointerNativeGestureEvent *pnge = event->asPointerNativeGestureEvent()) {
+ QNativeGestureEvent nge(pnge->type(), pnge->device()->qTouchDevice(), point->position(), point->scenePosition(), g,
+ pnge->value(), 0L, 0L); // TODO can't copy things I can't access
+ nge.accept();
+ QCoreApplication::sendEvent(item, &nge);
+ if (nge.isAccepted()) {
+ qCDebug(lcGestureTarget) << &nge << "->" << item;
+ event->setAccepted(true);
+ return true;
+ }
}
+#endif // gestures
}
- return false;
+ return false; // it wasn't handled
}
+#if QT_CONFIG(wheelevent)
/*! \reimp */
void QQuickWindow::wheelEvent(QWheelEvent *event)
{
@@ -1937,55 +2002,11 @@ void QQuickWindow::wheelEvent(QWheelEvent *event)
return;
event->ignore();
- d->deliverWheelEvent(d->contentItem, event);
+ d->deliverPointerEvent(d->pointerEventInstance(event));
d->lastWheelEventAccepted = event->isAccepted();
}
#endif // wheelevent
-#if QT_CONFIG(gestures)
-bool QQuickWindowPrivate::deliverNativeGestureEvent(QQuickItem *item, QNativeGestureEvent *event)
-{
- QQuickItemPrivate *itemPrivate = QQuickItemPrivate::get(item);
-
- QPointF p = item->mapFromScene(event->windowPos());
- if ((itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) && !item->contains(p))
- return false;
-
- QList<QQuickItem *> children = itemPrivate->paintOrderChildItems();
- for (int ii = children.count() - 1; ii >= 0; --ii) {
- QQuickItem *child = children.at(ii);
- if (!child->isVisible() || !child->isEnabled() || QQuickItemPrivate::get(child)->culled)
- continue;
- if (deliverNativeGestureEvent(child, event))
- return true;
- }
-
- // Try the Item's pointer handlers first
- QQuickPointerEvent *pointerEvent = pointerEventInstance(event);
- pointerEvent->localize(item);
- if (itemPrivate->handlePointerEvent(pointerEvent, false)) {
- if (pointerEvent->allPointsAccepted()) {
- event->accept();
- return true;
- }
- }
-
- // If still not accepted, try direct delivery to the item
- if (item->contains(p)) {
- QNativeGestureEvent copy(event->gestureType(), event->device(), p, event->windowPos(), event->screenPos(),
- event->value(), 0L, 0L); // TODO can't copy things I can't access
- event->accept();
- item->event(&copy);
- if (copy.isAccepted()) {
- event->accept();
- return true;
- }
- }
-
- return false;
-}
-#endif // gestures
-
bool QQuickWindowPrivate::deliverTouchCancelEvent(QTouchEvent *event)
{
qCDebug(DBG_TOUCH) << event;
@@ -2229,6 +2250,8 @@ QQuickPointerEvent *QQuickWindowPrivate::queryPointerEventInstance(QQuickPointer
if (eventType == QEvent::NativeGesture && !qobject_cast<QQuickPointerNativeGestureEvent*>(e))
continue;
#endif
+ if (eventType == QEvent::Wheel && !qobject_cast<QQuickPointerScrollEvent*>(e))
+ continue;
// Otherwise we assume there's only one event type per device.
// More disambiguation tests might need to be added above if that changes later.
if (e->device() == device)
@@ -2248,7 +2271,10 @@ QQuickPointerEvent *QQuickWindowPrivate::pointerEventInstance(QQuickPointerDevic
// QWindowSystemInterface::handleMouseEvent() does not take a device parameter:
// we assume all mouse events come from one mouse (the "core pointer").
// So when the event is a mouse event, device == QQuickPointerDevice::genericMouseDevice()
- ev = new QQuickPointerMouseEvent(q, device);
+ if (eventType == QEvent::Wheel)
+ ev = new QQuickPointerScrollEvent(q, device);
+ else
+ ev = new QQuickPointerMouseEvent(q, device);
break;
case QQuickPointerDevice::TouchPad:
case QQuickPointerDevice::TouchScreen:
@@ -2282,6 +2308,7 @@ QQuickPointerEvent *QQuickWindowPrivate::pointerEventInstance(QEvent *event) con
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
+ case QEvent::Wheel:
dev = QQuickPointerDevice::genericMouseDevice();
break;
case QEvent::TouchBegin:
@@ -2324,7 +2351,7 @@ void QQuickWindowPrivate::deliverPointerEvent(QQuickPointerEvent *event)
} else if (event->asPointerTouchEvent()) {
deliverTouchEvent(event->asPointerTouchEvent());
} else {
- Q_ASSERT(false);
+ deliverSinglePointEventUntilAccepted(event);
}
event->reset(nullptr);
@@ -2332,16 +2359,16 @@ void QQuickWindowPrivate::deliverPointerEvent(QQuickPointerEvent *event)
--pointerEventRecursionGuard;
}
-// check if item or any of its child items contain the point
+// check if item or any of its child items contain the point, or if any pointer handler "wants" the point
// FIXME: should this be iterative instead of recursive?
// If checkMouseButtons is true, it means we are finding targets for a mouse event, so no item for which acceptedMouseButtons() is NoButton will be added.
// If checkAcceptsTouch is true, it means we are finding targets for a touch event, so either acceptTouchEvents() must return true OR
// it must accept a synth. mouse event, thus if acceptTouchEvents() returns false but acceptedMouseButtons() is true, gets added; if not, it doesn't.
-QVector<QQuickItem *> QQuickWindowPrivate::pointerTargets(QQuickItem *item, const QPointF &scenePos, bool checkMouseButtons, bool checkAcceptsTouch) const
+QVector<QQuickItem *> QQuickWindowPrivate::pointerTargets(QQuickItem *item, QQuickEventPoint *point, bool checkMouseButtons, bool checkAcceptsTouch) const
{
QVector<QQuickItem *> targets;
auto itemPrivate = QQuickItemPrivate::get(item);
- QPointF itemPos = item->mapFromScene(scenePos);
+ QPointF itemPos = item->mapFromScene(point->scenePosition());
// if the item clips, we can potentially return early
if (itemPrivate->flags & QQuickItem::ItemClipsChildrenToShape) {
if (!item->contains(itemPos))
@@ -2355,11 +2382,15 @@ QVector<QQuickItem *> QQuickWindowPrivate::pointerTargets(QQuickItem *item, cons
auto childPrivate = QQuickItemPrivate::get(child);
if (!child->isVisible() || !child->isEnabled() || childPrivate->culled)
continue;
- targets << pointerTargets(child, scenePos, checkMouseButtons, checkAcceptsTouch);
+ targets << pointerTargets(child, point, checkMouseButtons, checkAcceptsTouch);
}
bool relevant = item->contains(itemPos);
- if (!(itemPrivate->hasPointerHandlers())) {
+ if (itemPrivate->hasPointerHandlers()) {
+ if (!relevant)
+ if (itemPrivate->anyPointerHandlerWants(point))
+ relevant = true;
+ } else {
if (relevant && checkMouseButtons && item->acceptedMouseButtons() == Qt::NoButton)
relevant = false;
if (relevant && checkAcceptsTouch && !(item->acceptTouchEvents() || item->acceptedMouseButtons()))
@@ -2440,6 +2471,7 @@ void QQuickWindowPrivate::deliverUpdatedTouchPoints(QQuickPointerTouchEvent *eve
// The grabber is not an item? It's a handler then. Let it have the event first.
QQuickPointerHandler *handler = static_cast<QQuickPointerHandler *>(grabber);
receiver = static_cast<QQuickPointerHandler *>(grabber)->parentItem();
+ hasFiltered.clear();
if (sendFilteredPointerEvent(event, receiver))
done = true;
event->localize(receiver);
@@ -2469,7 +2501,7 @@ void QQuickWindowPrivate::deliverUpdatedTouchPoints(QQuickPointerTouchEvent *eve
QQuickEventPoint *point = event->point(i);
if (point->state() == QQuickEventPoint::Pressed)
continue; // presses were delivered earlier; not the responsibility of deliverUpdatedTouchPoints
- QVector<QQuickItem *> targetItemsForPoint = pointerTargets(contentItem, point->scenePosition(), false, false);
+ QVector<QQuickItem *> targetItemsForPoint = pointerTargets(contentItem, point, false, false);
if (targetItems.count()) {
targetItems = mergePointerTargets(targetItems, targetItemsForPoint);
} else {
@@ -2494,12 +2526,20 @@ bool QQuickWindowPrivate::deliverPressOrReleaseEvent(QQuickPointerEvent *event,
int pointCount = event->pointCount();
QVector<QQuickItem *> targetItems;
bool isTouchEvent = (event->asPointerTouchEvent() != nullptr);
+ if (isTouchEvent && event->isPressEvent()) {
+ // When a second point is pressed, we're starting over with delivery, so
+ // don't let prior conception of which one is acting as a mouse interfere
+ touchMouseId = -1;
+ touchMouseDevice = nullptr;
+ }
for (int i = 0; i < pointCount; ++i) {
auto point = event->point(i);
+ if (point->state() == QQuickEventPoint::Pressed && !event->isDoubleClickEvent())
+ point->clearPassiveGrabbers();
point->setAccepted(false); // because otherwise touchEventForItem will ignore it
if (point->grabberPointerHandler() && point->state() == QQuickEventPoint::Released)
point->setGrabberPointerHandler(nullptr, true);
- QVector<QQuickItem *> targetItemsForPoint = pointerTargets(contentItem, point->scenePosition(), !isTouchEvent, isTouchEvent);
+ QVector<QQuickItem *> targetItemsForPoint = pointerTargets(contentItem, point, !isTouchEvent, isTouchEvent);
if (targetItems.count()) {
targetItems = mergePointerTargets(targetItems, targetItemsForPoint);
} else {
@@ -2512,6 +2552,7 @@ bool QQuickWindowPrivate::deliverPressOrReleaseEvent(QQuickPointerEvent *event,
qWarning("event went missing during delivery! (nested sendEvent() is not allowed)");
break;
}
+ hasFiltered.clear();
if (!handlersOnly && sendFilteredPointerEvent(event, item)) {
if (event->isAccepted()) {
for (int i = 0; i < event->pointCount(); ++i)
@@ -2567,7 +2608,6 @@ void QQuickWindowPrivate::deliverMatchingPointsToItem(QQuickItem *item, QQuickPo
// synthetic events - flickable sends one when setPressDelay is used.
auto oldMouseGrabber = q->mouseGrabberItem();
QPointF localPos = item->mapFromScene(point->scenePosition());
- Q_ASSERT(item->contains(localPos)); // transform is checked already
QMouseEvent *me = event->asMouseEvent(localPos);
me->accept();
QCoreApplication::sendEvent(item, me);
@@ -2595,6 +2635,7 @@ void QQuickWindowPrivate::deliverMatchingPointsToItem(QQuickItem *item, QQuickPo
bool eventAccepted = false;
// If any parent filters the event, we're done.
+ hasFiltered.clear();
if (sendFilteredPointerEvent(pointerEvent, item))
return;
@@ -2604,10 +2645,12 @@ void QQuickWindowPrivate::deliverMatchingPointsToItem(QQuickItem *item, QQuickPo
eventAccepted = touchEvent->isAccepted();
// If the touch event wasn't accepted, synthesize a mouse event and see if the item wants it.
- if (!eventAccepted && (itemPrivate->acceptedMouseButtons() & Qt::LeftButton)) {
- // send mouse event
- if (deliverTouchAsMouse(item, ptEvent))
- eventAccepted = true;
+ if (Q_LIKELY(QCoreApplication::testAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents))) {
+ if (!eventAccepted && (itemPrivate->acceptedMouseButtons() & Qt::LeftButton)) {
+ // send mouse event
+ if (deliverTouchAsMouse(item, ptEvent))
+ eventAccepted = true;
+ }
}
if (eventAccepted) {
@@ -2811,7 +2854,6 @@ QQuickItem *QQuickWindowPrivate::findCursorItem(QQuickItem *item, const QPointF
bool QQuickWindowPrivate::sendFilteredPointerEvent(QQuickPointerEvent *event, QQuickItem *receiver, QQuickItem *filteringParent)
{
- hasFiltered.clear();
return sendFilteredPointerEventImpl(event, receiver, filteringParent ? filteringParent : receiver->parentItem());
}
@@ -2872,7 +2914,7 @@ bool QQuickWindowPrivate::sendFilteredPointerEventImpl(QQuickPointerEvent *event
pt->setGrabberItem(filteringParent);
}
return true;
- } else {
+ } else if (Q_LIKELY(QCoreApplication::testAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents))) {
// filteringParent didn't filter the touch event. Give it a chance to filter a synthetic mouse event.
for (int i = 0; i < filteringParentTouchEvent->touchPoints().size(); ++i) {
const QTouchEvent::TouchPoint &tp = filteringParentTouchEvent->touchPoints().at(i);
@@ -2971,6 +3013,12 @@ bool QQuickWindowPrivate::dragOverThreshold(qreal d, Qt::Axis axis, QMouseEvent
return overThreshold;
}
+bool QQuickWindowPrivate::dragOverThreshold(QVector2D delta)
+{
+ int threshold = qApp->styleHints()->startDragDistance();
+ return qAbs(delta.x()) > threshold || qAbs(delta.y()) > threshold;
+}
+
/*!
\qmlproperty list<Object> Window::data
\default
diff --git a/src/quick/items/qquickwindow.h b/src/quick/items/qquickwindow.h
index 817178fdac..79e8a11aa8 100644
--- a/src/quick/items/qquickwindow.h
+++ b/src/quick/items/qquickwindow.h
@@ -95,6 +95,7 @@ public:
};
Q_DECLARE_FLAGS(CreateTextureOptions, CreateTextureOption)
+ Q_FLAG(CreateTextureOptions)
enum SceneGraphError {
ContextNotAvailable = 1
diff --git a/src/quick/items/qquickwindow_p.h b/src/quick/items/qquickwindow_p.h
index b5e3a2c1eb..10c8477417 100644
--- a/src/quick/items/qquickwindow_p.h
+++ b/src/quick/items/qquickwindow_p.h
@@ -152,12 +152,7 @@ public:
bool sendFilteredMouseEvent(QEvent *event, QQuickItem *receiver, QQuickItem *filteringParent);
bool sendFilteredPointerEvent(QQuickPointerEvent *event, QQuickItem *receiver, QQuickItem *filteringParent = nullptr);
bool sendFilteredPointerEventImpl(QQuickPointerEvent *event, QQuickItem *receiver, QQuickItem *filteringParent);
-#if QT_CONFIG(wheelevent)
- bool deliverWheelEvent(QQuickItem *, QWheelEvent *);
-#endif
-#if QT_CONFIG(gestures)
- bool deliverNativeGestureEvent(QQuickItem *, QNativeGestureEvent *);
-#endif
+ bool deliverSinglePointEventUntilAccepted(QQuickPointerEvent *);
// entry point of events to the window
void handleTouchEvent(QTouchEvent *);
@@ -180,7 +175,7 @@ public:
void deliverUpdatedTouchPoints(QQuickPointerTouchEvent *event);
void deliverMatchingPointsToItem(QQuickItem *item, QQuickPointerEvent *pointerEvent, bool handlersOnly = false);
- QVector<QQuickItem *> pointerTargets(QQuickItem *, const QPointF &, bool checkMouseButtons, bool checkAcceptsTouch) const;
+ QVector<QQuickItem *> pointerTargets(QQuickItem *, QQuickEventPoint *point, bool checkMouseButtons, bool checkAcceptsTouch) const;
QVector<QQuickItem *> mergePointerTargets(const QVector<QQuickItem *> &list1, const QVector<QQuickItem *> &list2) const;
// hover delivery
@@ -307,6 +302,7 @@ public:
QQuickWindowPrivate::dragOverThreshold(delta.y(), Qt::YAxis, point));
}
+ static bool dragOverThreshold(QVector2D delta);
// data property
static void data_append(QQmlListProperty<QObject> *, QObject *);
diff --git a/src/quick/qtquick2.cpp b/src/quick/qtquick2.cpp
index 24467a3701..63f3b91b82 100644
--- a/src/quick/qtquick2.cpp
+++ b/src/quick/qtquick2.cpp
@@ -55,11 +55,6 @@
#include <qqmlproperty.h>
#include <QtCore/QPointer>
-static void initResources()
-{
- Q_INIT_RESOURCE(scenegraph);
-}
-
QT_BEGIN_NAMESPACE
#if !QT_CONFIG(qml_debug)
@@ -185,8 +180,6 @@ void QQmlQtQuick2DebugStatesDelegate::resetBindingForInvalidProperty(QObject *ob
void QQmlQtQuick2Module::defineModule()
{
- initResources();
-
QQuick_initializeProviders();
QQuickUtilModule::defineModule();
diff --git a/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer.cpp b/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer.cpp
index d715d900ba..2e5fdbbe6b 100644
--- a/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer.cpp
@@ -77,6 +77,11 @@ QSGSoftwareRenderableNode *QSGAbstractSoftwareRenderer::renderableNode(QSGNode *
return m_nodes.value(node, nullptr);
}
+const QLinkedList<QSGSoftwareRenderableNode*> &QSGAbstractSoftwareRenderer::renderableNodes() const
+{
+ return m_renderableNodes;
+}
+
void QSGAbstractSoftwareRenderer::addNodeMapping(QSGNode *node, QSGSoftwareRenderableNode *renderableNode)
{
m_nodes.insert(node, renderableNode);
diff --git a/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer_p.h b/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer_p.h
index f6594d931a..99204ef25e 100644
--- a/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer_p.h
+++ b/src/quick/scenegraph/adaptations/software/qsgabstractsoftwarerenderer_p.h
@@ -88,6 +88,7 @@ protected:
QRect backgroundRect();
// only known after calling optimizeRenderList()
bool isOpaque() const { return m_isOpaque; }
+ const QLinkedList<QSGSoftwareRenderableNode*> &renderableNodes() const;
private:
void nodeAdded(QSGNode *node);
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwareadaptation.cpp b/src/quick/scenegraph/adaptations/software/qsgsoftwareadaptation.cpp
index a8b5944974..c33144344f 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwareadaptation.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwareadaptation.cpp
@@ -74,6 +74,7 @@ QSGContextFactoryInterface::Flags QSGSoftwareAdaptation::flags(const QString &)
QSGRenderLoop *QSGSoftwareAdaptation::createWindowManager()
{
+#if QT_CONFIG(thread)
static bool threaded = false;
static bool envChecked = false;
if (!envChecked) {
@@ -83,6 +84,7 @@ QSGRenderLoop *QSGSoftwareAdaptation::createWindowManager()
if (threaded)
return new QSGSoftwareThreadedRenderLoop;
+#endif
return new QSGSoftwareRenderLoop();
}
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwareglyphnode.cpp b/src/quick/scenegraph/adaptations/software/qsgsoftwareglyphnode.cpp
index 21f20c66cd..dd789b78c7 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwareglyphnode.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwareglyphnode.cpp
@@ -49,12 +49,40 @@ QSGSoftwareGlyphNode::QSGSoftwareGlyphNode()
setGeometry(&m_geometry);
}
+namespace {
+QRectF calculateBoundingRect(const QPointF &position, const QGlyphRun &glyphs)
+{
+ qreal minX = 0;
+ qreal minY = 0;
+ qreal maxX = 0;
+ qreal maxY = 0;
+
+ for (int i = 0, n = qMin(glyphs.glyphIndexes().size(), glyphs.positions().size()); i < n; ++i) {
+ QRectF glyphRect = glyphs.rawFont().boundingRect(glyphs.glyphIndexes()[i]);
+ glyphRect.translate(glyphs.positions()[i]);
+
+ if (i == 0) {
+ minX = glyphRect.left();
+ minY = glyphRect.top();
+ maxX = glyphRect.right();
+ maxY = glyphRect.bottom();
+ } else {
+ minX = qMin(glyphRect.left(), minX);
+ minY = qMin(glyphRect.top(), minY);
+ maxX = qMax(glyphRect.right(),maxX);
+ maxY = qMax(glyphRect.bottom(), maxY);
+ }
+ }
+ QRectF boundingRect(QPointF(minX, minY), QPointF(maxX, maxY));
+ return boundingRect.translated(position - QPointF(0.0, glyphs.rawFont().ascent()));
+}
+}
void QSGSoftwareGlyphNode::setGlyphs(const QPointF &position, const QGlyphRun &glyphs)
{
m_position = position;
m_glyphRun = glyphs;
- m_bounding_rect = glyphs.boundingRect().translated(m_position - QPointF(0.0, glyphs.rawFont().ascent()));
+ m_bounding_rect = calculateBoundingRect(position, glyphs);
}
void QSGSoftwareGlyphNode::setColor(const QColor &color)
@@ -91,8 +119,8 @@ void QSGSoftwareGlyphNode::paint(QPainter *painter)
QPointF pos = m_position - QPointF(0, m_glyphRun.rawFont().ascent());
qreal offset = 1.0;
- if (painter->device()->devicePixelRatio() != 0)
- offset = 1.0 / painter->device()->devicePixelRatio();
+ if (painter->device()->devicePixelRatioF() > 0.0)
+ offset = 1.0 / painter->device()->devicePixelRatioF();
switch (m_style) {
case QQuickText::Normal: break;
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode.cpp b/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode.cpp
index bf3141bc32..2c361e03e2 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode.cpp
@@ -47,6 +47,7 @@ QT_BEGIN_NAMESPACE
QSGSoftwareInternalRectangleNode::QSGSoftwareInternalRectangleNode()
: m_penWidth(0)
, m_radius(0)
+ , m_vertical(true)
, m_cornerPixmapIsDirty(true)
, m_devicePixelRatio(1)
{
@@ -186,6 +187,15 @@ void QSGSoftwareInternalRectangleNode::setGradientStops(const QGradientStops &st
markDirty(DirtyMaterial);
}
+void QSGSoftwareInternalRectangleNode::setGradientVertical(bool vertical)
+{
+ if (m_vertical != vertical) {
+ m_vertical = vertical;
+ m_cornerPixmapIsDirty = true;
+ markDirty(DirtyMaterial);
+ }
+}
+
void QSGSoftwareInternalRectangleNode::setRadius(qreal radius)
{
if (m_radius != radius) {
@@ -209,7 +219,7 @@ void QSGSoftwareInternalRectangleNode::update()
}
if (!m_stops.isEmpty()) {
- QLinearGradient gradient(QPoint(0,0), QPoint(0,1));
+ QLinearGradient gradient(QPoint(0,0), QPoint(m_vertical ? 0 : 1, m_vertical ? 1 : 0));
gradient.setStops(m_stops);
gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
m_brush = QBrush(gradient);
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode_p.h b/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode_p.h
index 1f87424d2a..125520de26 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode_p.h
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwareinternalrectanglenode_p.h
@@ -69,6 +69,7 @@ public:
void setPenColor(const QColor &color) override;
void setPenWidth(qreal width) override;
void setGradientStops(const QGradientStops &stops) override;
+ void setGradientVertical(bool vertical) override;
void setRadius(qreal radius) override;
void setAntialiasing(bool antialiasing) override { Q_UNUSED(antialiasing) }
void setAligned(bool aligned) override;
@@ -91,6 +92,7 @@ private:
double m_radius;
QPen m_pen;
QBrush m_brush;
+ bool m_vertical;
bool m_cornerPixmapIsDirty;
QPixmap m_cornerPixmap;
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwarepublicnodes.cpp b/src/quick/scenegraph/adaptations/software/qsgsoftwarepublicnodes.cpp
index 1463681fa3..471624d3f8 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwarepublicnodes.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwarepublicnodes.cpp
@@ -38,6 +38,7 @@
****************************************************************************/
#include "qsgsoftwarepublicnodes_p.h"
+#include "qsgsoftwarelayer_p.h"
#include "qsgsoftwarepixmaptexture_p.h"
#include "qsgsoftwareinternalimagenode_p.h"
@@ -104,6 +105,9 @@ void QSGSoftwareImageNode::paint(QPainter *painter)
} else if (QSGSoftwarePixmapTexture *pt = qobject_cast<QSGSoftwarePixmapTexture *>(m_texture)) {
const QPixmap &pm = pt->pixmap();
painter->drawPixmap(m_rect, pm, m_sourceRect);
+ } else if (QSGSoftwareLayer *pt = qobject_cast<QSGSoftwareLayer *>(m_texture)) {
+ const QPixmap &pm = pt->pixmap();
+ painter->drawPixmap(m_rect, pm, m_sourceRect);
} else if (QSGPlainTexture *pt = qobject_cast<QSGPlainTexture *>(m_texture)) {
const QImage &im = pt->image();
painter->drawImage(m_rect, im, m_sourceRect);
@@ -115,7 +119,6 @@ void QSGSoftwareImageNode::updateCachedMirroredPixmap()
if (m_transformMode == NoTransform) {
m_cachedPixmap = QPixmap();
} else {
-
if (QSGSoftwarePixmapTexture *pt = qobject_cast<QSGSoftwarePixmapTexture *>(m_texture)) {
QTransform mirrorTransform;
if (m_transformMode.testFlag(MirrorVertically))
@@ -123,6 +126,13 @@ void QSGSoftwareImageNode::updateCachedMirroredPixmap()
if (m_transformMode.testFlag(MirrorHorizontally))
mirrorTransform = mirrorTransform.scale(-1, 1);
m_cachedPixmap = pt->pixmap().transformed(mirrorTransform);
+ } else if (QSGSoftwareLayer *pt = qobject_cast<QSGSoftwareLayer *>(m_texture)) {
+ QTransform mirrorTransform;
+ if (m_transformMode.testFlag(MirrorVertically))
+ mirrorTransform = mirrorTransform.scale(1, -1);
+ if (m_transformMode.testFlag(MirrorHorizontally))
+ mirrorTransform = mirrorTransform.scale(-1, 1);
+ m_cachedPixmap = pt->pixmap().transformed(mirrorTransform);
} else if (QSGPlainTexture *pt = qobject_cast<QSGPlainTexture *>(m_texture)) {
m_cachedPixmap = QPixmap::fromImage(pt->image().mirrored(m_transformMode.testFlag(MirrorHorizontally), m_transformMode.testFlag(MirrorVertically)));
} else {
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderablenode_p.h b/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderablenode_p.h
index 8fc87db179..b20d0a1828 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderablenode_p.h
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderablenode_p.h
@@ -72,7 +72,7 @@ class QSGSoftwareNinePatchNode;
class QSGSoftwareSpriteNode;
class QSGRenderNode;
-class QSGSoftwareRenderableNode
+class Q_QUICK_PRIVATE_EXPORT QSGSoftwareRenderableNode
{
public:
enum NodeType {
@@ -104,6 +104,7 @@ public:
bool isOpaque() const { return m_isOpaque; }
bool isDirty() const { return m_isDirty; }
bool isDirtyRegionEmpty() const;
+ QSGNode *handle() const { return m_handle.node; }
void setTransform(const QTransform &transform);
void setClipRegion(const QRegion &clipRegion, bool hasClipRegion = true);
@@ -123,6 +124,7 @@ public:
private:
union RenderableNodeHandle {
+ QSGNode *node;
QSGSimpleRectNode *simpleRectNode;
QSGSimpleTextureNode *simpleTextureNode;
QSGSoftwareInternalImageNode *imageNode;
diff --git a/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderer.cpp b/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderer.cpp
index ffcee5f56e..e9ed52d428 100644
--- a/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderer.cpp
+++ b/src/quick/scenegraph/adaptations/software/qsgsoftwarerenderer.cpp
@@ -113,8 +113,8 @@ void QSGSoftwareRenderer::render()
setBackgroundColor(clearColor());
setBackgroundRect(QRect(0, 0,
- m_paintDevice->width() / m_paintDevice->devicePixelRatio(),
- m_paintDevice->height() / m_paintDevice->devicePixelRatio()));
+ m_paintDevice->width() / m_paintDevice->devicePixelRatioF(),
+ m_paintDevice->height() / m_paintDevice->devicePixelRatioF()));
// Build Renderlist
// The renderlist is created by visiting each node in the tree and when a
diff --git a/src/quick/scenegraph/adaptations/software/software.pri b/src/quick/scenegraph/adaptations/software/software.pri
index de5f01cdee..278dbe7944 100644
--- a/src/quick/scenegraph/adaptations/software/software.pri
+++ b/src/quick/scenegraph/adaptations/software/software.pri
@@ -18,8 +18,7 @@ SOURCES += \
$$PWD/qsgsoftwarerenderlistbuilder.cpp \
$$PWD/qsgsoftwarerenderloop.cpp \
$$PWD/qsgsoftwarelayer.cpp \
- $$PWD/qsgsoftwareadaptation.cpp \
- $$PWD/qsgsoftwarethreadedrenderloop.cpp
+ $$PWD/qsgsoftwareadaptation.cpp
HEADERS += \
$$PWD/qsgsoftwarecontext_p.h \
@@ -37,8 +36,7 @@ HEADERS += \
$$PWD/qsgsoftwarerenderlistbuilder_p.h \
$$PWD/qsgsoftwarerenderloop_p.h \
$$PWD/qsgsoftwarelayer_p.h \
- $$PWD/qsgsoftwareadaptation_p.h \
- $$PWD/qsgsoftwarethreadedrenderloop_p.h
+ $$PWD/qsgsoftwareadaptation_p.h
qtConfig(quick-sprite) {
SOURCES += \
@@ -46,3 +44,10 @@ qtConfig(quick-sprite) {
HEADERS += \
$$PWD/qsgsoftwarespritenode_p.h
}
+
+qtConfig(thread) {
+ SOURCES += \
+ $$PWD/qsgsoftwarethreadedrenderloop.cpp
+ HEADERS +=\
+ $$PWD/qsgsoftwarethreadedrenderloop_p.h
+}
diff --git a/src/quick/scenegraph/compressedtexture/qsgcompressedatlastexture.cpp b/src/quick/scenegraph/compressedtexture/qsgcompressedatlastexture.cpp
index e868a4380e..796bc870de 100644
--- a/src/quick/scenegraph/compressedtexture/qsgcompressedatlastexture.cpp
+++ b/src/quick/scenegraph/compressedtexture/qsgcompressedatlastexture.cpp
@@ -56,7 +56,6 @@
#include <private/qquickprofiler_p.h>
#include <private/qsgtexture_p.h>
#include <private/qsgcompressedtexture_p.h>
-#include <private/qsgpkmhandler_p.h>
QT_BEGIN_NAMESPACE
@@ -154,13 +153,12 @@ QSGTexture *Texture::removedFromAtlas() const
}
if (!m_data.isEmpty()) {
- QSGCompressedTexture::DataPtr texData(QSGCompressedTexture::DataPtr::create());
- texData->data = m_data;
- texData->size = m_size;
- texData->format = static_cast<Atlas*>(m_atlas)->format();
- texData->hasAlpha = hasAlphaChannel();
- texData->dataLength = m_dataLength;
- texData->dataOffset = m_dataOffset;
+ QTextureFileData texData;
+ texData.setData(m_data);
+ texData.setSize(m_size);
+ texData.setGLInternalFormat(static_cast<Atlas*>(m_atlas)->format());
+ texData.setDataLength(m_dataLength);
+ texData.setDataOffset(m_dataOffset);
m_nonatlas_texture = new QSGCompressedTexture(texData);
m_nonatlas_texture->setMipmapFiltering(mipmapFiltering());
m_nonatlas_texture->setFiltering(filtering());
diff --git a/src/quick/scenegraph/compressedtexture/qsgcompressedtexture.cpp b/src/quick/scenegraph/compressedtexture/qsgcompressedtexture.cpp
index 839c562989..d3310bc11c 100644
--- a/src/quick/scenegraph/compressedtexture/qsgcompressedtexture.cpp
+++ b/src/quick/scenegraph/compressedtexture/qsgcompressedtexture.cpp
@@ -49,50 +49,11 @@ QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(QSG_LOG_TEXTUREIO, "qt.scenegraph.textureio");
-bool QSGCompressedTextureData::isValid() const
-{
- if (data.isNull() || size.isEmpty() || !format)
- return false;
- if (dataLength < 0 || dataOffset < 0 || dataOffset >= data.length())
- return false;
- if (dataLength > 0 && qint64(dataOffset) + qint64(dataLength) > qint64(data.length()))
- return false;
-
- return true;
-}
-
-int QSGCompressedTextureData::sizeInBytes() const
-{
- if (!isValid())
- return 0;
- return dataLength > 0 ? dataLength : data.length() - dataOffset;
-}
-
-Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug dbg, const QSGCompressedTextureData *d)
-{
- QDebugStateSaver saver(dbg);
-
- dbg.nospace() << "QSGCompressedTextureData(";
- if (d) {
- dbg << d->logName << ' ';
- dbg << static_cast<QOpenGLTexture::TextureFormat>(d->format)
- << "[0x" << hex << d->format << dec << "]";
- dbg.space() << (d->hasAlpha ? "with" : "no") << "alpha" << d->size
- << "databuffer" << d->data.size() << "offset" << d->dataOffset << "length";
- dbg.nospace() << d->dataLength << ")";
- } else {
- dbg << "null)";
- }
- return dbg;
-}
-
-QSGCompressedTexture::QSGCompressedTexture(const DataPtr& texData)
+QSGCompressedTexture::QSGCompressedTexture(const QTextureFileData &texData)
: m_textureData(texData)
{
- if (m_textureData) {
- m_size = m_textureData->size;
- m_hasAlpha = m_textureData->hasAlpha;
- }
+ m_size = m_textureData.size();
+ m_hasAlpha = !formatIsOpaque(m_textureData.glInternalFormat());
}
QSGCompressedTexture::~QSGCompressedTexture()
@@ -155,37 +116,40 @@ void QSGCompressedTexture::bind()
if (m_uploaded)
return;
- QByteArray logName(m_textureData ? m_textureData->logName : QByteArrayLiteral("(unset)"));
-
- if (!m_textureData || !m_textureData->isValid()) {
- qCDebug(QSG_LOG_TEXTUREIO, "Invalid texture data for %s", logName.constData());
+ if (!m_textureData.isValid()) {
+ qCDebug(QSG_LOG_TEXTUREIO, "Invalid texture data for %s", m_textureData.logName().constData());
funcs->glBindTexture(GL_TEXTURE_2D, 0);
return;
}
if (Q_UNLIKELY(QSG_LOG_TEXTUREIO().isDebugEnabled())) {
- qCDebug(QSG_LOG_TEXTUREIO) << "Uploading texture" << m_textureData.data();
+ qCDebug(QSG_LOG_TEXTUREIO) << "Uploading texture" << m_textureData;
while (funcs->glGetError() != GL_NO_ERROR);
}
- funcs->glCompressedTexImage2D(GL_TEXTURE_2D, 0, m_textureData->format,
- m_size.width(), m_size.height(), 0, m_textureData->sizeInBytes(),
- m_textureData->data.constData() + m_textureData->dataOffset);
+ funcs->glCompressedTexImage2D(GL_TEXTURE_2D, 0, m_textureData.glInternalFormat(),
+ m_size.width(), m_size.height(), 0, m_textureData.dataLength(),
+ m_textureData.data().constData() + m_textureData.dataOffset());
if (Q_UNLIKELY(QSG_LOG_TEXTUREIO().isDebugEnabled())) {
GLuint error = funcs->glGetError();
if (error != GL_NO_ERROR) {
- qCDebug(QSG_LOG_TEXTUREIO, "glCompressedTexImage2D failed for %s, error 0x%x", logName.constData(), error);
+ qCDebug(QSG_LOG_TEXTUREIO, "glCompressedTexImage2D failed for %s, error 0x%x", m_textureData.logName().constData(), error);
}
}
- m_textureData.clear(); // Release this memory, not needed anymore
+ m_textureData = QTextureFileData(); // Release this memory, not needed anymore
updateBindOptions(true);
m_uploaded = true;
#endif // QT_CONFIG(opengl)
}
+QTextureFileData QSGCompressedTexture::textureData() const
+{
+ return m_textureData;
+}
+
bool QSGCompressedTexture::formatIsOpaque(quint32 glTextureFormat)
{
switch (glTextureFormat) {
@@ -211,14 +175,14 @@ bool QSGCompressedTexture::formatIsOpaque(quint32 glTextureFormat)
}
}
-QSGCompressedTextureFactory::QSGCompressedTextureFactory(const QSGCompressedTexture::DataPtr &texData)
+QSGCompressedTextureFactory::QSGCompressedTextureFactory(const QTextureFileData &texData)
: m_textureData(texData)
{
}
QSGTexture *QSGCompressedTextureFactory::createTexture(QQuickWindow *window) const
{
- if (!m_textureData || !m_textureData->isValid())
+ if (!m_textureData.isValid())
return nullptr;
// attempt to atlas the texture
@@ -232,15 +196,12 @@ QSGTexture *QSGCompressedTextureFactory::createTexture(QQuickWindow *window) con
int QSGCompressedTextureFactory::textureByteCount() const
{
- return m_textureData ? m_textureData->sizeInBytes() : 0;
+ return qMax(0, m_textureData.data().size() - m_textureData.dataOffset());
}
-
QSize QSGCompressedTextureFactory::textureSize() const
{
- if (m_textureData && m_textureData->isValid())
- return m_textureData->size;
- return QSize();
+ return m_textureData.size();
}
QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/compressedtexture/qsgcompressedtexture_p.h b/src/quick/scenegraph/compressedtexture/qsgcompressedtexture_p.h
index aa87316809..c3b58a2389 100644
--- a/src/quick/scenegraph/compressedtexture/qsgcompressedtexture_p.h
+++ b/src/quick/scenegraph/compressedtexture/qsgcompressedtexture_p.h
@@ -51,6 +51,7 @@
// We mean it.
//
+#include <private/qtexturefiledata_p.h>
#include <QSGTexture>
#include <QtQuick/private/qsgcontext_p.h>
#include <QQuickTextureFactory>
@@ -58,30 +59,11 @@
QT_BEGIN_NAMESPACE
-struct Q_QUICK_PRIVATE_EXPORT QSGCompressedTextureData
-{
- QByteArray logName;
- QByteArray data;
- QSize size;
- uint format = 0;
- int dataOffset = 0;
- int dataLength = 0;
- bool hasAlpha = false;
-
- bool isValid() const;
- int sizeInBytes() const;
-};
-
-Q_QUICK_PRIVATE_EXPORT QDebug operator<<(QDebug, const QSGCompressedTextureData *);
-
-
class Q_QUICK_PRIVATE_EXPORT QSGCompressedTexture : public QSGTexture
{
Q_OBJECT
public:
- typedef QSharedPointer<QSGCompressedTextureData> DataPtr;
-
- QSGCompressedTexture(const DataPtr& texData);
+ QSGCompressedTexture(const QTextureFileData& texData);
virtual ~QSGCompressedTexture();
int textureId() const override;
@@ -91,12 +73,12 @@ public:
void bind() override;
- const QSGCompressedTextureData *textureData();
+ QTextureFileData textureData() const;
static bool formatIsOpaque(quint32 glTextureFormat);
protected:
- DataPtr m_textureData;
+ QTextureFileData m_textureData;
QSize m_size;
mutable uint m_textureId = 0;
bool m_hasAlpha = false;
@@ -110,13 +92,14 @@ namespace QSGAtlasTexture {
class Q_QUICK_PRIVATE_EXPORT QSGCompressedTextureFactory : public QQuickTextureFactory
{
public:
- QSGCompressedTextureFactory(const QSGCompressedTexture::DataPtr& texData);
+ QSGCompressedTextureFactory(const QTextureFileData& texData);
QSGTexture *createTexture(QQuickWindow *) const override;
int textureByteCount() const override;
QSize textureSize() const override;
protected:
- QSGCompressedTexture::DataPtr m_textureData;
+ QTextureFileData m_textureData;
+
private:
friend class QSGAtlasTexture::Manager;
};
diff --git a/src/quick/scenegraph/compressedtexture/qsgktxhandler.cpp b/src/quick/scenegraph/compressedtexture/qsgktxhandler.cpp
deleted file mode 100644
index e3e4ca6824..0000000000
--- a/src/quick/scenegraph/compressedtexture/qsgktxhandler.cpp
+++ /dev/null
@@ -1,186 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtQuick 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 "qsgktxhandler_p.h"
-#include "qsgcompressedtexture_p.h"
-#include <QOpenGLTexture>
-#include <QtEndian>
-
-//#define KTX_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-#define KTX_IDENTIFIER_LENGTH 12
-static const char ktxIdentifier[KTX_IDENTIFIER_LENGTH] = { '\xAB', 'K', 'T', 'X', ' ', '1', '1', '\xBB', '\r', '\n', '\x1A', '\n' };
-static const quint32 platformEndianIdentifier = 0x04030201;
-static const quint32 inversePlatformEndianIdentifier = 0x01020304;
-
-struct KTXHeader {
- quint8 identifier[KTX_IDENTIFIER_LENGTH]; //Must match ktxIdentifier
- quint32 endianness; //Either platformEndianIdentifier or inversePlatformEndianIdentifier, other values not allowed.
- quint32 glType;
- quint32 glTypeSize;
- quint32 glFormat;
- quint32 glInternalFormat;
- quint32 glBaseInternalFormat;
- quint32 pixelWidth;
- quint32 pixelHeight;
- quint32 pixelDepth;
- quint32 numberOfArrayElements;
- quint32 numberOfFaces;
- quint32 numberOfMipmapLevels;
- quint32 bytesOfKeyValueData;
-};
-
-static const int headerSize = sizeof(KTXHeader);
-
-// Currently unused, declared for future reference
-struct KTXKeyValuePairItem {
- quint32 keyAndValueByteSize;
- /*
- quint8 keyAndValue[keyAndValueByteSize];
- quint8 valuePadding[3 - ((keyAndValueByteSize + 3) % 4)];
- */
-};
-
-struct KTXMipmapLevel {
- quint32 imageSize;
- /*
- for each array_element in numberOfArrayElements*
- for each face in numberOfFaces
- for each z_slice in pixelDepth*
- for each row or row_of_blocks in pixelHeight*
- for each pixel or block_of_pixels in pixelWidth
- Byte data[format-specific-number-of-bytes]**
- end
- end
- end
- Byte cubePadding[0-3]
- end
- end
- quint8 mipPadding[3 - ((imageSize + 3) % 4)]
- */
-};
-
-bool QSGKtxHandler::canRead(const QByteArray &suffix, const QByteArray &block)
-{
- Q_UNUSED(suffix)
-
- return (qstrncmp(block.constData(), ktxIdentifier, KTX_IDENTIFIER_LENGTH) == 0);
-}
-
-QQuickTextureFactory *QSGKtxHandler::read()
-{
- if (!device())
- return nullptr;
-
- QByteArray buf = device()->readAll();
- if (buf.size() < headerSize || !canRead(QByteArray(), buf)) {
- qCDebug(QSG_LOG_TEXTUREIO, "Invalid KTX file %s", logName().constData());
- return nullptr;
- }
-
- const KTXHeader *header = reinterpret_cast<const KTXHeader *>(buf.constData());
- if (!checkHeader(*header)) {
- qCDebug(QSG_LOG_TEXTUREIO, "Unsupported KTX file format in %s", logName().constData());
- return nullptr;
- }
-
- QSGCompressedTexture::DataPtr texData(QSGCompressedTexture::DataPtr::create());
-
- texData->size = QSize(decode(header->pixelWidth), decode(header->pixelHeight));
- texData->format = decode(header->glInternalFormat);
- texData->hasAlpha = !QSGCompressedTexture::formatIsOpaque(texData->format);
-
- // For now, ignore any additional mipmap levels
- int preambleSize = headerSize + decode(header->bytesOfKeyValueData);
- if (buf.size() >= preambleSize + int(sizeof(KTXMipmapLevel))) {
- texData->data = buf;
- texData->dataOffset = preambleSize + sizeof(quint32); // for the imageSize
- const KTXMipmapLevel *level = reinterpret_cast<const KTXMipmapLevel *>(buf.constData() + preambleSize);
- texData->dataLength = decode(level->imageSize);
- }
-
- if (!texData->isValid()) {
- qCDebug(QSG_LOG_TEXTUREIO, "Invalid values in header of KTX file %s", logName().constData());
- return nullptr;
- }
-
- texData->logName = logName();
-#ifdef KTX_DEBUG
- qDebug() << "KTX file handler read" << texData.data();
-#endif
-
- return new QSGCompressedTextureFactory(texData);
-}
-
-bool QSGKtxHandler::checkHeader(const KTXHeader &header)
-{
- if (header.endianness != platformEndianIdentifier && header.endianness != inversePlatformEndianIdentifier)
- return false;
- inverseEndian = (header.endianness == inversePlatformEndianIdentifier);
-#ifdef KTX_DEBUG
- QMetaEnum tfme = QMetaEnum::fromType<QOpenGLTexture::TextureFormat>();
- QMetaEnum ptme = QMetaEnum::fromType<QOpenGLTexture::PixelType>();
- qDebug("Header of %s:", logName().constData());
- qDebug(" glType: 0x%x (%s)", decode(header.glType), ptme.valueToKey(decode(header.glType)));
- qDebug(" glTypeSize: %u", decode(header.glTypeSize));
- qDebug(" glFormat: 0x%x (%s)", decode(header.glFormat), tfme.valueToKey(decode(header.glFormat)));
- qDebug(" glInternalFormat: 0x%x (%s)", decode(header.glInternalFormat), tfme.valueToKey(decode(header.glInternalFormat)));
- qDebug(" glBaseInternalFormat: 0x%x (%s)", decode(header.glBaseInternalFormat), tfme.valueToKey(decode(header.glBaseInternalFormat)));
- qDebug(" pixelWidth: %u", decode(header.pixelWidth));
- qDebug(" pixelHeight: %u", decode(header.pixelHeight));
- qDebug(" pixelDepth: %u", decode(header.pixelDepth));
- qDebug(" numberOfArrayElements: %u", decode(header.numberOfArrayElements));
- qDebug(" numberOfFaces: %u", decode(header.numberOfFaces));
- qDebug(" numberOfMipmapLevels: %u", decode(header.numberOfMipmapLevels));
- qDebug(" bytesOfKeyValueData: %u", decode(header.bytesOfKeyValueData));
-#endif
- return ((decode(header.glType) == 0) &&
- (decode(header.glFormat) == 0) &&
- (decode(header.pixelDepth) == 0) &&
- (decode(header.numberOfFaces) == 1));
-}
-
-quint32 QSGKtxHandler::decode(quint32 val)
-{
- return inverseEndian ? qbswap<quint32>(val) : val;
-}
-
-QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/compressedtexture/qsgpkmhandler.cpp b/src/quick/scenegraph/compressedtexture/qsgpkmhandler.cpp
deleted file mode 100644
index 618c0db045..0000000000
--- a/src/quick/scenegraph/compressedtexture/qsgpkmhandler.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtQuick 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 "qsgpkmhandler_p.h"
-#include "qsgcompressedtexture_p.h"
-
-#include <QFile>
-#include <QDebug>
-#include <qendian.h>
-#include <qopenglfunctions.h>
-#include <qqmlfile.h>
-#include <QOpenGLTexture>
-
-//#define ETC_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-static const int headerSize = 16;
-
-static unsigned int typeMap[5] = {
- QOpenGLTexture::RGB8_ETC1, // GL_ETC1_RGB8_OES,
- QOpenGLTexture::RGB8_ETC2, // GL_COMPRESSED_RGB8_ETC2,
- 0, // unused (obsolete)
- QOpenGLTexture::RGBA8_ETC2_EAC, // GL_COMPRESSED_RGBA8_ETC2_EAC,
- QOpenGLTexture::RGB8_PunchThrough_Alpha1_ETC2 // GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
-};
-
-bool QSGPkmHandler::canRead(const QByteArray &suffix, const QByteArray &block)
-{
- Q_UNUSED(suffix)
-
- return block.startsWith("PKM ");
-}
-
-QQuickTextureFactory *QSGPkmHandler::read()
-{
- if (!device())
- return nullptr;
-
- QSGCompressedTexture::DataPtr texData(QSGCompressedTexture::DataPtr::create());
-
- texData->data = device()->readAll();
- if (texData->data.size() < headerSize || !canRead(QByteArray(), texData->data)) {
- qCDebug(QSG_LOG_TEXTUREIO, "Invalid PKM file %s", logName().constData());
- return nullptr;
- }
-
- const char *rawData = texData->data.constData();
-
- // ignore version (rawData + 4 & 5)
-
- // texture type
- quint16 type = qFromBigEndian<quint16>(rawData + 6);
- if (type > sizeof(typeMap)/sizeof(typeMap[0])) {
- qCDebug(QSG_LOG_TEXTUREIO, "Unknown compression format in PKM file %s", logName().constData());
- return nullptr;
- }
- texData->format = typeMap[type];
- texData->hasAlpha = !QSGCompressedTexture::formatIsOpaque(texData->format);
-
- // texture size
- const int bpb = (texData->format == QOpenGLTexture::RGBA8_ETC2_EAC) ? 16 : 8;
- QSize paddedSize(qFromBigEndian<quint16>(rawData + 8), qFromBigEndian<quint16>(rawData + 10));
- texData->dataLength = (paddedSize.width() / 4) * (paddedSize.height() / 4) * bpb;
- QSize texSize(qFromBigEndian<quint16>(rawData + 12), qFromBigEndian<quint16>(rawData + 14));
- texData->size = texSize;
-
- texData->dataOffset = headerSize;
-
- if (!texData->isValid()) {
- qCDebug(QSG_LOG_TEXTUREIO, "Invalid values in header of PKM file %s", logName().constData());
- return nullptr;
- }
-
- texData->logName = logName();
-#ifdef ETC_DEBUG
- qDebug() << "PKM file handler read" << texData.data();
-#endif
- return new QSGCompressedTextureFactory(texData);
-}
-
-QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/coreapi/qsgabstractrenderer.h b/src/quick/scenegraph/coreapi/qsgabstractrenderer.h
index ab6fb4f317..b9805f9db6 100644
--- a/src/quick/scenegraph/coreapi/qsgabstractrenderer.h
+++ b/src/quick/scenegraph/coreapi/qsgabstractrenderer.h
@@ -61,6 +61,7 @@ public:
ClearStencilBuffer = 0x0004
};
Q_DECLARE_FLAGS(ClearMode, ClearModeBit)
+ Q_FLAG(ClearMode)
~QSGAbstractRenderer() override;
diff --git a/src/quick/scenegraph/qsgadaptationlayer.cpp b/src/quick/scenegraph/qsgadaptationlayer.cpp
index c64360f955..c99e149aa5 100644
--- a/src/quick/scenegraph/qsgadaptationlayer.cpp
+++ b/src/quick/scenegraph/qsgadaptationlayer.cpp
@@ -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 QtQuick module of the Qt Toolkit.
@@ -82,19 +82,26 @@ QSGDistanceFieldGlyphCache::~QSGDistanceFieldGlyphCache()
{
}
+QSGDistanceFieldGlyphCache::GlyphData &QSGDistanceFieldGlyphCache::emptyData(glyph_t glyph)
+{
+ GlyphData gd;
+ gd.texture = &s_emptyTexture;
+ QHash<glyph_t, GlyphData>::iterator it = m_glyphsData.insert(glyph, gd);
+ return it.value();
+}
+
QSGDistanceFieldGlyphCache::GlyphData &QSGDistanceFieldGlyphCache::glyphData(glyph_t glyph)
{
QHash<glyph_t, GlyphData>::iterator data = m_glyphsData.find(glyph);
if (data == m_glyphsData.end()) {
- GlyphData gd;
- gd.texture = &s_emptyTexture;
+ GlyphData &gd = emptyData(glyph);
gd.path = m_referenceFont.pathForGlyph(glyph);
// need bounding rect in base font size scale
qreal scaleFactor = qreal(1) / QT_DISTANCEFIELD_SCALE(m_doubleGlyphResolution);
QTransform scaleDown;
scaleDown.scale(scaleFactor, scaleFactor);
gd.boundingRect = scaleDown.mapRect(gd.path.boundingRect());
- data = m_glyphsData.insert(glyph, gd);
+ return gd;
}
return data.value();
}
@@ -234,10 +241,8 @@ void QSGDistanceFieldGlyphCache::setGlyphsPosition(const QList<GlyphPosition> &g
}
if (!invalidatedGlyphs.isEmpty()) {
- QLinkedList<QSGDistanceFieldGlyphConsumer *>::iterator it = m_registeredNodes.begin();
- while (it != m_registeredNodes.end()) {
- (*it)->invalidateGlyphs(invalidatedGlyphs);
- ++it;
+ for (QSGDistanceFieldGlyphConsumerList::iterator iter = m_registeredNodes.begin(); iter != m_registeredNodes.end(); ++iter) {
+ iter->invalidateGlyphs(invalidatedGlyphs);
}
}
}
@@ -280,10 +285,8 @@ void QSGDistanceFieldGlyphCache::setGlyphsTexture(const QVector<glyph_t> &glyphs
}
if (!invalidatedGlyphs.isEmpty()) {
- QLinkedList<QSGDistanceFieldGlyphConsumer*>::iterator it = m_registeredNodes.begin();
- while (it != m_registeredNodes.end()) {
- (*it)->invalidateGlyphs(invalidatedGlyphs);
- ++it;
+ for (QSGDistanceFieldGlyphConsumerList::iterator iter = m_registeredNodes.begin(); iter != m_registeredNodes.end(); ++iter) {
+ iter->invalidateGlyphs(invalidatedGlyphs);
}
}
}
diff --git a/src/quick/scenegraph/qsgadaptationlayer_p.h b/src/quick/scenegraph/qsgadaptationlayer_p.h
index 9c88b8272c..ba5c4353b2 100644
--- a/src/quick/scenegraph/qsgadaptationlayer_p.h
+++ b/src/quick/scenegraph/qsgadaptationlayer_p.h
@@ -64,6 +64,7 @@
#include <QtGui/private/qdatabuffer_p.h>
#include <private/qopenglcontext_p.h>
#include <private/qdistancefield_p.h>
+#include <private/qintrusivelist_p.h>
// ### remove
#include <QtQuick/private/qquicktext_p.h>
@@ -82,6 +83,7 @@ class QSGGlyphNode;
class QSGRootNode;
class QSGSpriteNode;
class QSGRenderNode;
+class QSGRenderContext;
class Q_QUICK_PRIVATE_EXPORT QSGNodeVisitorEx
{
@@ -136,6 +138,7 @@ public:
virtual void setPenColor(const QColor &color) = 0;
virtual void setPenWidth(qreal width) = 0;
virtual void setGradientStops(const QGradientStops &stops) = 0;
+ virtual void setGradientVertical(bool vertical) = 0;
virtual void setRadius(qreal radius) = 0;
virtual void setAntialiasing(bool antialiasing) { Q_UNUSED(antialiasing) }
virtual void setAligned(bool aligned) = 0;
@@ -403,7 +406,9 @@ public:
virtual ~QSGDistanceFieldGlyphConsumer() {}
virtual void invalidateGlyphs(const QVector<quint32> &glyphs) = 0;
+ QIntrusiveListNode node;
};
+typedef QIntrusiveList<QSGDistanceFieldGlyphConsumer, &QSGDistanceFieldGlyphConsumer::node> QSGDistanceFieldGlyphConsumerList;
class Q_QUICK_PRIVATE_EXPORT QSGDistanceFieldGlyphCache
{
@@ -464,8 +469,8 @@ public:
void update();
- void registerGlyphNode(QSGDistanceFieldGlyphConsumer *node) { m_registeredNodes.append(node); }
- void unregisterGlyphNode(QSGDistanceFieldGlyphConsumer *node) { m_registeredNodes.removeOne(node); }
+ void registerGlyphNode(QSGDistanceFieldGlyphConsumer *node) { m_registeredNodes.insert(node); }
+ void unregisterGlyphNode(QSGDistanceFieldGlyphConsumer *node) { m_registeredNodes.remove(node); }
virtual void registerOwnerElement(QQuickItem *ownerElement);
virtual void unregisterOwnerElement(QQuickItem *ownerElement);
@@ -503,6 +508,7 @@ protected:
uint textureIdForGlyph(glyph_t glyph) const;
GlyphData &glyphData(glyph_t glyph);
+ GlyphData &emptyData(glyph_t glyph);
#if defined(QSG_DISTANCEFIELD_CACHE_DEBUG)
void saveTexture(GLuint textureId, int width, int height) const;
@@ -510,18 +516,21 @@ protected:
inline bool isCoreProfile() const { return m_coreProfile; }
-private:
+ bool m_doubleGlyphResolution;
+
+protected:
QRawFont m_referenceFont;
+
+private:
int m_glyphCount;
- bool m_doubleGlyphResolution;
bool m_coreProfile;
QList<Texture> m_textures;
QHash<glyph_t, GlyphData> m_glyphsData;
QDataBuffer<glyph_t> m_pendingGlyphs;
QSet<glyph_t> m_populatingGlyphs;
- QLinkedList<QSGDistanceFieldGlyphConsumer*> m_registeredNodes;
+ QSGDistanceFieldGlyphConsumerList m_registeredNodes;
static Texture s_emptyTexture;
};
diff --git a/src/quick/scenegraph/qsgbasicinternalimagenode.cpp b/src/quick/scenegraph/qsgbasicinternalimagenode.cpp
index 4effaa154d..03b48b4b8a 100644
--- a/src/quick/scenegraph/qsgbasicinternalimagenode.cpp
+++ b/src/quick/scenegraph/qsgbasicinternalimagenode.cpp
@@ -487,7 +487,7 @@ void QSGBasicInternalImageNode::updateGeometry()
int hTiles = ceilRight - floorLeft;
int vTiles = ceilBottom - floorTop;
- bool hasTiles = hTiles != 1 || vTiles != 1;
+ bool hasTiles = hTiles > 1 || vTiles > 1;
bool fullTexture = innerSourceRect == QRectF(0, 0, 1, 1);
// An image can be rendered as a single quad if:
diff --git a/src/quick/scenegraph/qsgbasicinternalrectanglenode.cpp b/src/quick/scenegraph/qsgbasicinternalrectanglenode.cpp
index df124cce35..91317ee2d7 100644
--- a/src/quick/scenegraph/qsgbasicinternalrectanglenode.cpp
+++ b/src/quick/scenegraph/qsgbasicinternalrectanglenode.cpp
@@ -68,19 +68,30 @@ namespace
{
float x, y;
Color4ub color;
- void set(float nx, float ny, Color4ub ncolor)
+
+ void set(float primary, float secondary, Color4ub ncolor, bool vertical)
{
- x = nx; y = ny; color = ncolor;
+ if (vertical) {
+ x = secondary; y = primary;
+ } else {
+ x = primary; y = secondary;
+ }
+ color = ncolor;
}
};
struct SmoothVertex : public Vertex
{
float dx, dy;
- void set(float nx, float ny, Color4ub ncolor, float ndx, float ndy)
+
+ void set(float primary, float secondary, Color4ub ncolor, float dPrimary, float dSecondary, bool vertical)
{
- Vertex::set(nx, ny, ncolor);
- dx = ndx; dy = ndy;
+ Vertex::set(primary, secondary, ncolor, vertical);
+ if (vertical) {
+ dx = dSecondary; dy = dPrimary;
+ } else {
+ dx = dPrimary; dy = dSecondary;
+ }
}
};
@@ -103,6 +114,7 @@ QSGBasicInternalRectangleNode::QSGBasicInternalRectangleNode()
, m_antialiasing(false)
, m_gradient_is_opaque(true)
, m_dirty_geometry(false)
+ , m_gradient_is_vertical(true)
, m_geometry(QSGGeometry::defaultAttributes_ColoredPoint2D(), 0)
{
setGeometry(&m_geometry);
@@ -160,6 +172,15 @@ void QSGBasicInternalRectangleNode::setGradientStops(const QGradientStops &stops
m_dirty_geometry = true;
}
+void QSGBasicInternalRectangleNode::setGradientVertical(bool vertical)
+{
+ if (vertical == m_gradient_is_vertical)
+ return;
+ m_gradient_is_vertical = vertical;
+ m_dirty_geometry = true;
+}
+
+
void QSGBasicInternalRectangleNode::setRadius(qreal radius)
{
if (radius == m_radius)
@@ -230,12 +251,15 @@ void QSGBasicInternalRectangleNode::updateGeometry()
Color4ub transparent = { 0, 0, 0, 0 };
const QGradientStops &stops = m_gradient_stops;
+ float length = (m_gradient_is_vertical ? height : width);
+ float secondaryLength = (m_gradient_is_vertical ? width : height);
+
int nextGradientStop = 0;
- float gradientPos = penWidth / height;
+ float gradientPos = penWidth / length;
while (nextGradientStop < stops.size() && stops.at(nextGradientStop).first <= gradientPos)
++nextGradientStop;
int lastGradientStop = stops.size() - 1;
- float lastGradientPos = 1.0f - penWidth / height;
+ float lastGradientPos = 1.0f - penWidth / length;
while (lastGradientStop >= nextGradientStop && stops.at(lastGradientStop).first >= lastGradientPos)
--lastGradientStop;
int gradientIntersections = (lastGradientStop - nextGradientStop + 1);
@@ -319,40 +343,46 @@ void QSGBasicInternalRectangleNode::updateGeometry()
quint16 *indices = g->indexDataAsUShort();
quint16 index = 0;
- float py = 0; // previous inner y-coordinate.
- float plx = 0; // previous inner left x-coordinate.
- float prx = 0; // previous inner right x-coordinate.
+ float pp = 0; // previous inner primary coordinate.
+ float pss = 0; // previous inner secondary start coordinate.
+ float pse = 0; // previous inner secondary end coordinate.
float angle = 0.5f * float(M_PI) / segments;
float cosStep = qFastCos(angle);
float sinStep = qFastSin(angle);
+ float innerStart = (m_gradient_is_vertical ? innerRect.top() : innerRect.left());
+ float innerEnd = (m_gradient_is_vertical ? innerRect.bottom() : innerRect.right());
+ float innerLength = (m_gradient_is_vertical ? innerRect.height() : innerRect.width());
+ float innerSecondaryStart = (m_gradient_is_vertical ? innerRect.left() : innerRect.top());
+ float innerSecondaryEnd = (m_gradient_is_vertical ? innerRect.right() : innerRect.bottom());
+
for (int part = 0; part < 2; ++part) {
float c = 1 - part;
float s = part;
for (int i = 0; i <= segments; ++i) {
- float y, lx, rx;
+ float p, ss, se;
if (innerRadius > 0) {
- y = (part ? innerRect.bottom() : innerRect.top()) - innerRadius * c; // current inner y-coordinate.
- lx = innerRect.left() - innerRadius * s; // current inner left x-coordinate.
- rx = innerRect.right() + innerRadius * s; // current inner right x-coordinate.
- gradientPos = ((part ? innerRect.height() : 0) + radius - innerRadius * c) / height;
+ p = (part ? innerEnd : innerStart) - innerRadius * c; // current inner primary coordinate.
+ ss = innerSecondaryStart - innerRadius * s; // current inner secondary start coordinate.
+ se = innerSecondaryEnd + innerRadius * s; // current inner secondary end coordinate.
+ gradientPos = ((part ? innerLength : 0) + radius - innerRadius * c) / length;
} else {
- y = (part ? innerRect.bottom() + innerRadius : innerRect.top() - innerRadius); // current inner y-coordinate.
- lx = innerRect.left() - innerRadius; // current inner left x-coordinate.
- rx = innerRect.right() + innerRadius; // current inner right x-coordinate.
- gradientPos = ((part ? innerRect.height() + innerRadius : -innerRadius) + radius) / height;
+ p = (part ? innerEnd + innerRadius : innerStart - innerRadius); // current inner primary coordinate.
+ ss = innerSecondaryStart - innerRadius; // current inner secondary start coordinate.
+ se = innerSecondaryEnd + innerRadius; // current inner secondary end coordinate.
+ gradientPos = ((part ? innerLength + innerRadius : -innerRadius) + radius) / length;
}
- float Y = (part ? innerRect.bottom() : innerRect.top()) - outerRadius * c; // current outer y-coordinate.
- float lX = innerRect.left() - outerRadius * s; // current outer left x-coordinate.
- float rX = innerRect.right() + outerRadius * s; // current outer right x-coordinate.
+ float outerEdge = (part ? innerEnd : innerStart) - outerRadius * c; // current outer primary coordinate.
+ float outerSecondaryStart = innerSecondaryStart - outerRadius * s; // current outer secondary start coordinate.
+ float outerSecondaryEnd = innerSecondaryEnd + outerRadius * s; // current outer secondary end coordinate.
while (nextGradientStop <= lastGradientStop && stops.at(nextGradientStop).first <= gradientPos) {
// Insert vertices at gradient stops.
- float gy = (innerRect.top() - radius) + stops.at(nextGradientStop).first * height;
- float t = (gy - py) / (y - py);
- float glx = plx * (1 - t) + t * lx;
- float grx = prx * (1 - t) + t * rx;
+ float gp = (innerStart - radius) + stops.at(nextGradientStop).first * length;
+ float t = (gp - pp) / (p - pp);
+ float gis = pss * (1 - t) + t * ss; // gradient inner start
+ float gie = pse * (1 - t) + t * se; // gradient inner end
fillColor = colorToColor4ub(stops.at(nextGradientStop).second);
@@ -377,23 +407,23 @@ void QSGBasicInternalRectangleNode::updateGeometry()
indices[innerAATail++] = index + 3;
bool lower = stops.at(nextGradientStop).first > 0.5f;
- float dy = lower ? qMin(0.0f, height - gy - delta) : qMax(0.0f, delta - gy);
- smoothVertices[index++].set(grx, gy, fillColor, width - grx - delta, dy);
- smoothVertices[index++].set(glx, gy, fillColor, delta - glx, dy);
+ float dp = lower ? qMin(0.0f, length - gp - delta) : qMax(0.0f, delta - gp);
+ smoothVertices[index++].set(gp, gie, fillColor, dp, secondaryLength - gie - delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, gis, fillColor, dp, delta - gis, m_gradient_is_vertical);
if (penWidth) {
- smoothVertices[index++].set(grx, gy, borderColor, 0.49f * penWidth * s, -0.49f * penWidth * c);
- smoothVertices[index++].set(glx, gy, borderColor, -0.49f * penWidth * s, -0.49f * penWidth * c);
+ smoothVertices[index++].set(gp, gie, borderColor, -0.49f * penWidth * c, 0.49f * penWidth * s, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, gis, borderColor, -0.49f * penWidth * c, -0.49f * penWidth * s, m_gradient_is_vertical);
} else {
- dy = lower ? delta : -delta;
- smoothVertices[index++].set(grx, gy, transparent, delta, dy);
- smoothVertices[index++].set(glx, gy, transparent, -delta, dy);
+ dp = lower ? delta : -delta;
+ smoothVertices[index++].set(gp, gie, transparent, dp, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, gis, transparent, dp, -delta, m_gradient_is_vertical);
}
} else {
- vertices[index++].set(grx, gy, fillColor);
- vertices[index++].set(glx, gy, fillColor);
+ vertices[index++].set(gp, gie, fillColor, m_gradient_is_vertical);
+ vertices[index++].set(gp, gis, fillColor, m_gradient_is_vertical);
if (penWidth) {
- vertices[index++].set(grx, gy, borderColor);
- vertices[index++].set(glx, gy, borderColor);
+ vertices[index++].set(gp, gie, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(gp, gis, borderColor, m_gradient_is_vertical);
}
}
++nextGradientStop;
@@ -430,41 +460,41 @@ void QSGBasicInternalRectangleNode::updateGeometry()
indices[innerAATail++] = index + 1;
indices[innerAATail++] = index + 3;
- float dy = part ? qMin(0.0f, height - y - delta) : qMax(0.0f, delta - y);
- smoothVertices[index++].set(rx, y, fillColor, width - rx - delta, dy);
- smoothVertices[index++].set(lx, y, fillColor, delta - lx, dy);
+ float dp = part ? qMin(0.0f, length - p - delta) : qMax(0.0f, delta - p);
+ smoothVertices[index++].set(p, se, fillColor, dp, secondaryLength - se - delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(p, ss, fillColor, dp, delta - ss, m_gradient_is_vertical);
- dy = part ? delta : -delta;
+ dp = part ? delta : -delta;
if (penWidth) {
- smoothVertices[index++].set(rx, y, borderColor, 0.49f * penWidth * s, -0.49f * penWidth * c);
- smoothVertices[index++].set(lx, y, borderColor, -0.49f * penWidth * s, -0.49f * penWidth * c);
- smoothVertices[index++].set(rX, Y, borderColor, -0.49f * penWidth * s, 0.49f * penWidth * c);
- smoothVertices[index++].set(lX, Y, borderColor, 0.49f * penWidth * s, 0.49f * penWidth * c);
- smoothVertices[index++].set(rX, Y, transparent, delta, dy);
- smoothVertices[index++].set(lX, Y, transparent, -delta, dy);
+ smoothVertices[index++].set(p, se, borderColor, -0.49f * penWidth * c, 0.49f * penWidth * s, m_gradient_is_vertical);
+ smoothVertices[index++].set(p, ss, borderColor, -0.49f * penWidth * c, -0.49f * penWidth * s, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryEnd, borderColor, 0.49f * penWidth * c, -0.49f * penWidth * s, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryStart, borderColor, 0.49f * penWidth * c, 0.49f * penWidth * s, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryEnd, transparent, dp, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryStart, transparent, dp, -delta, m_gradient_is_vertical);
indices[--outerAAHead] = index - 2;
indices[--outerAAHead] = index - 4;
indices[outerAATail++] = index - 3;
indices[outerAATail++] = index - 1;
} else {
- smoothVertices[index++].set(rx, y, transparent, delta, dy);
- smoothVertices[index++].set(lx, y, transparent, -delta, dy);
+ smoothVertices[index++].set(p, se, transparent, dp, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(p, ss, transparent, dp, -delta, m_gradient_is_vertical);
}
} else {
- vertices[index++].set(rx, y, fillColor);
- vertices[index++].set(lx, y, fillColor);
+ vertices[index++].set(p, se, fillColor, m_gradient_is_vertical);
+ vertices[index++].set(p, ss, fillColor, m_gradient_is_vertical);
if (penWidth) {
- vertices[index++].set(rx, y, borderColor);
- vertices[index++].set(lx, y, borderColor);
- vertices[index++].set(rX, Y, borderColor);
- vertices[index++].set(lX, Y, borderColor);
+ vertices[index++].set(p, se, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(p, ss, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(outerEdge, outerSecondaryEnd, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(outerEdge, outerSecondaryStart, borderColor, m_gradient_is_vertical);
}
}
- py = y;
- plx = lx;
- prx = rx;
+ pp = p;
+ pss = ss;
+ pse = se;
// Rotate
qreal tmp = c;
@@ -543,19 +573,24 @@ void QSGBasicInternalRectangleNode::updateGeometry()
quint16 *indices = g->indexDataAsUShort();
quint16 index = 0;
- float lx = innerRect.left();
- float rx = innerRect.right();
- float lX = outerRect.left();
- float rX = outerRect.right();
+ float innerStart = (m_gradient_is_vertical ? innerRect.top() : innerRect.left());
+ float innerEnd = (m_gradient_is_vertical ? innerRect.bottom() : innerRect.right());
+ float outerStart = (m_gradient_is_vertical ? outerRect.top() : outerRect.left());
+ float outerEnd = (m_gradient_is_vertical ? outerRect.bottom() : outerRect.right());
+
+ float innerSecondaryStart = (m_gradient_is_vertical ? innerRect.left() : innerRect.top());
+ float innerSecondaryEnd = (m_gradient_is_vertical ? innerRect.right() : innerRect.bottom());
+ float outerSecondaryStart = (m_gradient_is_vertical ? outerRect.left() : outerRect.top());
+ float outerSecondaryEnd = (m_gradient_is_vertical ? outerRect.right() : outerRect.bottom());
for (int part = -1; part <= 1; part += 2) {
- float y = (part == 1 ? innerRect.bottom() : innerRect.top());
- float Y = (part == 1 ? outerRect.bottom() : outerRect.top());
- gradientPos = (y - innerRect.top() + penWidth) / height;
+ float innerEdge = (part == 1 ? innerEnd : innerStart);
+ float outerEdge = (part == 1 ? outerEnd : outerStart);
+ gradientPos = (innerEdge - innerStart + penWidth) / length;
while (nextGradientStop <= lastGradientStop && stops.at(nextGradientStop).first <= gradientPos) {
// Insert vertices at gradient stops.
- float gy = (innerRect.top() - penWidth) + stops.at(nextGradientStop).first * height;
+ float gp = (innerStart - penWidth) + stops.at(nextGradientStop).first * length;
fillColor = colorToColor4ub(stops.at(nextGradientStop).second);
@@ -580,22 +615,22 @@ void QSGBasicInternalRectangleNode::updateGeometry()
indices[innerAATail++] = index + 3;
bool lower = stops.at(nextGradientStop).first > 0.5f;
- float dy = lower ? qMin(0.0f, height - gy - delta) : qMax(0.0f, delta - gy);
- smoothVertices[index++].set(rx, gy, fillColor, width - rx - delta, dy);
- smoothVertices[index++].set(lx, gy, fillColor, delta - lx, dy);
+ float dp = lower ? qMin(0.0f, length - gp - delta) : qMax(0.0f, delta - gp);
+ smoothVertices[index++].set(gp, innerSecondaryEnd, fillColor, dp, secondaryLength - innerSecondaryEnd - delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, innerSecondaryStart, fillColor, dp, delta - innerSecondaryStart, m_gradient_is_vertical);
if (penWidth) {
- smoothVertices[index++].set(rx, gy, borderColor, 0.49f * penWidth, (lower ? 0.49f : -0.49f) * penWidth);
- smoothVertices[index++].set(lx, gy, borderColor, -0.49f * penWidth, (lower ? 0.49f : -0.49f) * penWidth);
+ smoothVertices[index++].set(gp, innerSecondaryEnd, borderColor, (lower ? 0.49f : -0.49f) * penWidth, 0.49f * penWidth, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, innerSecondaryStart, borderColor, (lower ? 0.49f : -0.49f) * penWidth, -0.49f * penWidth, m_gradient_is_vertical);
} else {
- smoothVertices[index++].set(rx, gy, transparent, delta, lower ? delta : -delta);
- smoothVertices[index++].set(lx, gy, transparent, -delta, lower ? delta : -delta);
+ smoothVertices[index++].set(gp, innerSecondaryEnd, transparent, lower ? delta : -delta, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(gp, innerSecondaryStart, transparent, lower ? delta : -delta, -delta, m_gradient_is_vertical);
}
} else {
- vertices[index++].set(rx, gy, fillColor);
- vertices[index++].set(lx, gy, fillColor);
+ vertices[index++].set(gp, innerSecondaryEnd, fillColor, m_gradient_is_vertical);
+ vertices[index++].set(gp, innerSecondaryStart, fillColor, m_gradient_is_vertical);
if (penWidth) {
- vertices[index++].set(rx, gy, borderColor);
- vertices[index++].set(lx, gy, borderColor);
+ vertices[index++].set(gp, innerSecondaryEnd, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(gp, innerSecondaryStart, borderColor, m_gradient_is_vertical);
}
}
++nextGradientStop;
@@ -632,34 +667,34 @@ void QSGBasicInternalRectangleNode::updateGeometry()
indices[innerAATail++] = index + 1;
indices[innerAATail++] = index + 3;
- float dy = part == 1 ? qMin(0.0f, height - y - delta) : qMax(0.0f, delta - y);
- smoothVertices[index++].set(rx, y, fillColor, width - rx - delta, dy);
- smoothVertices[index++].set(lx, y, fillColor, delta - lx, dy);
+ float dp = part == 1 ? qMin(0.0f, length - innerEdge - delta) : qMax(0.0f, delta - innerEdge);
+ smoothVertices[index++].set(innerEdge, innerSecondaryEnd, fillColor, dp, secondaryLength - innerSecondaryEnd - delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(innerEdge, innerSecondaryStart, fillColor, dp, delta - innerSecondaryStart, m_gradient_is_vertical);
if (penWidth) {
- smoothVertices[index++].set(rx, y, borderColor, 0.49f * penWidth, 0.49f * penWidth * part);
- smoothVertices[index++].set(lx, y, borderColor, -0.49f * penWidth, 0.49f * penWidth * part);
- smoothVertices[index++].set(rX, Y, borderColor, -0.49f * penWidth, -0.49f * penWidth * part);
- smoothVertices[index++].set(lX, Y, borderColor, 0.49f * penWidth, -0.49f * penWidth * part);
- smoothVertices[index++].set(rX, Y, transparent, delta, delta * part);
- smoothVertices[index++].set(lX, Y, transparent, -delta, delta * part);
+ smoothVertices[index++].set(innerEdge, innerSecondaryEnd, borderColor, 0.49f * penWidth * part, 0.49f * penWidth, m_gradient_is_vertical);
+ smoothVertices[index++].set(innerEdge, innerSecondaryStart, borderColor, 0.49f * penWidth * part, -0.49f * penWidth, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryEnd, borderColor, -0.49f * penWidth * part, -0.49f * penWidth, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryStart, borderColor, -0.49f * penWidth * part, 0.49f * penWidth, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryEnd, transparent, delta * part, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(outerEdge, outerSecondaryStart, transparent, delta * part, -delta, m_gradient_is_vertical);
indices[--outerAAHead] = index - 2;
indices[--outerAAHead] = index - 4;
indices[outerAATail++] = index - 3;
indices[outerAATail++] = index - 1;
} else {
- smoothVertices[index++].set(rx, y, transparent, delta, delta * part);
- smoothVertices[index++].set(lx, y, transparent, -delta, delta * part);
+ smoothVertices[index++].set(innerEdge, innerSecondaryEnd, transparent, delta * part, delta, m_gradient_is_vertical);
+ smoothVertices[index++].set(innerEdge, innerSecondaryStart, transparent, delta * part, -delta, m_gradient_is_vertical);
}
} else {
- vertices[index++].set(rx, y, fillColor);
- vertices[index++].set(lx, y, fillColor);
+ vertices[index++].set(innerEdge, innerSecondaryEnd, fillColor, m_gradient_is_vertical);
+ vertices[index++].set(innerEdge, innerSecondaryStart, fillColor, m_gradient_is_vertical);
if (penWidth) {
- vertices[index++].set(rx, y, borderColor);
- vertices[index++].set(lx, y, borderColor);
- vertices[index++].set(rX, Y, borderColor);
- vertices[index++].set(lX, Y, borderColor);
+ vertices[index++].set(innerEdge, innerSecondaryEnd, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(innerEdge, innerSecondaryStart, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(outerEdge, outerSecondaryEnd, borderColor, m_gradient_is_vertical);
+ vertices[index++].set(outerEdge, outerSecondaryStart, borderColor, m_gradient_is_vertical);
}
}
}
diff --git a/src/quick/scenegraph/qsgbasicinternalrectanglenode_p.h b/src/quick/scenegraph/qsgbasicinternalrectanglenode_p.h
index 98e53669ce..99f26b9aed 100644
--- a/src/quick/scenegraph/qsgbasicinternalrectanglenode_p.h
+++ b/src/quick/scenegraph/qsgbasicinternalrectanglenode_p.h
@@ -66,6 +66,7 @@ public:
void setPenColor(const QColor &color) override;
void setPenWidth(qreal width) override;
void setGradientStops(const QGradientStops &stops) override;
+ void setGradientVertical(bool vertical) override;
void setRadius(qreal radius) override;
void setAntialiasing(bool antialiasing) override;
void setAligned(bool aligned) override;
@@ -90,6 +91,7 @@ protected:
uint m_antialiasing : 1;
uint m_gradient_is_opaque : 1;
uint m_dirty_geometry : 1;
+ uint m_gradient_is_vertical : 1;
QSGGeometry m_geometry;
};
diff --git a/src/quick/scenegraph/qsgcontextplugin.cpp b/src/quick/scenegraph/qsgcontextplugin.cpp
index 628619fa46..66add51c55 100644
--- a/src/quick/scenegraph/qsgcontextplugin.cpp
+++ b/src/quick/scenegraph/qsgcontextplugin.cpp
@@ -73,6 +73,8 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
struct QSGAdaptationBackendData
{
QSGAdaptationBackendData();
+ ~QSGAdaptationBackendData();
+ Q_DISABLE_COPY(QSGAdaptationBackendData)
bool tried = false;
QSGContextFactoryInterface *factory = nullptr;
@@ -91,6 +93,11 @@ QSGAdaptationBackendData::QSGAdaptationBackendData()
builtIns.append(new QSGSoftwareAdaptation);
}
+QSGAdaptationBackendData::~QSGAdaptationBackendData()
+{
+ qDeleteAll(builtIns);
+}
+
Q_GLOBAL_STATIC(QSGAdaptationBackendData, qsg_adaptation_data)
// This only works when the backend is loaded (contextFactory() was called),
diff --git a/src/quick/scenegraph/qsgdefaultcontext.cpp b/src/quick/scenegraph/qsgdefaultcontext.cpp
index 9a0ac66690..1124bf1727 100644
--- a/src/quick/scenegraph/qsgdefaultcontext.cpp
+++ b/src/quick/scenegraph/qsgdefaultcontext.cpp
@@ -290,3 +290,10 @@ QSGRendererInterface::ShaderSourceTypes QSGDefaultContext::shaderSourceType() co
}
QT_END_NAMESPACE
+
+static void initResources()
+{
+ Q_INIT_RESOURCE(scenegraph);
+}
+
+Q_CONSTRUCTOR_FUNCTION(initResources)
diff --git a/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp b/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp
index ef189ba461..ccc57b0b86 100644
--- a/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp
+++ b/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache.cpp
@@ -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 QtQuick module of the Qt Toolkit.
@@ -39,12 +39,18 @@
#include "qsgdefaultdistancefieldglyphcache_p.h"
+#include <QtCore/qelapsedtimer.h>
+#include <QtCore/qbuffer.h>
+#include <QtQml/qqmlfile.h>
+
#include <QtGui/private/qdistancefield_p.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <QtQml/private/qqmlglobal_p.h>
#include <qopenglfunctions.h>
#include <qopenglframebufferobject.h>
#include <qmath.h>
+#include "qsgcontext_p.h"
+
#if !defined(QT_OPENGL_ES_2)
#include <QtGui/qopenglfunctions_3_2_core.h>
@@ -59,10 +65,12 @@ DEFINE_BOOL_CONFIG_OPTION(qsgPreferFullSizeGlyphCacheTextures, QSG_PREFER_FULLSI
# define QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING 2
#endif
-QSGDefaultDistanceFieldGlyphCache::QSGDefaultDistanceFieldGlyphCache(QOpenGLContext *c, const QRawFont &font)
+QSGDefaultDistanceFieldGlyphCache::QSGDefaultDistanceFieldGlyphCache(QOpenGLContext *c,
+ const QRawFont &font)
: QSGDistanceFieldGlyphCache(c, font)
, m_maxTextureSize(0)
, m_maxTextureCount(3)
+ , m_areaAllocator(nullptr)
, m_blitProgram(nullptr)
, m_blitBuffer(QOpenGLBuffer::VertexBuffer)
, m_fboGuard(nullptr)
@@ -81,7 +89,8 @@ QSGDefaultDistanceFieldGlyphCache::QSGDefaultDistanceFieldGlyphCache(QOpenGLCont
qWarning("Buffer creation failed");
}
- m_areaAllocator = new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()));
+ // Load a pregenerated cache if the font contains one
+ loadPregeneratedCache(font);
}
QSGDefaultDistanceFieldGlyphCache::~QSGDefaultDistanceFieldGlyphCache()
@@ -101,6 +110,9 @@ void QSGDefaultDistanceFieldGlyphCache::requestGlyphs(const QSet<glyph_t> &glyph
QList<GlyphPosition> glyphPositions;
QVector<glyph_t> glyphsToRender;
+ if (m_areaAllocator == nullptr)
+ m_areaAllocator = new QSGAreaAllocator(QSize(maxTextureSize(), m_maxTextureCount * maxTextureSize()));
+
for (QSet<glyph_t>::const_iterator it = glyphs.constBegin(); it != glyphs.constEnd() ; ++it) {
glyph_t glyphIndex = *it;
@@ -237,10 +249,23 @@ void QSGDefaultDistanceFieldGlyphCache::releaseGlyphs(const QSet<glyph_t> &glyph
m_unusedGlyphs += glyphs;
}
-void QSGDefaultDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo, int width, int height)
+void QSGDefaultDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
+ int width,
+ int height)
+{
+ QByteArray zeroBuf(width * height, 0);
+ createTexture(texInfo, width, height, zeroBuf.constData());
+}
+
+void QSGDefaultDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo,
+ int width,
+ int height,
+ const void *pixels)
{
- if (useTextureResizeWorkaround() && texInfo->image.isNull())
+ if (useTextureResizeWorkaround() && texInfo->image.isNull()) {
texInfo->image = QDistanceField(width, height);
+ memcpy(texInfo->image.bits(), pixels, width * height);
+ }
while (m_funcs->glGetError() != GL_NO_ERROR) { }
@@ -261,8 +286,7 @@ void QSGDefaultDistanceFieldGlyphCache::createTexture(TextureInfo *texInfo, int
const GLenum format = GL_ALPHA;
#endif
- QByteArray zeroBuf(width * height, 0);
- m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, zeroBuf.constData());
+ m_funcs->glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);
texInfo->size = QSize(width, height);
@@ -520,4 +544,261 @@ int QSGDefaultDistanceFieldGlyphCache::maxTextureSize() const
return m_maxTextureSize;
}
+namespace {
+ struct Qtdf {
+ // We need these structs to be tightly packed, but some compilers we use do not
+ // support #pragma pack(1), so we need to hardcode the offsets/sizes in the
+ // file format
+ enum TableSize {
+ HeaderSize = 14,
+ GlyphRecordSize = 46,
+ TextureRecordSize = 17
+ };
+
+ enum Offset {
+ // Header
+ majorVersion = 0,
+ minorVersion = 1,
+ pixelSize = 2,
+ textureSize = 4,
+ flags = 8,
+ headerPadding = 9,
+ numGlyphs = 10,
+
+ // Glyph record
+ glyphIndex = 0,
+ textureOffsetX = 4,
+ textureOffsetY = 8,
+ textureWidth = 12,
+ textureHeight = 16,
+ xMargin = 20,
+ yMargin = 24,
+ boundingRectX = 28,
+ boundingRectY = 32,
+ boundingRectWidth = 36,
+ boundingRectHeight = 40,
+ textureIndex = 44,
+
+ // Texture record
+ allocatedX = 0,
+ allocatedY = 4,
+ allocatedWidth = 8,
+ allocatedHeight = 12,
+ texturePadding = 16
+
+ };
+
+ template <typename T>
+ static inline T fetch(const char *data, Offset offset)
+ {
+ return qFromBigEndian<T>(data + int(offset));
+ }
+ };
+}
+
+bool QSGDefaultDistanceFieldGlyphCache::loadPregeneratedCache(const QRawFont &font)
+{
+ // The pregenerated data must be loaded first, otherwise the area allocator
+ // will be wrong
+ if (m_areaAllocator != nullptr) {
+ qWarning("Font cache must be loaded before cache is used");
+ return false;
+ }
+
+ static QElapsedTimer timer;
+
+ bool profile = QSG_LOG_TIME_GLYPH().isDebugEnabled();
+ if (profile)
+ timer.start();
+
+ QByteArray qtdfTable = font.fontTable("qtdf");
+ if (qtdfTable.isEmpty())
+ return false;
+
+ typedef QHash<TextureInfo *, QVector<glyph_t> > GlyphTextureHash;
+
+ GlyphTextureHash glyphTextures;
+
+ if (uint(qtdfTable.size()) < Qtdf::HeaderSize) {
+ qWarning("Invalid qtdf table in font '%s'",
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+ const char *qtdfTableStart = qtdfTable.constData();
+ const char *qtdfTableEnd = qtdfTableStart + qtdfTable.size();
+
+ int padding = 0;
+ int textureCount = 0;
+ {
+ quint8 majorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::majorVersion);
+ quint8 minorVersion = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::minorVersion);
+ if (majorVersion != 5 || minorVersion != 12) {
+ qWarning("Invalid version of qtdf table %d.%d in font '%s'",
+ majorVersion,
+ minorVersion,
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+ qreal pixelSize = qreal(Qtdf::fetch<quint16>(qtdfTableStart, Qtdf::pixelSize));
+ m_maxTextureSize = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::textureSize);
+ m_doubleGlyphResolution = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::flags) == 1;
+ padding = Qtdf::fetch<quint8>(qtdfTableStart, Qtdf::headerPadding);
+
+ if (pixelSize <= 0.0) {
+ qWarning("Invalid pixel size in '%s'", qPrintable(font.familyName()));
+ return false;
+ }
+
+ if (m_maxTextureSize <= 0) {
+ qWarning("Invalid texture size in '%s'", qPrintable(font.familyName()));
+ return false;
+ }
+
+ int systemMaxTextureSize;
+ m_funcs->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &systemMaxTextureSize);
+
+ if (m_maxTextureSize > systemMaxTextureSize) {
+ qWarning("System maximum texture size is %d. This is lower than the value in '%s', which is %d",
+ systemMaxTextureSize,
+ qPrintable(font.familyName()),
+ m_maxTextureSize);
+ }
+
+ if (padding != QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING) {
+ qWarning("Padding mismatch in '%s'. Font requires %d, but Qt is compiled with %d.",
+ qPrintable(font.familyName()),
+ padding,
+ QSG_DEFAULT_DISTANCEFIELD_GLYPH_CACHE_PADDING);
+ }
+
+ m_referenceFont.setPixelSize(pixelSize);
+
+ quint32 glyphCount = Qtdf::fetch<quint32>(qtdfTableStart, Qtdf::numGlyphs);
+ m_unusedGlyphs.reserve(glyphCount);
+
+ const char *allocatorData = qtdfTableStart + Qtdf::HeaderSize;
+ {
+ m_areaAllocator = new QSGAreaAllocator(QSize(0, 0));
+ allocatorData = m_areaAllocator->deserialize(allocatorData, qtdfTableEnd - allocatorData);
+ if (allocatorData == nullptr)
+ return false;
+ }
+
+ if (m_areaAllocator->size().height() % m_maxTextureSize != 0) {
+ qWarning("Area allocator size mismatch in '%s'", qPrintable(font.familyName()));
+ return false;
+ }
+
+ textureCount = m_areaAllocator->size().height() / m_maxTextureSize;
+ m_maxTextureCount = qMax(m_maxTextureCount, textureCount);
+
+ const char *textureRecord = allocatorData;
+ for (int i = 0; i < textureCount; ++i, textureRecord += Qtdf::TextureRecordSize) {
+ if (textureRecord + Qtdf::TextureRecordSize > qtdfTableEnd) {
+ qWarning("qtdf table too small in font '%s'.",
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+ TextureInfo *tex = textureInfo(i);
+ tex->allocatedArea.setX(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedX));
+ tex->allocatedArea.setY(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedY));
+ tex->allocatedArea.setWidth(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedWidth));
+ tex->allocatedArea.setHeight(Qtdf::fetch<quint32>(textureRecord, Qtdf::allocatedHeight));
+ tex->padding = Qtdf::fetch<quint8>(textureRecord, Qtdf::texturePadding);
+ }
+
+ const char *glyphRecord = textureRecord;
+ for (quint32 i = 0; i < glyphCount; ++i, glyphRecord += Qtdf::GlyphRecordSize) {
+ if (glyphRecord + Qtdf::GlyphRecordSize > qtdfTableEnd) {
+ qWarning("qtdf table too small in font '%s'.",
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+ glyph_t glyph = Qtdf::fetch<quint32>(glyphRecord, Qtdf::glyphIndex);
+ m_unusedGlyphs.insert(glyph);
+
+ GlyphData &glyphData = emptyData(glyph);
+
+#define FROM_FIXED_POINT(value) \
+(((qreal)value)/(qreal)65536)
+
+ glyphData.texCoord.x = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetX));
+ glyphData.texCoord.y = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureOffsetY));
+ glyphData.texCoord.width = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureWidth));
+ glyphData.texCoord.height = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::textureHeight));
+ glyphData.texCoord.xMargin = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::xMargin));
+ glyphData.texCoord.yMargin = FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::yMargin));
+ glyphData.boundingRect.setX(FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectX)));
+ glyphData.boundingRect.setY(FROM_FIXED_POINT(Qtdf::fetch<qint32>(glyphRecord, Qtdf::boundingRectY)));
+ glyphData.boundingRect.setWidth(FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectWidth)));
+ glyphData.boundingRect.setHeight(FROM_FIXED_POINT(Qtdf::fetch<quint32>(glyphRecord, Qtdf::boundingRectHeight)));
+
+#undef FROM_FIXED_POINT
+
+ int textureIndex = Qtdf::fetch<quint16>(glyphRecord, Qtdf::textureIndex);
+ if (textureIndex < 0 || textureIndex >= textureCount) {
+ qWarning("Invalid texture index %d (texture count == %d) in '%s'",
+ textureIndex,
+ textureCount,
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+
+ TextureInfo *texInfo = textureInfo(textureIndex);
+ m_glyphsTexture.insert(glyph, texInfo);
+
+ glyphTextures[texInfo].append(glyph);
+ }
+
+ GLint alignment = 4; // default value
+ m_funcs->glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
+
+ m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+ const uchar *textureData = reinterpret_cast<const uchar *>(glyphRecord);
+ for (int i = 0; i < textureCount; ++i) {
+
+ TextureInfo *texInfo = textureInfo(i);
+
+ int width = texInfo->allocatedArea.width();
+ int height = texInfo->allocatedArea.height();
+ qint64 size = width * height;
+ if (reinterpret_cast<const char *>(textureData + size) > qtdfTableEnd) {
+ qWarning("qtdf table too small in font '%s'.",
+ qPrintable(font.familyName()));
+ return false;
+ }
+
+ createTexture(texInfo, width, height, textureData);
+
+ QVector<glyph_t> glyphs = glyphTextures.value(texInfo);
+
+ Texture t;
+ t.textureId = texInfo->texture;
+ t.size = texInfo->size;
+
+ setGlyphsTexture(glyphs, t);
+
+ textureData += size;
+ }
+
+ m_funcs->glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
+ }
+
+ if (profile) {
+ quint64 now = timer.elapsed();
+ qCDebug(QSG_LOG_TIME_GLYPH,
+ "distancefield: %d pre-generated glyphs loaded in %dms",
+ m_unusedGlyphs.size(),
+ (int) now);
+ }
+
+ return true;
+}
+
QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache_p.h b/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache_p.h
index 76c0d20647..a0e4387af9 100644
--- a/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache_p.h
+++ b/src/quick/scenegraph/qsgdefaultdistancefieldglyphcache_p.h
@@ -85,7 +85,10 @@ public:
void setMaxTextureCount(int max) { m_maxTextureCount = max; }
int maxTextureCount() const { return m_maxTextureCount; }
+
private:
+ bool loadPregeneratedCache(const QRawFont &font);
+
struct TextureInfo {
GLuint texture;
QSize size;
@@ -96,6 +99,7 @@ private:
TextureInfo(const QRect &preallocRect = QRect()) : texture(0), allocatedArea(preallocRect) { }
};
+ void createTexture(TextureInfo * texInfo, int width, int height, const void *pixels);
void createTexture(TextureInfo * texInfo, int width, int height);
void resizeTexture(TextureInfo * texInfo, int width, int height);
diff --git a/src/quick/scenegraph/qsgdefaultrendercontext.cpp b/src/quick/scenegraph/qsgdefaultrendercontext.cpp
index 22e97a2dc9..73b79c6300 100644
--- a/src/quick/scenegraph/qsgdefaultrendercontext.cpp
+++ b/src/quick/scenegraph/qsgdefaultrendercontext.cpp
@@ -325,7 +325,8 @@ bool QSGDefaultRenderContext::separateIndexBuffer() const
// lifetime. An attempt to bind a buffer object to the other
// target will generate an INVALID_OPERATION error, and the
// current binding will remain untouched.
- static const bool isWebGL = qGuiApp->platformName().compare(QLatin1String("webgl")) == 0;
+ static const bool isWebGL = (qGuiApp->platformName().compare(QLatin1String("webgl")) == 0
+ || qGuiApp->platformName().compare(QLatin1String("wasm")) == 0);
return isWebGL;
}
diff --git a/src/quick/scenegraph/qsgrenderloop.cpp b/src/quick/scenegraph/qsgrenderloop.cpp
index 05f635cf1d..3d579fde46 100644
--- a/src/quick/scenegraph/qsgrenderloop.cpp
+++ b/src/quick/scenegraph/qsgrenderloop.cpp
@@ -221,10 +221,12 @@ QSGRenderLoop *QSGRenderLoop::instance()
}
switch (loopType) {
+#if QT_CONFIG(thread)
case ThreadedRenderLoop:
qCDebug(QSG_LOG_INFO, "threaded render loop");
s_instance = new QSGThreadedRenderLoop();
break;
+#endif
case WindowsRenderLoop:
qCDebug(QSG_LOG_INFO, "windows render loop");
s_instance = new QSGWindowsRenderLoop();
diff --git a/src/quick/scenegraph/scenegraph.pri b/src/quick/scenegraph/scenegraph.pri
index 4f98638487..ddd7fb7f4c 100644
--- a/src/quick/scenegraph/scenegraph.pri
+++ b/src/quick/scenegraph/scenegraph.pri
@@ -115,7 +115,6 @@ qtConfig(opengl(es1|es2)?) {
$$PWD/util/qsgdefaultimagenode.cpp \
$$PWD/util/qsgdefaultninepatchnode.cpp \
$$PWD/qsgdefaultlayer.cpp \
- $$PWD/qsgthreadedrenderloop.cpp \
$$PWD/qsgwindowsrenderloop.cpp
HEADERS += \
$$PWD/qsgdefaultglyphnode_p.h \
@@ -132,9 +131,15 @@ qtConfig(opengl(es1|es2)?) {
$$PWD/util/qsgdefaultimagenode_p.h \
$$PWD/util/qsgdefaultninepatchnode_p.h \
$$PWD/qsgdefaultlayer_p.h \
- $$PWD/qsgthreadedrenderloop_p.h \
$$PWD/qsgwindowsrenderloop_p.h
+ qtConfig(thread) {
+ SOURCES += \
+ $$PWD/qsgthreadedrenderloop.cpp
+ HEADERS += \
+ $$PWD/qsgthreadedrenderloop_p.h
+ }
+
qtConfig(quick-sprite) {
SOURCES += \
$$PWD/qsgdefaultspritenode.cpp
@@ -230,14 +235,9 @@ SOURCES += \
qtConfig(opengl(es1|es2)?) {
HEADERS += \
$$PWD/compressedtexture/qsgcompressedatlastexture_p.h \
- $$PWD/compressedtexture/qsgcompressedtexture_p.h \
- $$PWD/compressedtexture/qsgtexturefilehandler_p.h \
- $$PWD/compressedtexture/qsgpkmhandler_p.h \
- $$PWD/compressedtexture/qsgktxhandler_p.h
+ $$PWD/compressedtexture/qsgcompressedtexture_p.h
SOURCES += \
$$PWD/compressedtexture/qsgcompressedatlastexture.cpp \
- $$PWD/compressedtexture/qsgcompressedtexture.cpp \
- $$PWD/compressedtexture/qsgpkmhandler.cpp \
- $$PWD/compressedtexture/qsgktxhandler.cpp
+ $$PWD/compressedtexture/qsgcompressedtexture.cpp
}
diff --git a/src/quick/scenegraph/util/qsgareaallocator.cpp b/src/quick/scenegraph/util/qsgareaallocator.cpp
index cd270a1d63..9a8c8e333b 100644
--- a/src/quick/scenegraph/util/qsgareaallocator.cpp
+++ b/src/quick/scenegraph/util/qsgareaallocator.cpp
@@ -42,6 +42,9 @@
#include <QtCore/qglobal.h>
#include <QtCore/qrect.h>
#include <QtCore/qpoint.h>
+#include <QtCore/qdatastream.h>
+#include <QtCore/qstack.h>
+#include <QtCore/qendian.h>
QT_BEGIN_NAMESPACE
@@ -285,4 +288,145 @@ void QSGAreaAllocator::mergeNodeWithNeighbors(QSGAreaAllocatorNode *node)
} // end while(!done)
}
+namespace {
+ struct AreaAllocatorTable
+ {
+ enum TableSize {
+ HeaderSize = 10,
+ NodeSize = 9
+ };
+
+ enum Offset {
+ // Header
+ majorVersion = 0,
+ minorVersion = 1,
+ width = 2,
+ height = 6,
+
+ // Node
+ split = 0,
+ splitType = 4,
+ flags = 8
+ };
+
+ enum Flags {
+ IsOccupied = 1,
+ HasLeft = 2,
+ HasRight = 4
+ };
+
+ template <typename T>
+ static inline T fetch(const char *data, Offset offset)
+ {
+ return qFromBigEndian<T>(data + int(offset));
+ }
+
+ template <typename T>
+ static inline void put(char *data, Offset offset, T value)
+ {
+ qToBigEndian(value, data + int(offset));
+ }
+ };
+}
+
+QByteArray QSGAreaAllocator::serialize()
+{
+ QVarLengthArray<QSGAreaAllocatorNode *> nodesToProcess;
+
+ QStack<QSGAreaAllocatorNode *> nodes;
+ nodes.push(m_root);
+ while (!nodes.isEmpty()) {
+ QSGAreaAllocatorNode *node = nodes.pop();
+
+ nodesToProcess.append(node);
+ if (node->left != nullptr)
+ nodes.push(node->left);
+ if (node->right != nullptr)
+ nodes.push(node->right);
+ }
+
+ QByteArray ret;
+ ret.resize(AreaAllocatorTable::HeaderSize + AreaAllocatorTable::NodeSize * nodesToProcess.size());
+
+ char *data = ret.data();
+ AreaAllocatorTable::put(data, AreaAllocatorTable::majorVersion, quint8(5));
+ AreaAllocatorTable::put(data, AreaAllocatorTable::minorVersion, quint8(12));
+ AreaAllocatorTable::put(data, AreaAllocatorTable::width, quint32(m_size.width()));
+ AreaAllocatorTable::put(data, AreaAllocatorTable::height, quint32(m_size.height()));
+
+ data += AreaAllocatorTable::HeaderSize;
+ for (QSGAreaAllocatorNode *node : nodesToProcess) {
+ AreaAllocatorTable::put(data, AreaAllocatorTable::split, qint32(node->split));
+ AreaAllocatorTable::put(data, AreaAllocatorTable::splitType, quint32(node->splitType));
+
+ quint8 flags =
+ (node->isOccupied ? AreaAllocatorTable::IsOccupied : 0)
+ | (node->left != nullptr ? AreaAllocatorTable::HasLeft : 0)
+ | (node->right != nullptr ? AreaAllocatorTable::HasRight : 0);
+ AreaAllocatorTable::put(data, AreaAllocatorTable::flags, flags);
+ data += AreaAllocatorTable::NodeSize;
+ }
+
+ return ret;
+}
+
+const char *QSGAreaAllocator::deserialize(const char *data, int size)
+{
+ if (uint(size) < AreaAllocatorTable::HeaderSize) {
+ qWarning("QSGAreaAllocator::deserialize: Data not long enough to fit header");
+ return nullptr;
+ }
+
+ const char *end = data + size;
+
+ quint8 majorVersion = AreaAllocatorTable::fetch<quint8>(data, AreaAllocatorTable::majorVersion);
+ quint8 minorVersion = AreaAllocatorTable::fetch<quint8>(data, AreaAllocatorTable::minorVersion);
+ if (majorVersion != 5 || minorVersion != 12) {
+ qWarning("Unrecognized version %d.%d of QSGAreaAllocator",
+ majorVersion,
+ minorVersion);
+ return nullptr;
+ }
+
+ m_size = QSize(AreaAllocatorTable::fetch<quint32>(data, AreaAllocatorTable::width),
+ AreaAllocatorTable::fetch<quint32>(data, AreaAllocatorTable::height));
+
+ Q_ASSERT(m_root != nullptr);
+ Q_ASSERT(m_root->left == nullptr);
+ Q_ASSERT(m_root->right == nullptr);
+
+ QStack<QSGAreaAllocatorNode *> nodes;
+ nodes.push(m_root);
+
+ data += AreaAllocatorTable::HeaderSize;
+ while (!nodes.isEmpty()) {
+ if (data + AreaAllocatorTable::NodeSize > end) {
+ qWarning("QSGAreaAllocator::deseriable: Data not long enough for nodes");
+ return nullptr;
+ }
+
+ QSGAreaAllocatorNode *node = nodes.pop();
+
+ node->split = AreaAllocatorTable::fetch<qint32>(data, AreaAllocatorTable::split);
+ node->splitType = SplitType(AreaAllocatorTable::fetch<quint32>(data, AreaAllocatorTable::splitType));
+
+ quint8 flags = AreaAllocatorTable::fetch<quint8>(data, AreaAllocatorTable::flags);
+ node->isOccupied = flags & AreaAllocatorTable::IsOccupied;
+
+ if (flags & AreaAllocatorTable::HasLeft) {
+ node->left = new QSGAreaAllocatorNode(node);
+ nodes.push(node->left);
+ }
+
+ if (flags & AreaAllocatorTable::HasRight) {
+ node->right = new QSGAreaAllocatorNode(node);
+ nodes.push(node->right);
+ }
+
+ data += AreaAllocatorTable::NodeSize;
+ }
+
+ return data;
+}
+
QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/util/qsgareaallocator_p.h b/src/quick/scenegraph/util/qsgareaallocator_p.h
index 8bc05a5a5b..300a8128c0 100644
--- a/src/quick/scenegraph/util/qsgareaallocator_p.h
+++ b/src/quick/scenegraph/util/qsgareaallocator_p.h
@@ -69,6 +69,10 @@ public:
bool deallocate(const QRect &rect);
bool isEmpty() const { return m_root == nullptr; }
QSize size() const { return m_size; }
+
+ QByteArray serialize();
+ const char *deserialize(const char *data, int size);
+
private:
bool allocateInNode(const QSize &size, QPoint &result, const QRect &currentRect, QSGAreaAllocatorNode *node);
bool deallocateInNode(const QPoint &pos, QSGAreaAllocatorNode *node);
diff --git a/src/quick/scenegraph/util/qsgatlastexture.cpp b/src/quick/scenegraph/util/qsgatlastexture.cpp
index 7608a81ddc..66c6d3a882 100644
--- a/src/quick/scenegraph/util/qsgatlastexture.cpp
+++ b/src/quick/scenegraph/util/qsgatlastexture.cpp
@@ -143,11 +143,11 @@ QSGTexture *Manager::create(const QImage &image, bool hasAlphaChannel)
QSGTexture *Manager::create(const QSGCompressedTextureFactory *factory)
{
QSGTexture *t = nullptr;
- if (!qsgEnableCompressedAtlas() || !factory->m_textureData || !factory->m_textureData->isValid())
+ if (!qsgEnableCompressedAtlas() || !factory->m_textureData.isValid())
return t;
// TODO: further abstract the atlas and remove this restriction
- unsigned int format = factory->m_textureData->format;
+ unsigned int format = factory->m_textureData.glInternalFormat();
switch (format) {
case QOpenGLTexture::RGB8_ETC1:
case QOpenGLTexture::RGB8_ETC2:
@@ -158,15 +158,15 @@ QSGTexture *Manager::create(const QSGCompressedTextureFactory *factory)
return t;
}
- QSize size = factory->m_textureData->size;
+ QSize size = factory->m_textureData.size();
if (size.width() < m_atlas_size_limit && size.height() < m_atlas_size_limit) {
QHash<unsigned int, QSGCompressedAtlasTexture::Atlas*>::iterator i = m_atlases.find(format);
if (i == m_atlases.end())
i = m_atlases.insert(format, new QSGCompressedAtlasTexture::Atlas(m_atlas_size, format));
// must be multiple of 4
QSize paddedSize(((size.width() + 3) / 4) * 4, ((size.height() + 3) / 4) * 4);
- QByteArray data = factory->m_textureData->data;
- t = i.value()->create(data, factory->m_textureData->sizeInBytes(), factory->m_textureData->dataOffset, size, paddedSize);
+ QByteArray data = factory->m_textureData.data();
+ t = i.value()->create(data, factory->m_textureData.dataLength(), factory->m_textureData.dataOffset(), size, paddedSize);
}
return t;
}
@@ -351,19 +351,6 @@ Texture *Atlas::create(const QImage &image)
return nullptr;
}
-static void swizzleBGRAToRGBA(QImage *image)
-{
- const int width = image->width();
- const int height = image->height();
- uint *p = (uint *) image->bits();
- int stride = image->bytesPerLine() / 4;
- for (int i = 0; i < height; ++i) {
- for (int x = 0; x < width; ++x)
- p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);
- p += stride;
- }
-}
-
void Atlas::upload(Texture *texture)
{
const QImage &image = texture->image();
@@ -395,7 +382,7 @@ void Atlas::upload(Texture *texture)
}
if (m_externalFormat == GL_RGBA)
- swizzleBGRAToRGBA(&tmp);
+ tmp = std::move(tmp).convertToFormat(QImage::Format_RGBA8888_Premultiplied);
QOpenGLContext::currentContext()->functions()->glTexSubImage2D(GL_TEXTURE_2D, 0,
r.x(), r.y(), r.width(), r.height(),
m_externalFormat, GL_UNSIGNED_BYTE, tmp.constBits());
diff --git a/src/quick/scenegraph/util/qsgdepthstencilbuffer.cpp b/src/quick/scenegraph/util/qsgdepthstencilbuffer.cpp
index 56508af152..94912778f8 100644
--- a/src/quick/scenegraph/util/qsgdepthstencilbuffer.cpp
+++ b/src/quick/scenegraph/util/qsgdepthstencilbuffer.cpp
@@ -57,20 +57,34 @@ QSGDepthStencilBuffer::~QSGDepthStencilBuffer()
m_manager->m_buffers.remove(m_format);
}
+#ifndef GL_DEPTH_STENCIL_ATTACHMENT
+#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
+#endif
+
void QSGDepthStencilBuffer::attach()
{
+#ifndef Q_OS_WASM
m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, m_depthBuffer);
m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, m_stencilBuffer);
+#else
+ m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
+ GL_RENDERBUFFER, m_stencilBuffer);
+#endif
}
void QSGDepthStencilBuffer::detach()
{
+#ifndef Q_OS_WASM
m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, 0);
m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
GL_RENDERBUFFER, 0);
+#else
+ m_functions.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
+ GL_RENDERBUFFER, 0);
+#endif
}
#ifndef GL_DEPTH24_STENCIL8_OES
@@ -81,12 +95,17 @@ void QSGDepthStencilBuffer::detach()
#define GL_DEPTH_COMPONENT24_OES 0x81A6
#endif
+#ifndef GL_DEPTH_STENCIL
+#define GL_DEPTH_STENCIL 0x84F9
+#endif
+
QSGDefaultDepthStencilBuffer::QSGDefaultDepthStencilBuffer(QOpenGLContext *context, const Format &format)
: QSGDepthStencilBuffer(context, format)
{
const GLsizei width = format.size.width();
const GLsizei height = format.size.height();
+#ifndef Q_OS_WASM
if (format.attachments == (DepthAttachment | StencilAttachment)
&& m_functions.hasOpenGLExtension(QOpenGLExtensions::PackedDepthStencil))
{
@@ -138,6 +157,12 @@ QSGDefaultDepthStencilBuffer::QSGDefaultDepthStencilBuffer(QOpenGLContext *conte
m_functions.glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, width, height);
}
}
+#else
+ m_functions.glGenRenderbuffers(1, &m_depthBuffer);
+ m_functions.glBindRenderbuffer(GL_RENDERBUFFER, m_depthBuffer);
+ m_functions.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, width, height);
+ m_stencilBuffer = m_depthBuffer;
+#endif
}
QSGDefaultDepthStencilBuffer::~QSGDefaultDepthStencilBuffer()
diff --git a/src/quick/scenegraph/util/qsgengine.h b/src/quick/scenegraph/util/qsgengine.h
index e9e01dc710..e48b7784ae 100644
--- a/src/quick/scenegraph/util/qsgengine.h
+++ b/src/quick/scenegraph/util/qsgengine.h
@@ -66,6 +66,7 @@ public:
TextureIsOpaque = 0x0010
};
Q_DECLARE_FLAGS(CreateTextureOptions, CreateTextureOption)
+ Q_FLAG(CreateTextureOptions)
explicit QSGEngine(QObject *parent = nullptr);
~QSGEngine() override;
diff --git a/src/quick/scenegraph/util/qsgtexture.cpp b/src/quick/scenegraph/util/qsgtexture.cpp
index fea92a5121..982d05691d 100644
--- a/src/quick/scenegraph/util/qsgtexture.cpp
+++ b/src/quick/scenegraph/util/qsgtexture.cpp
@@ -659,17 +659,6 @@ QSGPlainTexture::~QSGPlainTexture()
#endif
}
-void qsg_swizzleBGRAToRGBA(QImage *image)
-{
- const int width = image->width();
- const int height = image->height();
- for (int i = 0; i < height; ++i) {
- uint *p = (uint *) image->scanLine(i);
- for (int x = 0; x < width; ++x)
- p[x] = ((p[x] << 16) & 0xff0000) | ((p[x] >> 16) & 0xff) | (p[x] & 0xff00ff00);
- }
-}
-
void QSGPlainTexture::setImage(const QImage &image)
{
m_image = image;
@@ -841,7 +830,7 @@ void QSGPlainTexture::bind()
internalFormat = GL_RGBA;
#endif
} else {
- qsg_swizzleBGRAToRGBA(&tmp);
+ tmp = std::move(tmp).convertToFormat(QImage::Format_RGBA8888_Premultiplied);
}
qint64 swizzleTime = 0;
diff --git a/src/quick/scenegraph/util/qsgtexturereader.cpp b/src/quick/scenegraph/util/qsgtexturereader.cpp
index 8e95f27120..5e12ca4035 100644
--- a/src/quick/scenegraph/util/qsgtexturereader.cpp
+++ b/src/quick/scenegraph/util/qsgtexturereader.cpp
@@ -38,36 +38,40 @@
****************************************************************************/
#include "qsgtexturereader_p.h"
-
-#include <private/qtquickglobal_p.h>
-
-#include <private/qsgtexturefilehandler_p.h>
+#include <private/qtexturefilereader_p.h>
#if QT_CONFIG(opengl)
-#include <private/qsgpkmhandler_p.h>
-#include <private/qsgktxhandler_p.h>
+#include <private/qsgcompressedtexture_p.h>
#endif
-#include <QFileInfo>
-
QT_BEGIN_NAMESPACE
QSGTextureReader::QSGTextureReader(QIODevice *device, const QString &fileName)
- : m_device(device), m_fileInfo(fileName)
{
+#if QT_CONFIG(opengl)
+ m_reader = new QTextureFileReader(device, fileName);
+#else
+ Q_UNUSED(device);
+ Q_UNUSED(fileName);
+#endif
}
QSGTextureReader::~QSGTextureReader()
{
- delete m_handler;
+ delete m_reader;
}
QQuickTextureFactory *QSGTextureReader::read()
{
#if QT_CONFIG(opengl)
- if (!isTexture())
+ if (!m_reader)
+ return nullptr;
+
+ QTextureFileData texData = m_reader->read();
+ if (!texData.isValid())
return nullptr;
- return m_handler->read();
+
+ return new QSGCompressedTextureFactory(texData);
#else
return nullptr;
#endif
@@ -75,41 +79,12 @@ QQuickTextureFactory *QSGTextureReader::read()
bool QSGTextureReader::isTexture()
{
-#if QT_CONFIG(opengl)
- if (!checked) {
- checked = true;
- if (!init())
- return false;
-
- QByteArray headerBlock = m_device->peek(64);
- QByteArray suffix = m_fileInfo.suffix().toLower().toLatin1();
- QByteArray logName = m_fileInfo.fileName().toUtf8();
-
- // Currently the handlers are hardcoded; later maybe a list of plugins
- if (QSGPkmHandler::canRead(suffix, headerBlock)) {
- m_handler = new QSGPkmHandler(m_device, logName);
- } else if (QSGKtxHandler::canRead(suffix, headerBlock)) {
- m_handler = new QSGKtxHandler(m_device, logName);
- }
- // else if OtherHandler::canRead() ...etc.
- }
- return (m_handler != nullptr);
-#else
- return false;
-#endif
+ return m_reader ? m_reader->canRead() : false;
}
QList<QByteArray> QSGTextureReader::supportedFileFormats()
{
- // Hardcoded for now
- return {QByteArrayLiteral("pkm"), QByteArrayLiteral("ktx")};
-}
-
-bool QSGTextureReader::init()
-{
- if (!m_device)
- return false;
- return m_device->isReadable();
+ return QTextureFileReader::supportedFileFormats();
}
QT_END_NAMESPACE
diff --git a/src/quick/scenegraph/util/qsgtexturereader_p.h b/src/quick/scenegraph/util/qsgtexturereader_p.h
index 19e33bf5c3..20c17fce50 100644
--- a/src/quick/scenegraph/util/qsgtexturereader_p.h
+++ b/src/quick/scenegraph/util/qsgtexturereader_p.h
@@ -58,7 +58,7 @@ QT_BEGIN_NAMESPACE
class QIODevice;
class QQuickTextureFactory;
-class QSGTextureFileHandler;
+class QTextureFileReader;
class QSGTextureReader
{
@@ -75,11 +75,7 @@ public:
static QList<QByteArray> supportedFileFormats();
private:
- bool init();
- QIODevice *m_device = nullptr;
- QFileInfo m_fileInfo;
- QSGTextureFileHandler *m_handler = nullptr;
- bool checked = false;
+ QTextureFileReader *m_reader = nullptr;
};
QT_END_NAMESPACE
diff --git a/src/quick/util/qquickanimation.cpp b/src/quick/util/qquickanimation.cpp
index 9ee1a323e5..02be9daac0 100644
--- a/src/quick/util/qquickanimation.cpp
+++ b/src/quick/util/qquickanimation.cpp
@@ -234,6 +234,27 @@ QQmlProperty QQuickAbstractAnimationPrivate::createProperty(QObject *obj, const
The corresponding handler is \c onStopped.
*/
+/*!
+ \qmlsignal QtQuick::Animation::finished()
+ \since 5.12
+
+ This signal is emitted when the animation has finished naturally.
+
+ It is not emitted when \l running is set to \c false, nor for animations whose
+ \l loops property is set to \c Animation.Infinite.
+
+ In addition, it is only emitted for top-level, standalone animations. It
+ will not be emitted for animations in a Behavior or Transition, or
+ animations that are part of an animation group.
+
+ If \l alwaysRunToEnd is true, this signal will not be emitted until the
+ animation has completed its current iteration.
+
+ The corresponding handler is \c onFinished.
+
+ \sa stopped(), started(), running
+*/
+
void QQuickAbstractAnimation::setRunning(bool r)
{
Q_D(QQuickAbstractAnimation);
@@ -656,6 +677,7 @@ void QQuickAbstractAnimationPrivate::animationFinished(QAbstractAnimationJob*)
if (loopCount != 1)
animationInstance->setLoopCount(loopCount);
}
+ emit q->finished();
}
QQuickAbstractAnimation::ThreadingModel QQuickAbstractAnimation::threadingModel() const
diff --git a/src/quick/util/qquickanimation_p.h b/src/quick/util/qquickanimation_p.h
index 2293f2597f..746cb938bd 100644
--- a/src/quick/util/qquickanimation_p.h
+++ b/src/quick/util/qquickanimation_p.h
@@ -126,6 +126,7 @@ Q_SIGNALS:
void pausedChanged(bool);
void alwaysRunToEndChanged(bool);
void loopCountChanged(int);
+ Q_REVISION(12) void finished();
public Q_SLOTS:
void restart();
diff --git a/src/quick/util/qquickglobal.cpp b/src/quick/util/qquickglobal.cpp
index 7fa20636ec..5337bfd640 100644
--- a/src/quick/util/qquickglobal.cpp
+++ b/src/quick/util/qquickglobal.cpp
@@ -388,7 +388,7 @@ public:
float matVals[16];
QV4::ScopedValue v(scope);
for (quint32 i = 0; i < 16; ++i) {
- v = array->getIndexed(i);
+ v = array->get(i);
if (!v->isNumber())
return QMatrix4x4();
matVals[i] = v->asDouble();
diff --git a/src/quick/util/qquickimageprovider.cpp b/src/quick/util/qquickimageprovider.cpp
index f7c8724318..ced981de3e 100644
--- a/src/quick/util/qquickimageprovider.cpp
+++ b/src/quick/util/qquickimageprovider.cpp
@@ -39,8 +39,10 @@
#include "qquickimageprovider.h"
+#include "qquickimageprovider_p.h"
#include "qquickpixmapcache_p.h"
#include <QtQuick/private/qsgcontext_p.h>
+#include <private/qqmlglobal_p.h>
QT_BEGIN_NAMESPACE
@@ -160,7 +162,10 @@ QQuickTextureFactory *QQuickTextureFactory::textureFactoryForImage(const QImage
Constructs the image response
*/
QQuickImageResponse::QQuickImageResponse()
+ : QObject(*(new QQuickImageResponsePrivate))
{
+ qmlobject_connect(this, QQuickImageResponse, SIGNAL(finished()),
+ this, QQuickImageResponse, SLOT(_q_finished()));
}
/*!
@@ -329,8 +334,6 @@ void QQuickImageResponse::cancel()
\c cache property to \c false for the relevant \l Image, \l BorderImage or
\l AnimatedImage object.
- The \l {Qt Quick 1} version of this class is named QDeclarativeImageProvider.
-
\sa QQmlEngine::addImageProvider()
*/
diff --git a/src/quick/util/qquickimageprovider.h b/src/quick/util/qquickimageprovider.h
index 4f8193789a..82d0501697 100644
--- a/src/quick/util/qquickimageprovider.h
+++ b/src/quick/util/qquickimageprovider.h
@@ -69,6 +69,8 @@ public:
static QQuickTextureFactory *textureFactoryForImage(const QImage &image);
};
+class QQuickImageResponsePrivate;
+
class Q_QUICK_EXPORT QQuickImageResponse : public QObject
{
Q_OBJECT
@@ -84,6 +86,10 @@ public Q_SLOTS:
Q_SIGNALS:
void finished();
+
+private:
+ Q_DECLARE_PRIVATE(QQuickImageResponse)
+ Q_PRIVATE_SLOT(d_func(), void _q_finished())
};
class Q_QUICK_EXPORT QQuickImageProvider : public QQmlImageProviderBase
diff --git a/src/quick/handlers/qquickhandlersmodule_p.h b/src/quick/util/qquickimageprovider_p.h
index 7eb8d39b98..b5baf79319 100644
--- a/src/quick/handlers/qquickhandlersmodule_p.h
+++ b/src/quick/util/qquickimageprovider_p.h
@@ -37,8 +37,8 @@
**
****************************************************************************/
-#ifndef QQUICKHANDLERSMODULE_P_H
-#define QQUICKHANDLERSMODULE_P_H
+#ifndef QQUICKQQUICKIMAGEPROVIDER_P_H
+#define QQUICKQQUICKIMAGEPROVIDER_P_H
//
// W A R N I N G
@@ -51,18 +51,22 @@
// We mean it.
//
-#include <qqml.h>
#include <private/qtquickglobal_p.h>
+#include <private/qobject_p.h>
+#include <qquickimageprovider.h>
QT_BEGIN_NAMESPACE
-class Q_QUICK_PRIVATE_EXPORT QQuickHandlersModule
+class QQuickImageResponsePrivate : public QObjectPrivate
{
+ Q_DECLARE_PUBLIC(QQuickImageResponse)
public:
- static void defineModule();
+ bool finished = false;
+
+ void _q_finished() { finished = true; }
};
-QT_END_NAMESPACE
-#endif // QQUICKHANDLERSMODULE_P_H
+QT_END_NAMESPACE
+#endif // QQUICKQQUICKIMAGEPROVIDER_P_H
diff --git a/src/quick/util/qquickpixmapcache.cpp b/src/quick/util/qquickpixmapcache.cpp
index 4237ec3edf..0dd2a88ca1 100644
--- a/src/quick/util/qquickpixmapcache.cpp
+++ b/src/quick/util/qquickpixmapcache.cpp
@@ -39,6 +39,7 @@
#include "qquickpixmapcache_p.h"
#include <qquickimageprovider.h>
+#include "qquickimageprovider_p.h"
#include <qqmlengine.h>
#include <private/qqmlglobal_p.h>
@@ -179,6 +180,8 @@ public:
QQuickPixmapReaderThreadObject(QQuickPixmapReader *);
void processJobs();
bool event(QEvent *e) override;
+public slots:
+ void asyncResponseFinished(QQuickImageResponse *response);
private slots:
void networkRequestDone();
void asyncResponseFinished();
@@ -613,10 +616,15 @@ void QQuickPixmapReaderThreadObject::networkRequestDone()
#endif
}
+void QQuickPixmapReaderThreadObject::asyncResponseFinished(QQuickImageResponse *response)
+{
+ reader->asyncResponseFinished(response);
+}
+
void QQuickPixmapReaderThreadObject::asyncResponseFinished()
{
QQuickImageResponse *response = static_cast<QQuickImageResponse *>(sender());
- reader->asyncResponseFinished(response);
+ asyncResponseFinished(response);
}
void QQuickPixmapReader::processJobs()
@@ -800,7 +808,14 @@ void QQuickPixmapReader::processJob(QQuickPixmapReply *runningJob, const QUrl &u
response = asyncProvider->requestImageResponse(imageId(url), runningJob->requestSize);
}
- QObject::connect(response, SIGNAL(finished()), threadObject, SLOT(asyncResponseFinished()));
+ // Might be that the async provider was so quick it emitted the signal before we
+ // could connect to it.
+ if (static_cast<QQuickImageResponsePrivate*>(QObjectPrivate::get(response))->finished) {
+ QMetaObject::invokeMethod(threadObject, "asyncResponseFinished",
+ Qt::QueuedConnection, Q_ARG(QQuickImageResponse*, response));
+ } else {
+ QObject::connect(response, SIGNAL(finished()), threadObject, SLOT(asyncResponseFinished()));
+ }
asyncResponses.insert(response, runningJob);
break;
diff --git a/src/quick/util/qquickprofiler.cpp b/src/quick/util/qquickprofiler.cpp
index bd9f04e562..decc6eac31 100644
--- a/src/quick/util/qquickprofiler.cpp
+++ b/src/quick/util/qquickprofiler.cpp
@@ -116,9 +116,8 @@ void QQuickProfiler::stopProfilingImpl()
m_data.clear();
}
-void QQuickProfiler::reportDataImpl(bool trackLocations)
+void QQuickProfiler::reportDataImpl()
{
- Q_UNUSED(trackLocations);
QMutexLocker lock(&m_dataMutex);
emit dataReady(m_data);
m_data.clear();
diff --git a/src/quick/util/qquickprofiler_p.h b/src/quick/util/qquickprofiler_p.h
index d699ddf371..28b058c2e8 100644
--- a/src/quick/util/qquickprofiler_p.h
+++ b/src/quick/util/qquickprofiler_p.h
@@ -357,7 +357,7 @@ protected:
void startProfilingImpl(quint64 features);
void stopProfilingImpl();
- void reportDataImpl(bool trackLocations);
+ void reportDataImpl();
void setTimer(const QElapsedTimer &t);
};
diff --git a/src/quick/util/qquickpropertychanges.cpp b/src/quick/util/qquickpropertychanges.cpp
index a3a598621f..8e2ac32ace 100644
--- a/src/quick/util/qquickpropertychanges.cpp
+++ b/src/quick/util/qquickpropertychanges.cpp
@@ -208,7 +208,7 @@ public:
bool isExplicit : 1;
void decode();
- void decodeBinding(const QString &propertyPrefix, const QV4::CompiledData::Unit *qmlUnit, const QV4::CompiledData::Binding *binding);
+ void decodeBinding(const QString &propertyPrefix, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &qmlUnit, const QV4::CompiledData::Binding *binding);
class ExpressionChange {
public:
@@ -236,19 +236,19 @@ public:
QQmlProperty property(const QString &);
};
-void QQuickPropertyChangesParser::verifyList(const QV4::CompiledData::Unit *qmlUnit, const QV4::CompiledData::Binding *binding)
+void QQuickPropertyChangesParser::verifyList(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QV4::CompiledData::Binding *binding)
{
if (binding->type == QV4::CompiledData::Binding::Type_Object) {
- error(qmlUnit->objectAt(binding->value.objectIndex), QQuickPropertyChanges::tr("PropertyChanges does not support creating state-specific objects."));
+ error(compilationUnit->objectAt(binding->value.objectIndex), QQuickPropertyChanges::tr("PropertyChanges does not support creating state-specific objects."));
return;
}
if (binding->type == QV4::CompiledData::Binding::Type_GroupProperty
|| binding->type == QV4::CompiledData::Binding::Type_AttachedProperty) {
- const QV4::CompiledData::Object *subObj = qmlUnit->objectAt(binding->value.objectIndex);
+ const QV4::CompiledData::Object *subObj = compilationUnit->objectAt(binding->value.objectIndex);
const QV4::CompiledData::Binding *subBinding = subObj->bindingTable();
for (quint32 i = 0; i < subObj->nBindings; ++i, ++subBinding) {
- verifyList(qmlUnit, subBinding);
+ verifyList(compilationUnit, subBinding);
}
}
}
@@ -259,26 +259,26 @@ void QQuickPropertyChangesPrivate::decode()
return;
for (const QV4::CompiledData::Binding *binding : qAsConst(bindings))
- decodeBinding(QString(), compilationUnit->data, binding);
+ decodeBinding(QString(), compilationUnit, binding);
bindings.clear();
decoded = true;
}
-void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix, const QV4::CompiledData::Unit *qmlUnit, const QV4::CompiledData::Binding *binding)
+void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QV4::CompiledData::Binding *binding)
{
Q_Q(QQuickPropertyChanges);
- QString propertyName = propertyPrefix + qmlUnit->stringAt(binding->propertyNameIndex);
+ QString propertyName = propertyPrefix + compilationUnit->stringAt(binding->propertyNameIndex);
if (binding->type == QV4::CompiledData::Binding::Type_GroupProperty
|| binding->type == QV4::CompiledData::Binding::Type_AttachedProperty) {
QString pre = propertyName + QLatin1Char('.');
- const QV4::CompiledData::Object *subObj = qmlUnit->objectAt(binding->value.objectIndex);
+ const QV4::CompiledData::Object *subObj = compilationUnit->objectAt(binding->value.objectIndex);
const QV4::CompiledData::Binding *subBinding = subObj->bindingTable();
for (quint32 i = 0; i < subObj->nBindings; ++i, ++subBinding) {
- decodeBinding(pre, qmlUnit, subBinding);
+ decodeBinding(pre, compilationUnit, subBinding);
}
return;
}
@@ -298,7 +298,7 @@ void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix,
}
}
- if (binding->type == QV4::CompiledData::Binding::Type_Script || binding->containsTranslations()) {
+ if (binding->type == QV4::CompiledData::Binding::Type_Script || binding->isTranslationBinding()) {
QUrl url = QUrl();
int line = -1;
int column = -1;
@@ -313,8 +313,8 @@ void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix,
QString expression;
QQmlBinding::Identifier id = QQmlBinding::Invalid;
- if (!binding->containsTranslations()) {
- expression = binding->valueAsString(qmlUnit);
+ if (!binding->isTranslationBinding()) {
+ expression = binding->valueAsString(compilationUnit.data());
id = binding->value.compiledScriptIndex;
}
expressions << ExpressionChange(propertyName, binding, id, expression, url, line, column);
@@ -328,10 +328,10 @@ void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix,
case QV4::CompiledData::Binding::Type_TranslationById:
Q_UNREACHABLE();
case QV4::CompiledData::Binding::Type_String:
- var = binding->valueAsString(qmlUnit);
+ var = binding->valueAsString(compilationUnit.data());
break;
case QV4::CompiledData::Binding::Type_Number:
- var = binding->valueAsNumber();
+ var = binding->valueAsNumber(compilationUnit->constants);
break;
case QV4::CompiledData::Binding::Type_Boolean:
var = binding->valueAsBoolean();
@@ -343,13 +343,13 @@ void QQuickPropertyChangesPrivate::decodeBinding(const QString &propertyPrefix,
properties << qMakePair(propertyName, var);
}
-void QQuickPropertyChangesParser::verifyBindings(const QV4::CompiledData::Unit *qmlUnit, const QList<const QV4::CompiledData::Binding *> &props)
+void QQuickPropertyChangesParser::verifyBindings(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &props)
{
for (int ii = 0; ii < props.count(); ++ii)
- verifyList(qmlUnit, props.at(ii));
+ verifyList(compilationUnit, props.at(ii));
}
-void QQuickPropertyChangesParser::applyBindings(QObject *obj, QV4::CompiledData::CompilationUnit *compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings)
+void QQuickPropertyChangesParser::applyBindings(QObject *obj, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings)
{
QQuickPropertyChangesPrivate *p =
static_cast<QQuickPropertyChangesPrivate *>(QObjectPrivate::get(obj));
@@ -468,7 +468,7 @@ QQuickPropertyChanges::ActionList QQuickPropertyChanges::actions()
QQmlContextData *context = QQmlContextData::get(qmlContext(this));
QQmlBinding *newBinding = nullptr;
- if (e.binding && e.binding->containsTranslations()) {
+ if (e.binding && e.binding->isTranslationBinding()) {
newBinding = QQmlBinding::createTranslationBinding(d->compilationUnit, e.binding, object(), context);
} else if (e.id != QQmlBinding::Invalid) {
QV4::Scope scope(qmlEngine(this)->handle());
diff --git a/src/quick/util/qquickpropertychanges_p.h b/src/quick/util/qquickpropertychanges_p.h
index 35b37e84cb..74fe511d6e 100644
--- a/src/quick/util/qquickpropertychanges_p.h
+++ b/src/quick/util/qquickpropertychanges_p.h
@@ -101,10 +101,10 @@ public:
QQuickPropertyChangesParser()
: QQmlCustomParser(AcceptsAttachedProperties) {}
- void verifyList(const QV4::CompiledData::Unit *qmlUnit, const QV4::CompiledData::Binding *binding);
+ void verifyList(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QV4::CompiledData::Binding *binding);
- void verifyBindings(const QV4::CompiledData::Unit *qmlUnit, const QList<const QV4::CompiledData::Binding *> &props) override;
- void applyBindings(QObject *obj, QV4::CompiledData::CompilationUnit *compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings) override;
+ void verifyBindings(const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &props) override;
+ void applyBindings(QObject *obj, const QQmlRefPointer<QV4::CompiledData::CompilationUnit> &compilationUnit, const QList<const QV4::CompiledData::Binding *> &bindings) override;
};
diff --git a/src/quick/util/qquickstate.cpp b/src/quick/util/qquickstate.cpp
index b953ad1c7f..3ca6440784 100644
--- a/src/quick/util/qquickstate.cpp
+++ b/src/quick/util/qquickstate.cpp
@@ -222,7 +222,7 @@ bool QQuickState::isWhenKnown() const
QQmlBinding *QQuickState::when() const
{
Q_D(const QQuickState);
- return d->when;
+ return d->when.data();
}
void QQuickState::setWhen(QQmlBinding *when)
diff --git a/src/quick/util/qquickstate_p_p.h b/src/quick/util/qquickstate_p_p.h
index f1bc24c558..61472b4d06 100644
--- a/src/quick/util/qquickstate_p_p.h
+++ b/src/quick/util/qquickstate_p_p.h
@@ -203,12 +203,12 @@ class QQuickStatePrivate : public QObjectPrivate
public:
QQuickStatePrivate()
- : when(nullptr), named(false), inState(false), group(nullptr) {}
+ : named(false), inState(false), group(nullptr) {}
typedef QList<QQuickSimpleAction> SimpleActionList;
QString name;
- QQmlBinding *when;
+ QQmlBinding::Ptr when;
bool named;
struct OperationGuard : public QQmlGuard<QQuickStateOperation>
diff --git a/src/quick/util/qquickstategroup.cpp b/src/quick/util/qquickstategroup.cpp
index c852c16509..d8daec2f07 100644
--- a/src/quick/util/qquickstategroup.cpp
+++ b/src/quick/util/qquickstategroup.cpp
@@ -302,10 +302,19 @@ void QQuickStateGroup::componentComplete()
Q_D(QQuickStateGroup);
d->componentComplete = true;
+ QVarLengthArray<QString, 4> names;
+ names.reserve(d->states.count());
for (int ii = 0; ii < d->states.count(); ++ii) {
QQuickState *state = d->states.at(ii);
if (!state->isNamed())
state->setName(QLatin1String("anonymousState") + QString::number(++d->unnamedCount));
+
+ const QString stateName = state->name();
+ if (names.contains(stateName)) {
+ qmlWarning(state->parent()) << "Found duplicate state name: " << stateName;
+ } else {
+ names.append(std::move(stateName));
+ }
}
if (d->updateAutoState()) {
diff --git a/src/quick/util/qquicksvgparser.cpp b/src/quick/util/qquicksvgparser.cpp
index 2bf9c121d3..0687913565 100644
--- a/src/quick/util/qquicksvgparser.cpp
+++ b/src/quick/util/qquicksvgparser.cpp
@@ -280,11 +280,8 @@ bool QQuickSvgParser::parsePathDataFast(const QString &dataStr, QPainterPath &pa
++str;
QChar pathElem = *str;
++str;
- QChar endc = *end;
- *const_cast<QChar *>(end) = 0; // parseNumbersArray requires 0-termination that QStringRef cannot guarantee
QVarLengthArray<qreal, 8> arg;
parseNumbersArray(str, arg);
- *const_cast<QChar *>(end) = endc;
if (pathElem == QLatin1Char('z') || pathElem == QLatin1Char('Z'))
arg.append(0);//dummy
const qreal *num = arg.constData();
diff --git a/src/quick/util/qquicktransitionmanager.cpp b/src/quick/util/qquicktransitionmanager.cpp
index a1367249c6..e51de1a02a 100644
--- a/src/quick/util/qquicktransitionmanager.cpp
+++ b/src/quick/util/qquicktransitionmanager.cpp
@@ -91,10 +91,10 @@ void QQuickTransitionManager::complete()
{
d->applyBindings();
- for (int ii = 0; ii < d->completeList.count(); ++ii) {
- const QQmlProperty &prop = d->completeList.at(ii).property();
- prop.write(d->completeList.at(ii).value());
- }
+ // Explicitly take a copy in case the write action triggers a script that modifies the list.
+ QQuickTransitionManagerPrivate::SimpleActionList completeListCopy = d->completeList;
+ for (const QQuickSimpleAction &action : qAsConst(completeListCopy))
+ action.property().write(action.value());
d->completeList.clear();
@@ -131,7 +131,9 @@ void QQuickTransitionManager::transition(const QList<QQuickStateAction> &list,
{
cancel();
+ // The copy below is ON PURPOSE, because firing actions might involve scripts that modify the list.
QQuickStateOperation::ActionList applyList = list;
+
// Determine which actions are binding changes and disable any current bindings
for (const QQuickStateAction &action : qAsConst(applyList)) {
if (action.toBinding)
@@ -156,8 +158,7 @@ void QQuickTransitionManager::transition(const QList<QQuickStateAction> &list,
if (transition && !d->bindingsList.isEmpty()) {
// Apply all the property and binding changes
- for (int ii = 0; ii < applyList.size(); ++ii) {
- const QQuickStateAction &action = applyList.at(ii);
+ for (const QQuickStateAction &action : qAsConst(applyList)) {
if (action.toBinding) {
QQmlPropertyPrivate::setBinding(action.toBinding.data(), QQmlPropertyPrivate::None, QQmlPropertyData::BypassInterceptor | QQmlPropertyData::DontRemoveBinding);
} else if (!action.event) {
@@ -170,17 +171,15 @@ void QQuickTransitionManager::transition(const QList<QQuickStateAction> &list,
}
}
- // Read all the end values for binding changes
- for (int ii = 0; ii < applyList.size(); ++ii) {
- QQuickStateAction *action = &applyList[ii];
- if (action->event) {
- action->event->saveTargetValues();
+ // Read all the end values for binding changes.
+ for (auto it = applyList.begin(), eit = applyList.end(); it != eit; ++it) {
+ if (it->event) {
+ it->event->saveTargetValues();
continue;
}
- const QQmlProperty &prop = action->property;
- if (action->toBinding || !action->toValue.isValid()) {
- action->toValue = prop.read();
- }
+ const QQmlProperty &prop = it->property;
+ if (it->toBinding || !it->toValue.isValid())
+ it->toValue = prop.read();
}
// Revert back to the original values
@@ -210,29 +209,20 @@ void QQuickTransitionManager::transition(const QList<QQuickStateAction> &list,
delete oldInstance;
// Modify the action list to remove actions handled in the transition
- for (int ii = 0; ii < applyList.count(); ++ii) {
- const QQuickStateAction &action = applyList.at(ii);
-
+ auto isHandledInTransition = [this, touched](const QQuickStateAction &action) {
if (action.event) {
-
- if (action.actionDone) {
- applyList.removeAt(ii);
- --ii;
- }
-
+ return action.actionDone;
} else {
-
if (touched.contains(action.property)) {
if (action.toValue != action.fromValue)
- d->completeList <<
- QQuickSimpleAction(action, QQuickSimpleAction::EndState);
-
- applyList.removeAt(ii);
- --ii;
+ d->completeList << QQuickSimpleAction(action, QQuickSimpleAction::EndState);
+ return true;
}
-
}
- }
+ return false;
+ };
+ auto newEnd = std::remove_if(applyList.begin(), applyList.end(), isHandledInTransition);
+ applyList.erase(newEnd, applyList.end());
}
// Any actions remaining have not been handled by the transition and should
@@ -270,12 +260,9 @@ void QQuickTransitionManager::cancel()
if (d->transitionInstance && d->transitionInstance->isRunning())
d->transitionInstance->stop();
- for(int i = 0; i < d->bindingsList.count(); ++i) {
- QQuickStateAction action = d->bindingsList[i];
+ for (const QQuickStateAction &action : qAsConst(d->bindingsList)) {
if (action.toBinding && action.deletableToBinding) {
QQmlPropertyPrivate::removeBinding(action.property);
- action.toBinding = nullptr;
- action.deletableToBinding = false;
} else if (action.event) {
//### what do we do here?
}
diff --git a/src/quick/util/qquickutilmodule.cpp b/src/quick/util/qquickutilmodule.cpp
index b2e5b84cf4..31d4d4c437 100644
--- a/src/quick/util/qquickutilmodule.cpp
+++ b/src/quick/util/qquickutilmodule.cpp
@@ -132,4 +132,7 @@ void QQuickUtilModule::defineModule()
qmlRegisterType<QQuickShortcut,9>("QtQuick", 2, 9, "Shortcut");
#endif
+
+ qmlRegisterUncreatableType<QQuickAbstractAnimation, 12>("QtQuick", 2, 12, "Animation",
+ QQuickAbstractAnimation::tr("Animation is an abstract class"));
}
diff --git a/src/quick/util/util.pri b/src/quick/util/util.pri
index edcb268cd9..c51f082d03 100644
--- a/src/quick/util/util.pri
+++ b/src/quick/util/util.pri
@@ -53,6 +53,7 @@ HEADERS += \
$$PWD/qquickfontloader_p.h \
$$PWD/qquickstyledtext_p.h \
$$PWD/qquickimageprovider.h \
+ $$PWD/qquickimageprovider_p.h \
$$PWD/qquicksvgparser_p.h \
$$PWD/qquickvaluetypes_p.h \
$$PWD/qquickanimator_p.h \