diff options
author | Arno Rehn <a.rehn@menlosystems.com> | 2022-09-23 16:31:47 +0200 |
---|---|---|
committer | Arno Rehn <a.rehn@menlosystems.com> | 2022-09-27 20:59:21 +0200 |
commit | 7a7051b58f78a85cc55aece7b8691583c33ac47e (patch) | |
tree | e5c8bef3bac3a8e6bbd60818fc7e2af6e01ba96e /src/corelib/doc/snippets | |
parent | 38f8d531a26720cbf5574f06481c58ef4dad7e4b (diff) |
QMetaType: Support custom unary converters with optional<To> return type
To indicate success of a conversion, the public API has previously only
supported registering member functions of the form To (From::*)(bool *).
When adding custom converters for types that cannot be modified, this is
usually not a possibility.
As an alternative, this patch adds support for std::optional in the
UnaryFunction overload of QMetaType::registerConverter. If the returned
optional has no value, the conversion is considered failed.
Task-number: QTBUG-92902
Change-Id: Ibac52d2cb9b5a2457081b4bebb0def1f03e3c55d
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
Diffstat (limited to 'src/corelib/doc/snippets')
-rw-r--r-- | src/corelib/doc/snippets/qmetatype/registerConverters.cpp | 8 |
1 files changed, 8 insertions, 0 deletions
diff --git a/src/corelib/doc/snippets/qmetatype/registerConverters.cpp b/src/corelib/doc/snippets/qmetatype/registerConverters.cpp index 5c5e76c7b0..f53d04b7a6 100644 --- a/src/corelib/doc/snippets/qmetatype/registerConverters.cpp +++ b/src/corelib/doc/snippets/qmetatype/registerConverters.cpp @@ -1,6 +1,7 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause +#include <QJsonObject> #include <QMetaType> #include <QString> @@ -50,5 +51,12 @@ int main() { QMetaType::registerConverter<CustomStringType, QString>([](const CustomStringType &str) { return QString::fromUtf8(str.data()); }); + QMetaType::registerConverter<QJsonValue, QPointF>( + [](const QJsonValue &value) -> std::optional<QPointF> { + const auto object = value.toObject(); + if (!object.contains("x") || !object.contains("y")) + return std::nullopt; // The conversion fails if the required properties are missing + return QPointF{object["x"].toDouble(), object["y"].toDouble()}; + }); //! [unaryfunc] } |